1.日志输出到控制台

npm i log4js -D

封装log4js文件:

注意:每次都要重新获取log4js.getLogger(‘debug’)级别才能生效

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.debuglogger.debug(content);}exports.info = (content) =>{let logger = log4js.getLogger('info')logger.level = levels.infologger.info(content);}exports.warn = (content) =>{let logger = log4js.getLogger('warn')logger.level = levels.warnlogger.warn(content);}exports.error = (content) =>{let logger = log4js.getLogger('error')logger.level = levels.errorlogger.error(content);}

app.js文件中引入并使用log4js

// 使用封装的log4j日志const logger = require("./utils/log4js");// loggerapp.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.日志输出到日志文件

修改配置为输出到文件即可

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 + patternalwaysIncludePattern: 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.debuglogger.debug(content);}exports.info = (content) =>{let logger = log4js.getLogger('info')logger.level = levels.infologger.info(content);}exports.warn = (content) =>{let logger = log4js.getLogger('warn')logger.level = levels.warnlogger.warn(content);}exports.error = (content) =>{let logger = log4js.getLogger('error')logger.level = levels.errorlogger.error(content);}