The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Track when a user logins

Linda Kendrick
Kilo Guru

Created a new u_user_login table that wanting to track everytime a user logs in. I need to run reports to see how many times a person/dept is logging inot the instance.

I created a business rule on the new table with the following settings:
When:after
Insert:yes
Active:yes
Script
var gr = new GlideRecord("u_user_login");

if (current.operation() == 'login')
{
gr.sys_created_by = event.parm1;
gr.sys_created_on = event.parm2;
}

I used the default columns that were created with the table as I just need to track the user and the date.
I am not sure if I am using the current.operation correctly and I am not seeing a record getting inserted into the new table.

11 REPLIES 11

Linda Kendrick
Kilo Guru

Correction: I put the Business Rule on the sysevent table not the new table i created.


Kostya
Mega Guru

current.operation() may return "update" or "insert".
You have to change the if to
if (current.operation() == 'insert' && current.name=='login')
and dont forget to initialize the GlideRecords and use insert().

Also, do not you the fields sys_created_by and sys_created_on, as they are used by the system and set automatically.
Create new fields instead, f.e.

if (current.operation() == 'insert' && current.name=='login')
var gr = new GlideRecord("u_user_login");
gr.initialize();
gr.u_user = event.parm1
gr.u_logged_in_at = current.parm1; // current because the rule runs on Event table
gr.insert();
}

Refer to https://wiki.servicenow.com/index.php?title=GlideRecord for more details


But be aware of this concept, because this would be executed every time the event is inserted. There may be veeery much events a day.


Hit the Thumb Icon and/or mark as Correct, if my answer was correct. So you help others to see correct responses and I get fame 🙂

Cheers,
Kostya

CapaJC
ServiceNow Employee
ServiceNow Employee

Here's how I would do this. There is already a "login" event that gets generated when a user logs in, and you can react to a specific event with a new Script Action you create. System Policy > Script Actions.

Parm 1 of the event is the user name, Parm 2 is the IP address.

Create a new Script Action that reacts to the "login" event. No condition. Make it active. Use a variant of the following in the script:



var userLogin = new GlideRecord("u_user_login");
userLogin.u_user_name = event.parm1; // works if u_user_name is just a String field to store User name
userLogin.u_user = event.user_id; // works if u_user is a reference field to the sys_user table
userLogin.u_when = event.sys_created_on; // works if u_when is a date/time field
userLogin.u_ip = event.parm2; // works if u_ip is a String field to store IP address
userLogin.insert();


I was able to get this option to work. thank you