日志

更新时间: 2024-03-04 10:29:35

您可以在Node.js运行环境中打印和查看日志,通过日志快速定位问题或分析日志了解函数执行过程和耗时等,提升系统的可靠性和稳定性。

打印日志

函数往标准输出stdout打印的日志内容会被收集到创建服务时指定的Logstore中,您可以使用如下几种方式打印日志至标准输出stdout。打印日志的示例如下所示。

ES模块

说明

此示例仅支持运行在Node.js 18及以上版本的运行时环境。

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模块

'usestrict';

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、日志级别等信息。输出的日志内容如下所示。

2023-04-01T10:04:19.024Z 19b394a3-4fff-480c-9b5c-cbdfd6952f4e [silly] hello,world

直接使用context.logger打印日志

当您配置的函数实例并发度大于1时,一个函数实例会同时并发处理多个请求。此时强烈建议使用context.logger打印日志,以通过RequestId区分各并发请求的日志。输出的日志内容如下所示。

2023-04-01T10:04:19.024Z 19b394a3-4fff-480c-9b5c-cbdfd6952f4e [info] hello,fc

查看日志

函数执行完成后,您可以在函数详情页的调用日志页签查看日志信息。具体操作和说明,请参见查看调用日志

阿里云首页 函数计算(旧版) 相关技术圈