node.js express使用log4js記錄日誌

創建log.js

var log4js = require('log4js');
log4js.configure({
    appenders: [
        {
            type: 'console',
            category: "console"
        }, //控制檯輸出
        {
            type: "dateFile",
            filename: 'logs/log.log',
            pattern: "_yyyy-MM-dd",
            alwaysIncludePattern: false,
            category: 'dateFileLog'
        }//日期文件格式
    ],
    replaceConsole: true,   //替換console.log
    levels:{
        dateFileLog: 'INFO'
    }
});

var dateFileLog = log4js.getLogger('dateFileLog');

exports.logger = dateFileLog;

exports.use = function(app) {
    //頁面請求日誌,用auto的話,默認級別是WARN
    //app.use(log4js.connectLogger(dateFileLog, {level:'auto', format:':method :url'}));
    app.use(log4js.connectLogger(dateFileLog, {level:'debug', format:':method :url'}));
}

在app.js中添加以下代碼,由於加載順序的原因,放在其他app.use前面

var log = require('./log');
log.use(app);

功能中記錄日誌,require路徑根據自己項目修改:

var logger = require('../log').logger;
logger.info("this is log");

需要注意的是,如果日誌使用的是日期(如本例子),即一天一個文件,測試的話,直接修改日期測試,是不會生產新的日期日誌的,必須把時間調爲晚上23點59分,然後等着過整點,這時候可以測試是否會生成新的文件,官方例子說明如下(https://github.com/nomiddlename/log4js-node/wiki/Date%20rolling%20file%20appender):


Then initial logging would create a file called "blah.log".At midnight, the current "blah.log" file would be renamed to "blah.log-2012-09-26" (for example), and a new "blah.log" file created.

發佈了119 篇原創文章 · 獲贊 21 · 訪問量 101萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章