Is it possible to export Google Apps Script Execution transcript - google-apps-script

I have a written a web Apps Script which is deployed to run in the context of user accessing the web app.
Is it possible to export web Apps Script's Execution Transcript programatically?

Not directly.
You won't get a full stack trace, but you can be meticulous with Logging everything you want to be notified with. At the end of the script you could extract the log and email that.
Logger.getLog();
If you really wanted to be fancy, there are a few implementations of custom Loggers which extent the standard Logger.log(). For instance if you had an object that every time you send a log message to it, it would time-stamp overall duration, time since last log and the message passed to it, all to Logger.log. Same object could have a getLog(0 method of its own which did extra stuff - should you wish.
There is a notable logger library at Google Apps Script Examples by Peter Herrmann which will also allow you to log to a spreadsheet.
But in short, no, you cannot export the execution log.

Related

How to debug or view logs in Google App Script fired from sheet

When developing Google Apps Scripts (specifically for Sheets in my case), you can use the Debug button to step through code and inspect variables, or you can use the Logger to output debug info.
What I can't figure out, however, is if there is any way to do these things when functions are triggered through the sheet itself. For example, from a custom menu item which fires a function, or an onEdit() trigger.
It makes it very difficult to debug issues because, as far as I can tell, GAS simply fails silently. Nothing useful appears in the browser JS console either.
I'm writing this answer as a community wiki, since the issue was resolved from the comments section, in order to provide a proper response to the question.
As mentioned in the comments, you can use the Apps Script execution log in the script editor. You can use either the Logger or console logging service.
In addition, to test a trigger function and check if there are any errors, you can do the following:
Since you're using onEdit trigger, edit a cell in the sheet.
Go to the Apps Script project.
If there are errors, you can view the logs in the "Executions" section and you'll find a list of executions which you can filter by Failed and Time out.
Reference:
Apps Script mechanisms for logging

How to visualise errors from doPost(e)?

I have been attempting to find a method to log any errors that occur after a doPost(e) method executes with Apps Script (using JS). The previously answered question regarding this topic mentioned StackDriver logging with reference to the old editor provided by Google. However, how do I access a similar function with the new editor?
For some more context, if I execute functions from script editor, the Google Sheet they are editing, or through a trigger, I am able to view the errors through the Execution Log tab. But for any calls made through doPost, I am unable to view the causes of error. How do I log these errors?
Edit: I believe there might be a slight misunderstanding. The programmed doPost(e) takes user input from a Telegram bot and responds accordingly. Till date, the bot has been functioning as designed; however, for future debugging I wish to be able to somehow see any caused errors. This would provide more information than simply a "Failed" in the execution log. Any help is appreciated.
Apps Script Logging
Note:
Error Reporting interface in the Developer Console is pretty much similar with option 2 so I will not provide any further example.
Sample WebApp Code:
function doGet(e) {
var params = JSON.stringify(e);
console.log(params);
}
Sample Request:
https://script.google.com/..../exec?username=sample2&password=1234
Option1: Check the built-in Apps Script execution log
You can check the logs when you open your script and go to Execution tab
You can also check the logs in https://script.google.com/home/executions
Option2: Using Cloud Logging interface in the Developer Console
Assuiming you already attached a standard GCP project with your script project
You can view Cloud logs and error reports in the Google Cloud Platform console
Under Log Fields -> Select Apps Script Function
It will display the results under Query Results Tab

Apps Script Activity Reporting/Visualization

I've been developing an apps script project for my company that tracks our time/expenses. I've structured the project like so:
The company has a paid Gsuite account that owns all the spreadsheets hosted on the company's google drive.
Each employee has their own "user" spreadsheet which is shared from the company Gsuite account with the employee's personal gmail account.
Each of the user spreadsheets has a container-bound script that accesses a central library script.
The library script allows us to update the script centrally and the effects are immediate for each user. It also prevents users from seeing the central script and meddling with it.
Each of the user container-bound scripts have installable triggers that are authorized by the company account so that the code being run has full authority to do what it needs to to the spreadsheets.
This setup has been working quite well for us with about 40 users. The drawback to this setup is that since all the script activity is run by the company account via the triggers, the activity of all our users is logged under the single company account and therefore capped by the apps script server quotas for a single user. This hasn't been much of an issue for us yet as long as our script is efficient in how it runs. I have looked into deploying this project as a web-app for our company, but there doesn't seem to be a good way to control/limit user access to the central files. In other words, if this project was running as a web app installed by each user, each user would need to have access to all the central spreadsheets that the project uses behind the scenes. And we don't want that.
SO with that background, here is my question. How do I efficiently track apps script activity to see how close we are to hitting our server quota, and identify which of my functions need to be optimized?
I started doing this by writing a entry into a "activity log" spreadsheet every time the script was called. It tracked what function was called, and who the user was and it had a start time entry and and end time entry so I can see how long unique executions took and which ones failed. This was great because I had a live view into the project activity and could graph it using the spreadsheet graphs tools. Where this began to break down was the fact that every execution of the script required two write-actions: one for initialization and another for completion. Since the script is being executed every time a user made an edit to their spreadsheet, during times of high traffic, the activity log spreadsheet became inaccessible and errors would be thrown all over the place.
So I have since transitioned to tracking activity by connecting each script file to a single Google Cloud Platform (GCP) project and using the Logger API. Writing logs is a lot more efficient than writing an entry to a spreadsheet, so the high traffic errors are all but gone. The problem now is that the GCP log browser isn't as easy to use as a spreadsheet and I can't graph the logs or sum up the activity to see where we stand with our server quota.
I've spent some time now trying to figure out how to automatically export the logs from the GCP so I can process the logs in real-time. I see how to download the logs as csv files, which I can then import into a google spreadsheet and do the calcs and graphing I need, but this is a manual process, and doesn't show live data.
I have also figured out how to stream the logs from GCP by setting up a "sink" that transfers the logs to a "bucket" which can theoretically be read by other services. This got me excited to try out Google Data Studio, which I saw is able to use Google Cloud Storage "buckets" as a data source. Unfortunately though, Google Data Studio can only read csv files in cloud storage, and not the json files that my "sink" is generating in my "bucket" for the logs.
So I've hit a wall. Am I missing something here? I'm just trying to get live data showing current activity on our apps script project so I can identify failed executions, see total processing time, and sort the logs by user or function so I can quickly identify where I need to optimize my script.
You've already referenced using GCP side of your Apps Script.
Have a look at Metric explorer, it lets you see quota usage per resource and auto generates graph for you.
But long term I think re-building your solution may be a better idea. At minimum switching to submitting data via Google Forms will save you on operation.

Correct scope for Google App Script Execution API?

I'm hoping to automate some HR work by running a Google App Script via the Execution API. Without getting too much into the details, I'd like to pass employee evaluation data as a parameter into the App Script. The script will then use this data to compile an "Employee Review" GDoc.
So far, I have ran a simple test App Script using the Execution API. For example, I can successfully run a simple function which logs a string or interacts with spreadsheets. So far so good.
But I run into problems when trying to write to a GDoc (which is unfortunately integral to my task). Here's my paired down script:
// TODO: Eventually, we'll pass these variables as arguments
var docId = "MY-DOC-ID";
// Find the team member review doc
var doc = DocumentApp.openById(docId);
// Replace placeholder text
var docBody = doc.getActiveSection();
docBody.replaceText('{{DATE}}', "Date set by App Script!!!");
doc.saveAndClose();
This script works when I press the "Run" button in the App Scripts web UI. But when I try to run via the Execution API, I get:
{
"error": "unauthorized_client",
"error_description": "Unauthorized client or scope in request."
}
So apparently I haven't provided the correct scope? Following the docs, I can find the necessary scope(s) in Project Properties > Scopes which says:
But when I try adding that scope, it wont work. As I said other scopes (e.g. https://www.googleapis.com/auth/spreadsheets) work just fine. Perhaps the auth/documents scope is no longer supported or there's a bug in their API?
Questions
What is the correct scope? I can see a big list here but I don't see https://www.googleapis.com/auth/documents, so?
Any other suggestions? For example, is it possible to write to a Google Doc using the Google Client API directly (i.e. without using App Scripts)?
Doh. I figured out the solution to my problem. While it was a dumb mistake, it's nevertheless worth posting as it may save others confusion in the future.
First, a little context about my setup. I'm authenticating to the Google Client API using a Service Account. Furthermore, as is common when using a service account setup, I am impersonating a user within our organization (specifically my own account).
My missing step (obvious in hindsight)...
Log into the App Script web UI as the person you are impersonating.
Manually run the script by pressing the play button
If the impersonated user has not already granted permissions to access the required scopes, you will be prompted to do so.
After granting access (specifically for the https://www.googleapis.com/auth/documents scope), my authorization error disappeared.
So the lesson: Make sure the account you are impersonating has granted access for all the scopes which your script requires.

Debugging GScript called by Google App

I have written some GScript that is called by a Google App (Awesome Tables).
How do I debug the GScript while it is running after being initiated by the Google App (I particularly want to see that values in variables as I step through the code)?
I found that Google Apps Script has a Logger Class. I used this to log messages when certain stages in my code was reached (some included variable values) and then emailed the whole log to myself. See https://developers.google.com/apps-script/reference/base/logger
I don't know of a way to do this. The best approach is probably to mimic the calling application by creating a test function in your Google Apps Script that calls the main function with the appropriate parameters. Then you can step through the code and see values using the debugger.
Try to check this Debugging part in the Google Apps Script documentation if it can help you.
It is stated here that there are some strategies for handling errors and investigating a script that is not running the way you expect.
Execution transcript
Logging custom messages
Using the debugger and breakpoints
For more information, check this Some Simple Debugging for Google Apps Script