猿记录

一个记录、分享的博客

您的位置:主页 > 技术专栏 > node >

node 中日志记录和错误处理

2018-01-03 17:29:41 作者:yxl 次阅读 node

代码示例地址:https://github.com/yxl720/koa-log/tree/master
1、日志记录主要是使用了log4js   
      官网的简单demo
const log4js = require('log4js');
log4js.configure({
  appenders: { cheese: { type: 'file', filename: 'cheese.log' } },
  categories: { default: { appenders: ['cheese'], level: 'error' } }
});
const logger = log4js.getLogger('cheese');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');
 
2、基于koa封装了一个日志中间件
   //logger.js 
const log4js = require('log4js');
//日志封装函数
const access = require('./access.js')
 
//应用级别的日记记录
const methods = ['trace','debug','info','warn','error','fatal','mark'];
 
//日记切割
 
module.exports = (options)=>{
let contextLogger = {};
const defaultInfo = {
env:'dev',
dir:'logs',
appLogLevel:'info'
}
//将传过来的options 对象 合并
const opts = Object.assign({},defaultInfo,options || {})
console.log( opts );
const { env,dir,appLogLevel } = opts; //解构
const appenders = { cheese: { type: 'dateFile', filename: `${dir}/log`,pattern:'-yyyy-MM-dd.log',alwaysIncludePattern:true} }
 
//判断是否开发环境 开发环境就直接输出在终端 方便调试
if( env === 'dev' || env === 'local' || env === 'development' ){
appenders.out = {
type:'console'
}
}
 
const config = {
appenders: appenders,
categories: { default: { appenders: Object.keys(appenders), level: appLogLevel } }
}
 
return async (ctx,next)=>{
const start = +new Date(); //开始时间
log4js.configure(config);
const logger = log4js.getLogger('cheese');
methods.forEach((method,i)=>{
contextLogger[method] = (message)=>{
logger[method](access(ctx,message,{}))
}
})
//挂载在上下文上
ctx.log = contextLogger
await next()
 
const end = +new Date(); //结束时间
const responseTime = end - start;
logger.info(access(ctx,`响应时间为${responseTime/1000}s`,{}));
  }
}
//index.js
const logger = require('./logger')
module.exports = (options)=>{
const loggerMiddleware = logger(options);
return (ctx,next)=>{
return loggerMiddleware(ctx,next).catch((e)=>{
if(ctx.status < 500){
ctx.status = 500;
}
ctx.log.error(e.stack);
ctx.state.logged = true;
ctx.throw(e);
})
}
}
//access.js
//记录客户端的信息
module.exports = (ctx,message,commonInfo) => {
const {method,url,host,headers} = ctx.request;
const client = {
method,
url,
host,
message,
referer:headers['referer'],
userAgent:headers['user-agent']
}
return JSON.stringify(Object.assign(commonInfo,client));
}
 

凡本站注明“本站”或“投稿”的所有文章,版权均属于本站或投稿人,未经本站授权不得转载、摘编或利用其它方式使用上述作品。

编辑:yxl 关键词: node,日志处理
0

网友评论