You can print and view logs in Node.js runtimes. The logs can be used to quickly locate issues or analyzed to obtain function execution information, such as the function execution process and duration. This improves system reliability and stability.
Log printing
The log content that is printed by a function to the standard output (stdout) is stored in the specified Logstore in Simple Log Service when you create a service. You can use one of the following methods to print logs to stdout. The following sample code provides an example:
ECMAScript modules
This example supports only Node.js 18 or later.
The sample code supports one-click deployment. You can deploy the sample code in Function Compute with one click. nodejs-fc-log-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 modules
'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');
};
Use process.stdout.write to print logs
If you use this method to print logs, the log content is printed. The following log is printed:
hi,fc
Use console.log to print logs
If you use this method to print logs, each log contains information such as the time, request ID, and log level. The following log is printed:
2024-03-04 07:01:16.927 1-65e571bc-158a59e8-b63f98cd471c [info] hello,world
Use context.logger to print logs
If you configure the instance concurrency of the function to a value that is greater than 1, one function instance concurrently processes multiple requests. In this case, we recommend that you use context.logger to print logs to distinguish the logs of each concurrent request by request ID. The following log is printed:
2024-03-04 07:01:16.927 1-65e571bc-158a59e8-b63f98cd471c [[object Object]] hello,fc
View logs
After the function is executed, you can view the logs on the Logs tab of the function details page. For more information, see View function invocation logs.