Write a simple script to log a custom message in the Google Apps Script log

Write a simple script to log a custom message in the Google Apps Script log

Instructions:

  • Open the Google Apps Script editor by navigating to script.google.com.
  • Create a new project and paste the code into the script editor.
  • Save and name your project.
  • Run the logMessage function.
  • View the log by clicking on View > Logs.

Explanation: This script defines a function logMessage that creates a variable message containing a string. It then uses Logger.log() to print this message to the Google Apps Script log.

function logMessage() {

 const myName = ‘Laurence’;

 const message = `Hello my name is ${myName}`;

 Logger.log(message);

}

The function named logMessage() that uses the Google Apps Script Logger to log a message to the script’s log. 

Let’s break down the code step by step:

  1. const myName = ‘Laurence’;: This line declares a constant variable named myName and assigns the string value ‘Laurence’ to it. It essentially stores the name “Laurence” in the variable.
  2. const message = `Hello my name is ${myName}`;: This line declares another constant variable named message. It uses template literals, denoted by backticks (), to create a string. Within the template literal, ${myName}is a placeholder for the value stored in themyNamevariable. This allows you to dynamically insert the value ofmyNameinto the string. So,message` will hold the string “Hello my name is Laurence.”
  3. Logger.log(message);: This line uses the Logger.log() method provided by Google Apps Script. It logs the value of the message variable to the script’s log.

When you run the logMessage() function, it will log the following message to the script’s log:

This is a simple example of using template literals to create a formatted message with dynamic content and then logging it for debugging or informational purposes using Google Apps Script’s Logger. The logged messages are typically viewed in the “Logs” section of the Google Apps Script editor, which can be helpful for debugging and monitoring script execution.