// 安装log4js
npm install log4js --save-dev
// log.ts
import Koa from 'koa'
import log4js from 'log4js'
const env = process.env.NODE_ENV
log4js.configure({
appenders: {
everything: {
type: 'dateFile',
filename: './logs/day',
pattern: 'yyyy-MM-dd.log',
alwaysIncludePattern: true,
keepFileExt: true,
daysToKeep: 7
},
dev: {
type: 'console'
}
},
categories: {
default: {
appenders: ['everything'],
level: 'info'
},
dev: {
appenders: ['dev', 'everything'],
level: 'debug'
}
}
})
let logger = env !== 'production'
? log4js.getLogger('dev')
: log4js.getLogger()
export default async function (ctx: Koa.Context, next: Koa.Next) {
ctx.logger = logger
try {
// 放行请求,以捕捉请求内异常
await next()
if (ctx.status === 404) {
ctx.throw(404);
}
// 记录大于200的错误
const ctxBody = ctx.body as IResult
if (ctxBody.code > 200) {
logger.info(JSON.stringify({
url: ctx.url,
message: ctxBody.message
}))
}
} catch (error: any) {
// 记录异常日志
logger.error(JSON.stringify({
url: ctx.url,
error: error.message
}))
}
}