1.日志输出到控制台
npm i log4js -D
封装log4js文件:
注意:每次都要重新获取log4js.getLogger('debug')级别才能生效
javascript
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' }
},
categories:{
default: { appenders: ['console'], level: 'debug' },
}
});
/**
* 日志输出 level 为 debug
*/
exports.debug = (content) => {
//注意:每次都要重新获取log4js.getLogger('debug')级别才能生效
let logger = log4js.getLogger('debug')
logger.level = levels.debug
logger.debug(content);
}
exports.info = (content) =>{
let logger = log4js.getLogger('info')
logger.level = levels.info
logger.info(content);
}
exports.warn = (content) =>{
let logger = log4js.getLogger('warn')
logger.level = levels.warn
logger.warn(content);
}
exports.error = (content) =>{
let logger = log4js.getLogger('error')
logger.level = levels.error
logger.error(content);
}
app.js文件中引入并使用log4js
javascript
// 使用封装的log4j日志
const logger = require("./utils/log4js");
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
// console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// 使用log4j输出日志
logger.info(`log4j输出日志:读取到log4js日志`);
logger.info(`log4j输出日志:${ctx.method} ${ctx.url} - ${ms}ms`);
})
2.日志输出到日志文件
修改配置为输出到文件即可
javascript
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' },
// 输出日志到日志文件
info:{
type: 'file',
filename: 'logs/info-logs.log'
},
error:{
type: 'dateFile',
filename: 'logs/error',
pattern: 'yyyy-MM-dd.log',
// 设置文件名称是 filename + pattern
alwaysIncludePattern: true
}
},
categories:{
default: { appenders: ['console'], level: 'debug' },
info: {
appenders: ["info","console"],
level: 'info'
},
error:{
appenders: ["error","console"],
level: 'error'
}
}
});
/**
* 日志输出 level 为 debug
*/
exports.debug = (content) => {
let logger = log4js.getLogger('debug')
logger.level = levels.debug
logger.debug(content);
}
exports.info = (content) =>{
let logger = log4js.getLogger('info')
logger.level = levels.info
logger.info(content);
}
exports.warn = (content) =>{
let logger = log4js.getLogger('warn')
logger.level = levels.warn
logger.warn(content);
}
exports.error = (content) =>{
let logger = log4js.getLogger('error')
logger.level = levels.error
logger.error(content);
}