Thursday, 17 January 2019

Log actions performed by a user running a script

The following Google Apps Script code has been developed to provide a standalone function that you could include in your scripting projects to help determine which user ran it and what actions it has performed. It is one I hope to start embedding where suitable and is designed to output the information into a Google sheet - Date/Time, User, Action.

There have been a couple of instances where it would have been useful to know who and when a script was run, as part of diagnosing a fault. The function takes an input parameter of action which could simply be a variable with descriptive text at certain checkpoints in your script (particularly the start/end).
Screenshot of spreadsheet with logs from script
Example log output from script to spreadsheet

The code
We start by getting the email address of the person running the script ('getActiveUser' - a command also used in this blog post). We then get the relevant spreadsheet details as normal ('getSheetByName') looking for the name Log in my example.

We need to capture the date/time for the log so we create a date variable and format it ('formatDate'). All 3 items can now be wrapped up into an array (remember that action is an input parameter and so will be fed into the function when it is called from elsewhere in the script).

The final step is to 'appendRow' so that the information is added to the next available row in spreadsheet log. I have included a quick function to test logEvent at the end of the code for you.

Log event when running code.xslx

No comments:

Post a Comment