Node JS - Log4js

1. install package

1
2
npm i config
npm i log4js

2. Creat config/default.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"logger": {
"appenders": {
"file": {
"type": "file",
"filename": "logs/log.log",
"maxLogSize": 104857600,
"backups": 10,
"layout": {
"type": "json"
}
},
"console": {
"type": "console"
}
},
"categories": {
"default": {
"appenders": ["file"],
"level": "trace"
}
}
}
}

3. Creat log.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const config = require('config');
const log4js = require('log4js');

log4js.addLayout('json', function(config) {
return function(logEvent) {
return JSON.stringify(logEvent);
};
});

log4js.configure(config.logger);

module.exports = {
log4js,
getLogger: log4js.getLogger
};

4. Ceate index.js

1
2
3
4
5
6
7
const logger = require('./log').getLogger('logtest');
logger.trace('testTrace');
logger.debug('testDebug');
logger.info('testInfo');
logger.warn('testWarn');
logger.error('testError');
logger.fatal('testFatal');

5. Run

1
node index.js

index

Demo

Reference