1.日志输出到控制台
npm i log4js -D
封装log4js文件:
const log4js = require("log4js");
const logger = log4js.getLogger();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) => {logger.level = levels.debuglogger.debug(content);}exports.info = (content) =>{logger.level = levels.infologger.info(content);
}exports.warn = (content) =>{logger.level = levels.warnlogger.warn(content);
}exports.error = (content) =>{logger.level = levels.errorlogger.error(content);
}
app.js文件中引入并使用log4js
// 使用封装的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.日志输出到日志文件
修改配置为输出到文件即可
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 + patternalwaysIncludePattern: true}},categories:{default: { appenders: ['console'], level: 'debug' },info: {appenders: ["info","console"],level: 'info'},error:{appenders: ["error","console"],level: 'error'}}
});