Categories: NodeJS

NodeJS – 為 console.log 加上時間與檔案紀錄。

如果你有開發 Node.js 的經驗,一定相當常運用其內建的 console.log() 來作為 Debug 的方式之一。

而當整個系統完成或上線之後,就比較無法使用這種方式去找後續發生的問題,因為我們不見得能看到系統端終端機中的內容,但若為了這個紀錄功能要多寫一個 function 然後替換掉原本拿來 debug 用的 console.log …這也太麻煩了吧。

幸運的是,JavaScript 允許你用 Override 的方式來覆寫原有的程式,改成你所需要的樣子。

等一下我們就要來覆寫 console.log 這個 function 來為它加入時間戳記以及寫入一個檔案作為紀錄的功能。

開始之前

在這支程式中,我為了方便產生時間格式,有使用到 date-utils 這個模組,所以請記得在你的 Node.js 專案資料夾中安裝

npm install date-utils --save

並在程式碼上方加入

require('date-utils')

已便使用這個模組提供的 toFormat 功能。

程式碼

在你的程式中加入:

// log override
console.log=(function() {
      var orig = console.log;
      return function() {
        try {
          var tmp=process.stdout;
          process.stdout=process.stderr;
          // get now
          var now = new Date();
          // format time
          var now_formated = now.toFormat("YYYY-MM-DD HH24:MI:SS");
          var strDate = '[' + now_formated + '] ';
          if (Buffer.isBuffer(arguments[0])) {
            arguments[0] = strDate + arguments[0];
          } else if (typeof arguments[0] !== 'object') {
            arguments[0] = strDate + arguments[0];
          } else if (typeof arguments[0] === 'object') {
            arguments[0] = strDate + JSON.stringify(arguments[0]);
          }
          orig.apply(console, arguments);
        } finally {
          process.stdout=tmp;
        }
    };
})();

然後執行你的程式,應該就會看到類似下方的訊息,這樣是不是更好紀錄與找問題了呢?

[2015-12-19 20:15:35] Hello, World!

參考來源:http://davidherron.com/blog/2014-04-26/overriding-consolelog-nodejs-and-other-thoughts-about-logging-node-apps

duye.chen

Recent Posts

[教學] 打造你的 NFT 智能合約 – ERC721A

GM!前些日子在幣圈亂玩,一路...

2 年 ago

JavaScript – Singleton 設計模式

前言 在設計程式時,我們有時會...

3 年 ago

PlaidML 讓你的 Mac 也能加速 Tensorflow 機器學習!

相信很多使用 Mac 或者手上...

3 年 ago

RESTful API 測試很煩,只好動手寫屬於自己的測試了

寫在最前面 嗨,大家好久不見!...

3 年 ago

Node.js 與 Socket.io – 即時聊天室實作:資料庫

經過前兩篇(一、二)文章,我們...

6 年 ago