Logging with log4js in Node.js

You can use the log4js module to record logs. First, install the log4js module using the following command:

npm install log4js

Then, introduce the log4js module in your code and configure it. Here is an example configuration file:

{
  "appenders": {
    "file": {
      "type": "file",
      "filename": "logs/access.log",
      "maxLogSize": 10485760,
      "backups": 3,
      "compress": true
    },
    "console": {
      "type": "console"
    }
  },
  "categories": {
    "default": {
      "appenders": ["file", "console"],
      "level": "info"
    }
  }
}

In this configuration, we define two appenders: one for file output and one for console output. We also define a category that outputs logs to both appenders.

Next, load the configuration file in your code and get the logger object. Example:

const log4js = require('log4js');
const logger = log4js.getLogger();
logger.level = 'debug';

Now you can use the logger object to record logs. For example:

logger.debug('Debug message');
logger.info('Info message');
logger.warn('Warn message');
logger.error('Error message');

This will log messages at different levels respectively.

评论

暂无评论。

登录后可发表评论。