node.js项目中使用log4js保存日志文件

Posted by PanMin on June 12, 2017

node.js项目中使用log4js保存日志文件

log4js提供了多个日志等级分类,同时也能替换console.log输出,另外他还可以按照文件大小或者日期来生成本地日志文件,还可以使用邮件等形式发送日志。

安装log4js

npm install log4js --save

log4js配置

新建log_config.js文件:

var log4js = require('log4js')
var path = require('path')
var fs = require('fs')
var basePath = path.resolve(__dirname,'../logs')

var errorPath = basePath+'/errors/'
var resPath = basePath+'/responses/'

var errorFilename = errorPath+'/error'
var resFilename = resPath+'/response'

/**
 * 确定目录是否存在,如果不存在则创建目录
 */
var confirmPath = function(pathStr) {
    if(!fs.existsSync(pathStr)){
        fs.mkdirSync(pathStr);
        console.log('createPath: ' + pathStr);
    }
}



log4js.configure({
    appenders:[
        {
            category:'console',
            type:'console'
        },
        {
            category:'errorLog',           //logger名称
            type:'dateFile',               //日志类型
            filename:errorFilename,        //日志输出位置
            alwaysIncludePattern:true,    //是否总是有后缀名
            pattern:'-yyyy-MM-dd-hh.log'   //后缀,每小时创建一个新的日志文件
        },
        {
            category:'responseLog',
            type: 'dateFile',
            filename: resFilename,
            alwaysIncludePattern:true,
            pattern: "-yyyy-MM-dd-hh.log"
        }
    ],
    replaceConsole:true              //是否替换console.log
})

//创建log的根目录'logs'
if(basePath){
    confirmPath(basePath)
    //根据不同的logType创建不同的文件目录
    confirmPath(errorPath)
    confirmPath(resPath)
}

module.exports = log4js

新建log.js文件:

var log4js = require('./log_config')

var errorLog = log4js.getLogger('errorLog')          //此处使用category的值
var resLog = log4js.getLogger('responseLog')         //此处使用category的值

var log = {}
log.i = function (ctx, resTime) {
    if(ctx){
        resLog.info(formatRes(ctx, resTime));
    }
}

log.e = function (ctx, error, resTime) {
    if(ctx&&error){
        errorLog.error(formatError(ctx, error, resTime));
    }
}

//格式化响应日志
var formatRes = function (ctx, resTime) {
    var logText = new String();

    //响应日志开始
    logText += "\n" + "*************** response log start ***************" + "\n";

    //添加请求日志
    logText += formatReqLog(ctx.request, resTime);

    //响应状态码
    logText += "response status: " + ctx.status + "\n";

    //响应内容
    logText += "response body: " + "\n" + JSON.stringify(ctx.body) + "\n";

    //响应日志结束
    logText += "*************** response log end ***************" + "\n";

    return logText;

}

//格式化错误日志
var formatError = function (ctx, err, resTime) {
    var logText = new String();

    //错误信息开始
    logText += "\n" + "*************** error log start ***************" + "\n";

    //添加请求日志
    logText += formatReqLog(ctx.request, resTime);

    //错误名称
    logText += "err name: " + err.name + "\n";
    //错误信息
    logText += "err message: " + err.message + "\n";
    //错误详情
    logText += "err stack: " + err.stack + "\n";

    //错误信息结束
    logText += "*************** error log end ***************" + "\n";

    return logText;
};

//格式化请求日志
var formatReqLog = function (req, resTime) {

    var logText = new String();

    var method = req.method;
    //访问方法
    logText += "request method: " + method + "\n";

    //请求原始地址
    logText += "request originalUrl:  " + req.originalUrl + "\n";

    //客户端ip
    logText += "request client ip:  " + req.ip + "\n";

    //开始时间
    var startTime;
    //请求参数
    if (method === 'GET') {
        logText += "request query:  " + JSON.stringify(req.query) + "\n";
        // startTime = req.query.requestStartTime;
    } else {
        logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
        // startTime = req.body.requestStartTime;
    }
    //服务器响应时间
    logText += "response time: " + resTime + "\n";

    return logText;
}

module.exports = log;

在app.js中配置使用

const log = require('./configs/log')
// logger
app.use(async (ctx, next) => {
    //响应开始时间
    const start = new Date();
    //响应间隔时间
    var ms;
    try {
        //开始进入到下一个中间件
        await next();

        ms = new Date() - start;
        //记录响应日志
        log.i(ctx, ms);

    } catch (error) {

        ms = new Date() - start;
        //记录异常日志
        log.e(ctx, error, ms);
    }

console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})