在 Google 应用程序脚本中打印到控制台?

我对编程很陌生(已经上过 Codecademy 的一些 JS 课程)。我试图创建一个简单的脚本,以确定,如果给了一个电子表格的结果从扑克游戏,谁应该支付谁。我打开 Google Apps Script,开始写下面的代码:

function addplayerstoArray(numplayers) {


var playerArray = [];


for (i=0; i<numplayers; i++) {
playerArray.push(i);
}
}


addplayerstoArray(7);


console.log(playerArray[3])

这个想法是创建一个包含所有玩家的数组。在运行代码时,我以为它会在控制台上打印“3”。但什么都没发生。上面说

“ ReferenceError:”控制台“未定义。”

A)关于 Google Apps 脚本控制台在打印方面是如何工作的,我有什么不明白的地方吗? 这样我就可以看到我的代码是否达到了我想要的效果?

B)代码有问题吗?

176517 次浏览

The console is not available because the code is running in the cloud, not in your browser. Instead, use the Logger class provided by GAS:

Logger.log(playerArray[3])

and then view the results in the IDE under View > Logs...

Here's some documentation on logging with GAS.

Edit: 2017-07-20 Apps script now also provides Stackdriver Logging. View these logs in the script editor under View - Console Logs.

Just to build on vinnief's hacky solution above, I use MsgBox like this:

Browser.msgBox('BorderoToMatriz', Browser.Buttons.OK_CANCEL);

and it acts kinda like a break point, stops the script and outputs whatever string you need to a pop-up box. I find especially in Sheets, where I have trouble with Logger.log, this provides an adequate workaround most times.

In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac

If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.

Even though Logger.log() is technically the correct way to output something to the console, it has a few annoyances:

  1. The output can be an unstructured mess and hard to quickly digest.
  2. You have to first run the script, then click View / Logs, which is two extra clicks (one if you remember the Ctrl+Enter keyboard shortcut).
  3. You have to insert Logger.log(playerArray), and then after debugging you'd probably want to remove Logger.log(playerArray), hence an additional 1-2 more steps.
  4. You have to click on OK to close the overlay (yet another extra click).

Instead, whenever I want to debug something I add breakpoints (click on line number) and press the Debug button (bug icon). Breakpoints work well when you are assigning something to a variable, but not so well when you are initiating a variable and want to peek inside of it at a later point, which is similar to what the op is trying to do. In this case, I would force a break condition by entering "x" (x marks the spot!) to throw a run-time error:

enter image description here

Compare with viewing Logs:

enter image description here

The Debug console contains more information and is a lot easier to read than the Logs overlay. One minor benefit with this method is that you never have to worry about polluting your code with a bunch of logging commands if keeping clean code is your thing. Even if you enter "x", you are forced to remember to remove it as part of the debugging process or else your code won't run (built-in cleanup measure, yay).

Answering the OP questions

A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?

The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.

B) Is it a problem with the code?

As the error message said, the problem was that console was not defined but nowadays the same code will throw other error:

ReferenceError: "playerArray" is not defined. (line 12, file "Code")

That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.

var playerArray = [];


function addplayerstoArray(numplayers) {
for (i=0; i<numplayers; i++) {
playerArray.push(i);
}
}


addplayerstoArray(7);


console.log(playerArray[3])

Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.

Addendum


NOTES:
  1. As of May 2022, logs will be available in the Executions page for 7 days. Also when running a function from the Apps Script editor, the logs will be shown on the bottom of the screen.
  2. Stackdriver Logging was renamed to Cloud Logging.

On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!') will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.

From Google Apps Script Release Notes 2017

June 23, 2017

Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.

From Logging > Stackdriver logging

The following example shows how to use the console service to log information in Stackdriver.

function measuringExecutionTime() {
// A simple INFO log message, using sprintf() formatting.
console.info('Timing the %s function (%d arguments)', 'myFunction', 1);


// Log a JSON object at a DEBUG level. The log is labeled
// with the message string in the log viewer, and the JSON content
// is displayed in the expanded log structure under "structPayload".
var parameters = {
isValid: true,
content: 'some string',
timestamp: new Date()
};
console.log({message: 'Function Input', initialData: parameters});


var label = 'myFunction() time';  // Labels the timing log entry.
console.time(label);              // Starts the timer.
try {
myFunction(parameters);         // Function to time.
} catch (e) {
// Logs an ERROR message.
console.error('myFunction() yielded an error: ' + e);
}
console.timeEnd(label);      // Stops the timer, logs execution duration.
}

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

Make sure you select the function that needs to be executed. See screenshot:
Apps script logging

Logger.log (your message), then look at log.

in new Apps script ( post from 2021) to see log:

  1. go to Apps Script
  2. in the sidebar swich tab from editor to 4th tab (i have other language so i dont know runs or opens how its called) abowe settings
  3. this tab contains history of all scripts runs, just drop down it and you will see your logs

If you are developing a Google App Script Add-On, an easy temporary solution is to just throw your message as an error. It will display in the popup window.

function handleEvent(e) {
throw new Error(JSON.stringify(e)); //now you can inspect the event
}

Code
enter image description here

Add-On Window
enter image description here