log4js的使用


log4js的使用

安装:

1
npm install log4js

定义:logger.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'use strict';

let moment = require('moment'); // 日期处理
let chalk = require('chalk'); // 字体颜色
let log4js = require('log4js');

log4js.configure({
appenders: {
console: {type: 'console'},
debugFileJohn: {// 个人debug日志
type: 'dateFile',
filename: 'logs/john-',
pattern: 'yyyy-MM-dd.log',
maxLogSize: 10 * 1000 * 1000,
numBackups: 3,
alwaysIncludePattern: true
},
debugFile: {
type: 'dateFile',
filename: 'logs/debug-',
pattern: 'yyyy-MM-dd.log',
maxLogSize: 10 * 1000 * 1000,
numBackups: 3,
alwaysIncludePattern: true
}
},
categories: {
default: {appenders: ['console'], level: 'info'},
john: {appenders: ['console', 'debugFileJohn'], level: 'debug'},
debug: {appenders: ['console', 'debugFile'], level: 'debug'},
}
});

let johnLogger = log4js.getLogger('john');

exports.OFF = -1;
exports.DEBUG = 1;
exports.INFO = 2;
exports.WARN = 3;
exports.ERROR = 4;

let log_level = require("../config.js").log_level || exports.DEBUG; // 默认日志级别 DEBUG

function now() {
return '[' + moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ']';
}

function john(msg, showLog = true) {
if (log_level === exports.OFF || !showLog)
return;

if (log_level <= exports.DEBUG) {
johnLogger.info(now() + ' [DEBUG] ' + msg);
johnLogger.info(chalk.yellow("----------------------------------------------------------------------------------------------"));
}
}
exports.john = john;

使用:

1
2
3
4
5
/**
* 全局变量定义
*/
let log = require('./utils/logger.js');
global.Log = log;//打印日志工具
1
Log.john('a:' + a + ' b:' + b);