日志
更新時間 2024-12-10 12:14:00
最近更新時間: 2024-12-10 12:14:00
分享文章
本文介紹如何在Node.js運行環境下打印和查看函數日志。
打印日志
當需要查看函數運行相關的自定義狀態時,可以使用如下幾種方式打印日志至標準輸出stdout。往標準輸出stdout打印的日志內容會被函數收集。
ES模塊
export const handler = async (event, context) => {
?process.stdout.write('hi,fc\n');
?console.log('hello,world');
?context.logger.info('hello,fc');
?return "Hello World!";
};
CommonJS模塊
'use strict';
exports.handler = (event, context, callback) => {
?process.stdout.write('hi,fc\n');
?console.log('hello,world');
?context.logger.info('hello,fc');
? ?
?callback(null, 'hello,world');
};
以下分別介紹所使用的幾種日志打印方法。
使用process.stdout.write打印日志
使用此方法打印日志會將內容原樣輸出到日志中。輸出的日志內容如下所示。
hi,fc
使用console.log打印日志
使用此方法打印的每條日志中都會包含時間、RequestId、日志級別等信息。輸出的日志內容如下所示。
2024-03-04 07:01:16.927 1-65e571bc-158a59e8-b63f98cd471c [info] hello,world
直接使用context.logger打印日志
當您配置的函數實例并發度大于1時,一個函數實例會同時并發處理多個請求。此時強烈建議使用context.logger打印日志,以通過RequestId區分各并發請求的日志。輸出的日志內容如下所示。
2024-03-04 07:01:16.927 1-65e571bc-158a59e8-b63f98cd471c [[object Object]] hello,fc
查看日志
函數執行完成后,您可以在函數詳情頁的日志頁簽查看日志信息。