/** * Logs Google Sheet information. * @param {number} rowNumber The spreadsheet row number. * @param {string} email The email to send with the row data. */functionemailDataRow(rowNumber,email){console.log('Emailing data row '+rowNumber+' to '+email);try{constsheet=SpreadsheetApp.getActiveSheet();constdata=sheet.getDataRange().getValues();constrowData=data[rowNumber-1].join(' ');console.log('Row '+rowNumber+' data: '+rowData);MailApp.sendEmail(email,'Data in row '+rowNumber,rowData);}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',err.message);}}
使用「2」和「john@example.com」輸入內容執行這項指令碼時,系統會寫入下列記錄:
[16-09-12 13:50:42:193 PDT] Emailing data row 2 to john@example.com
[16-09-12 13:50:42:271 PDT] Row 2 data: Cost 103.24
/** * Logs the time taken to execute 'myFunction'. */functionmeasuringExecutionTime(){// 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 "jsonPayload".constparameters={isValid:true,content:'some string',timestamp:newDate()};console.log({message:'Function Input',initialData:parameters});constlabel='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.}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-31 (世界標準時間)。"],[[["\u003cp\u003eApps Script provides three logging mechanisms: the built-in execution log, Cloud Logging, and Error Reporting to assist with debugging and monitoring.\u003c/p\u003e\n"],["\u003cp\u003eThe execution log, accessed via the editor, streams real-time logs but with limited persistence, suitable for basic development checks.\u003c/p\u003e\n"],["\u003cp\u003eCloud Logging offers persistent logs viewable in the Developer Console or Apps Script dashboard, ideal for multi-user environments and detailed analysis.\u003c/p\u003e\n"],["\u003cp\u003eError Reporting automatically collects and displays script exceptions in the Developer Console or GCP console, streamlining error identification and resolution.\u003c/p\u003e\n"],["\u003cp\u003eException logging is enabled by default for new Apps Script projects, and requires a standard Google Cloud project for full functionality with Cloud Logging and Error Reporting.\u003c/p\u003e\n"]]],[],null,["When developing any kind of app, you often want to log information to help\ndiagnose faults during development, to identify and diagnose customer issues,\nand for other purposes.\n\nApps Script provides three different mechanisms for logging:\n\n- The built-in [Apps Script execution log](#execution_log_logging).\n This log is lightweight and streams in real time, but persists only for a\n short time.\n\n- The [Cloud Logging](#cloud_logging) interface in the\n Developer Console, which provides logs that persist for many days after their\n creation.\n\n- The [Error Reporting](#error_reporting) interface\n in the Developer Console, which collects and records errors that occur\n while your script is running.\n\nThese are described in the following sections. In addition to these mechanisms,\nyou can also build your own logger code that, for example, writes information\nto a logging [Spreadsheet](/apps-script/reference/spreadsheet/spreadsheet-app)\nor [JDBC database](/apps-script/guides/jdbc).\n\nUse the Apps Script execution log\n\nA basic approach to logging in Apps Script is to use the built-in\nexecution log. To view these logs, at the top\nof the editor, click **Execution log**. When you run a function or use the\ndebugger, the logs stream in real time.\n\nYou can use either the [`Logger`](/apps-script/reference/base/logger) or\n[`console`](/apps-script/reference/base/console) logging services in the\nbuilt-in execution log.\n\nThese logs are intended for simple checks during development and debugging,\nand do not persist very long.\n\nFor example, consider this function: \nutils/logging.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/utils/logging.gs) \n\n```gosu\n/**\n * Logs Google Sheet information.\n * @param {number} rowNumber The spreadsheet row number.\n * @param {string} email The email to send with the row data.\n */\nfunction emailDataRow(rowNumber, email) {\n console.log('Emailing data row ' + rowNumber + ' to ' + email);\n try {\n const sheet = SpreadsheetApp.getActiveSheet();\n const data = sheet.getDataRange().getValues();\n const rowData = data[rowNumber - 1].join(' ');\n console.log('Row ' + rowNumber + ' data: ' + rowData);\n MailApp.sendEmail(email, 'Data in row ' + rowNumber, rowData);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', err.message);\n }\n}\n```\n\nWhen this script is run with inputs \"2\" and \"john@example.com\" the\nfollowing logs are written:\n\u003e \\[16-09-12 13:50:42:193 PDT\\] Emailing data row 2 to john@example.com \n\u003e\n\u003e \\[16-09-12 13:50:42:271 PDT\\] Row 2 data: Cost 103.24\n\nCloud Logging\n\nApps Script also provides partial access to the Google Cloud Platform (GCP)\n[Cloud Logging](https://cloud.google.com/logging/docs/) service. When you\nrequire logging that persists for several days, or need a more complex logging\nsolution for a multi-user production environment, Cloud Logging is the preferred\nchoice. See [Cloud Logging quotas and limits](https://cloud.google.com/logging/quotas)\nfor data retention and other quota details.\n\nIf you need more logging quota, you can\n[submit a Google Cloud Platform quota request](https://cloud.google.com/docs/quota#requesting_higher_quota).\nThis requires that you have access to the\n[Cloud Platform project](/apps-script/guides/cloud-platform-projects)\nthat your script uses.\n| **Note:** Cloud Logging provides a number of services beyond storing logs, such as alerts and metrics. At this time these services aren't available from Apps Script.\n\nUsing Cloud Logging\n\nCloud logs are attached to the [Google Cloud project](/apps-script/guides/cloud-platform-projects)\nassociated with your Apps Script. You can view a simplified version of these\nlogs in the [Apps Script dashboard](https://script.google.com/home/executions).\n\nTo make full use of Cloud Logging and its capabilities, use a\n[standard Google Cloud project](/apps-script/guides/cloud-platform-projects#standard_cloud_platform_projects)\nwith your script project. This lets you access Cloud logs directly in the\n[GCP Console](/apps-script/guides/cloud-platform-projects#viewing_cloud_logs_and_error_reports_in_the_google_cloud_platform_console)\nand gives you more viewing and filtering options.\n| **Note:** If you use the Rhino runtime, Cloud Logging doesn't support the Apps Script [`Logger`](/apps-script/reference/base/logger) service. Instead, use the [`console`](/apps-script/reference/base/console) service.\n\nWhen logging, it is good privacy practice to avoid recording any personal\ninformation about the user, such as email addresses. Cloud logs are\nautomatically labeled with\n[active user keys](/apps-script/guides/logging#active_user_keys)\nyou can use to locate a specific user's log messages when necessary.\n\nYou can log strings, formatted strings, and even JSON objects using the\nfunctions provided by the Apps Script\n[`console`](/apps-script/reference/base/console) service.\n\nThe following example shows how to use the [`console`](/apps-script/reference/base/console)\nservice to log information in Cloud Operations. \nutils/logging.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/utils/logging.gs) \n\n```gosu\n/**\n * Logs the time taken to execute 'myFunction'.\n */\nfunction measuringExecutionTime() {\n // A simple INFO log message, using sprintf() formatting.\n console.info('Timing the %s function (%d arguments)', 'myFunction', 1);\n\n // Log a JSON object at a DEBUG level. The log is labeled\n // with the message string in the log viewer, and the JSON content\n // is displayed in the expanded log structure under \"jsonPayload\".\n const parameters = {\n isValid: true,\n content: 'some string',\n timestamp: new Date()\n };\n console.log({message: 'Function Input', initialData: parameters});\n const label = 'myFunction() time'; // Labels the timing log entry.\n console.time(label); // Starts the timer.\n try {\n myFunction(parameters); // Function to time.\n } catch (e) {\n // Logs an ERROR message.\n console.error('myFunction() yielded an error: ' + e);\n }\n console.timeEnd(label); // Stops the timer, logs execution duration.\n}\n```\n\nActive user keys\n\nTemporary active user keys provide a convenient way to spot unique users in\nCloud Log entries without revealing the identities of those users. Keys\nare per script and change roughly once a month to provide additional security\nshould a user reveal their identity to a developer, for example while reporting\nan issue.\n\nTemporary active user keys are superior to logging identifiers like email\naddresses because:\n\n- You don't have to add anything to your logging; they're already there!\n- They don't require user authorization.\n- They protect user privacy.\n\nTo find temporary active user keys in your Cloud Log entries,\n[view your Cloud logs in the Google Cloud console](/apps-script/guides/cloud-platform-projects#viewing_cloud_logs_and_error_reports_in_the_google_cloud_platform_console).\nYou can do this only if your script project is using a\n[standard Google Cloud project](/apps-script/guides/cloud-platform-projects#standard_cloud_platform_projects)\nthat you have access to. Once you've opened the Google Cloud project in the console,\nselect a log entry of interest and expand it to view\n**metadata \\\u003e labels \\\u003e script.googleapis.com/user_key**.\n\nYou can also get the temporary active user key by calling\n[`Session.getTemporaryActiveUserKey()`](/apps-script/reference/base/session#getTemporaryActiveUserKey())\nin your script. One way to use this method is to display the key to the user\nwhile they are running your script. Then users may choose to include their keys\nwhen reporting issues to help you identify the relevant logs.\n\nException logging\n\nException logging sends unhandled exceptions in your script project code\nto Cloud Logging, along with a stack trace.\n\nTo view exception logs, follow the steps below:\n\n1. Open the Apps Script project.\n2. At the left, click **Executions** playlist_play.\n3. At the top, click **Add a filter \\\u003e Status**.\n4. Select the **Failed** and **Timed out** checkboxes.\n\nYou can also [view logged exceptions in the GCP console](/apps-script/guides/cloud-platform-projects#viewing_cloud_logs_and_error_reports_in_the_google_cloud_platform_console)\nif your script project is using a\n[standard Google Cloud project](/apps-script/guides/cloud-platform-projects#standard_cloud_platform_projects)\nthat you have access to.\n\nEnable exception logging\n\nException logging is enabled by default for new projects. To enable exception\nlogging for older projects, follow the steps below:\n\n1. Open the script project.\n2. At the left, click **Project Settings** settings.\n3. Select the **Log uncaught exceptions to Cloud Operations** checkbox.\n\nError Reporting\n\nException logging automatically integrates with\n[Cloud Error Reporting](https://cloud.google.com/error-reporting/docs/),\na service that aggregates and displays errors produced in your script.\nYou can\n[view your Cloud error reports in the Google Cloud console](/apps-script/guides/cloud-platform-projects#viewing_cloud_logs_and_error_reports_in_the_google_cloud_platform_console).\nIf you are prompted to \"Set up Error Reporting\" this is because\nyour script has not yet logged any exceptions. No setup is required beyond\n[enabling exception logging](#exception_logging).\n\nLogging requirements\n\nThere are no requirements for using the built-in execution log.\n\nYou can view a simplified version of Cloud logs in the\n[Apps Script dashboard](https://script.google.com/home/executions). However, to\nmake the most of Cloud Logging and error reporting you must have access\nto the GCP project of the script. This is only possible if your script project\nis using a [standard Google Cloud project](/apps-script/guides/cloud-platform-projects#standard_cloud_platform_projects)."]]