Class Logger

Logger

借助此类,如果脚本与标准 Cloud 项目相关联,开发者可以将数据写入执行日志和 Google Cloud Logging。在 Cloud Logging 中,此类是结构化日志记录和 jsonPayload 支持的首选。对于基于时间的日志记录,请使用 console

方法

方法返回类型简介
clear()void清除日志。
getLog()String返回当前日志中的完整消息列表。
log(data)Logger将数据写入日志。
log(format, values)Logger使用所提供的格式和值将格式化字符串写入日志记录控制台。

详细文档

clear()

清除日志。


getLog()

返回当前日志中的完整消息列表。此方法可用于保存或通过电子邮件发送脚本执行期间生成的整个日志输出。

// Generate a log, then email it to the person who ran the script. const files = DriveApp.getFiles(); while (files.hasNext()) {   Logger.log(files.next().getName()); } const recipient = Session.getActiveUser().getEmail(); const subject = 'A list of files in your Google Drive'; const body = Logger.getLog(); MailApp.sendEmail(recipient, subject, body);

返回

String - Logging 控制台中的日志


log(data)

将数据写入日志。数据可以是字符串、JavaScript 对象或具有 message 属性的对象。

Logger.log("my log message"); // Info   my logmessage Logger.log({ key: "value" }); // Info   {key=value} Logger.log({ message: "my log message", data: { key: "value" } }) // Info   my logmessage

传递对象时,如果对象包含 message 属性,则该属性会用作日志消息。否则,系统会调用 toString() 方法将对象转换为字符串。所有其他可序列化为 JSON 的属性都包含在 LogEntryjsonPayload 中,如下例所示:

{   "insertId": "w5eib...",   "jsonPayload": {     "message": "my log message",     "serviceContext": {       "service": "AKfyc..."     },     "data": {       "key": "value"     }   },   "resource": {     "type": "app_script_function",     "labels": {       "invocation_type": "editor",       "function_name": "unknown",       "project_id": "1234567890"     }   },   "timestamp": "2024-11-15T23:28:19.448591Z",   "severity": "INFO",   "labels": {     "script.googleapis.com/user_key": "AOX2d...",     "script.googleapis.com/process_id": "EAEA1...",     "script.googleapis.com/project_key": "MQXvl...",     "script.googleapis.com/deployment_id": "AKfyc..."   },   "logName": "projects/[PROJECT_ID]/logs/script.googleapis.com%2Fconsole_logs",   "receiveTimestamp": "2024-11-15T23:28:20.363790313Z" }

参数

名称类型说明
dataObject要记录的对象

返回

Logger - Logger,用于链式调用。


log(format, values)

使用所提供的格式和值将格式化字符串写入日志记录控制台。该字符串可以包含多个 %s 占位符,这些占位符会被替换为转换为字符串的参数列表中的相应值。

// Log the number of Google Groups you belong to. const groups = GroupsApp.getGroups(); Logger.log('You are a member of %s Google Groups.', groups.length);

参数

名称类型说明
formatString格式字符串,其中包含的 %s 实例数量与 values 参数数量相同
valuesObject...要插入格式字符串中的值的数量可变

返回

Logger - Logger,用于链式调用