Node.js logs are displayed in the Log Service console by default, which causes inconvenience for data collection and troubleshooting. You can use Log4js to write logs into files and customize the log format, which facilitates data collection and consolidation.

var log4js = require('log4js');
log4js.configure({
  appenders: [
    {   
      type: 'file', // File output
      filename: 'logs/access.log', 
      maxLogSize: 1024,
      backups:3,
      category: 'normal' 
    }   
  ]
});
var logger = log4js.getLogger('normal');
logger.setLevel('INFO');
logger.info("this is a info msg");
logger.error("this is a err msg");

Log format

After logs are stored to text files by using Log4js, the logs are displayed in the following format in the files:

[2016-02-24 17:42:38.946] [INFO] normal - this is a info msg
[2016-02-24 17:42:38.951] [ERROR] normal - this is a err msg

Log4js defines six log output levels. They are TRACE, DEBUG, INFO, WARN, ERROR, and FATAL in ascending order.

Configure Logtail to collect Node.js logs

Select configurations based on the network deployment and your actual situation. For more information, see Python logs.

The regular expression that is automatically generated is based on the sample log only and may not be suitable for other logs. Therefore, you must adjust the regular expression after it is automatically generated. You can refer to the following sample Node.js logs to configure appropriate regular expressions for your logs.

Common Node.js logs and related regular expressions:
  • Sample Node.js log 1:
    • Sample log:
      [2016-02-24 17:42:38.946] [INFO] normal - this is a info msg
    • Regular expression:
      \[([^]]+)]\s\[([^\]]+)]\s(\w+)\s-(. *)
    • Extracted fields:

      time, level, loggerName, and message

  • Sample Node.js log 2:
    • Sample log:
      [2016-01-31 12:02:25.844] [INFO] access - 42.120.73.203 - - "GET /user/projects/ali_sls_log? ignoreError=true HTTP/1.1" 304 - "http://
      aliyun.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36"
    • Regular expression:
      \[([^]]+)]\s\[(\w+)]\s(\w+)\s-\s(\S+)\s-\s-\s"([^"]+)"\s(\d+)[^"]+("[^"]+)"\s"([^"]+). *
    • Extracted fields:

      time, level, loggerName, ip, request, status, referer, and user_agent