log4js是js的log工具
本身比较好用,简易做了下封装
1.定义一个普通的console的日志输出 和文件的保存输出(默认error级别) 导出一个定义函数
utils/log4js.js
const log4js = require('log4js')
const levels = {
'trace': log4js.levels.TRACE,
'debug': log4js.levels.DEBUG,
'info': log4js.levels.INFO,
'warn': log4js.levels.WARN,
'error': log4js.levels.ERROR,
'fatal': log4js.levels.FATAL,
}
log4js.configure({
appenders: {
console: {type: 'console'},
error: {
type: "dateFile",
filename: 'logs/error-log',
pattern: 'yyyy-MM-dd.log',
alwaysIncludePattern: true
}
},
categories: {
// 默认的 getLogger
default: {appenders: ['console'], level: 'debug'},
error: {
appenders: ['error'],
level: 'error'
}
}
})
function defineLogger(type = 'default') {
const obj = {}
Object.keys(levels).forEach(key => {
obj[key] = (c) => {
const log = log4js.getLogger(type);
log.level = levels[key]
log[key](c)
}
})
return obj
}
module.exports = defineLogger
2.使用
app.js
导入 定义
const defineLogger = require('./utils/log4js')
const defaultLogger = defineLogger()
const errorLogger = defineLogger("error")
// logger
app.use(async (ctx, next) => {
await next()
defaultLogger.fatal("this is default fatal console log")
errorLogger.fatal("this is error fatal in file")
})
似乎需要自己创建logs文件夹