In Google Apps Script, the Logger
class provides simple logging functionality that can help you debug your scripts by recording messages in the Google Apps Script log. This log can be viewed in the Apps Script editor under the “Executions” or “Logs” tabs.
Basic Usage of Logger.log
The Logger.log
method is used to record messages. Here’s a simple example:
function logMessage() {
Logger.log('This is a log message.');
}
When you run the logMessage
function, you’ll see “This is a log message.” appear in the log.
Logging Variable Values
Often, you want to log the value of a variable to understand what’s happening in your script. Here’s how you can log a variable:
function logVariable() {
var username = 'John Doe';
Logger.log('The username is: ' + username);
}
In this example, the log will contain “The username is: John Doe”.
Using Formatted Strings with Logger.log
When you need to log multiple variables or create more complex log messages, using formatted strings can be very useful. JavaScript provides a way to format strings with placeholders, which can be replaced by variable values.
Here’s an example using Logger.log
with a formatted string:
function logFormattedString() {
var groups = ['Admins', 'Editors', 'Viewers'];
Logger.log('You are a member of %s Google Groups.', groups.length);
}
In this example, %s
is a placeholder that will be replaced by the value of groups.length
. The log will contain “You are a member of 3 Google Groups.”.
Combining Multiple Values in a Log Message
You can combine multiple placeholders in a log message. Here’s an example:
function logMultipleValues() {
var username = 'Jane Smith';
var groups = ['Admins', 'Editors', 'Viewers'];
Logger.log('%s is a member of %s Google Groups.', username, groups.length);
}
This will log “Jane Smith is a member of 3 Google Groups.”.
Practical Example: Logging API Responses
Imagine you are working with an API and want to log the response. Here’s a practical example:
function logApiResponse() {
var url = 'https://api.example.com/data';
var response = UrlFetchApp.fetch(url);
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
Logger.log('API Response Code: %s', responseCode);
Logger.log('API Response Body: %s', responseBody);
}
In this script, the response code and body from an API call are logged.
Conclusion
Using Logger.log
in Google Apps Script is an essential technique for debugging and understanding your script’s behavior. Whether you’re logging simple messages, variable values, or using formatted strings, Logger.log
can help you monitor your script’s execution and diagnose issues effectively.