node.js express使用log4js記錄日誌__js

來源:互聯網
上載者:User

建立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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.