1. 程式人生 > >如何在pm2 cluster模式下,使用winston-daily-rotate-file

如何在pm2 cluster模式下,使用winston-daily-rotate-file

問題:

最近用nodejs+express寫了一個WebServer類應用。其中使用pm2 cluster模式進行程序管理,nodejs程式碼中,使用winston-daily-rotate-file進行log記錄。其中winston-daily-rotate-file配置如下:


所以問題來了,發現其中maxFiles設定不起作用,winston-daily-rotate-file並沒有刪除多餘的日誌檔案

原因:

查看了一下winston-daily-rotate-file的原始碼,發現新版的winston-daily-rotate-file使用file-stream-rotator進行檔案rotation的管理,其中file-stream-rotator把所產生的的檔案資訊放入和檔案同目錄下的.audit.json中:


其中內容類似如下:

因為pm2的cluster模式會根據cpu的核數,啟動多個程序,但是winston-daily-rotate-file的配置,導致多個程序共享一個同一個目錄(也就是./logs),這會導致.audit.json相互覆蓋,從而丟失了一些日誌檔案的記錄資訊,因此file-stream-rotator無法對他們進行管理。

解決方案:

1,每個程序應該有自己的log資料夾,這樣不會產生.audit.json覆蓋的問題

2,要考慮重啟的問題,所以每個資料夾的名稱要相對穩定,每次重啟時,新的程序還是可以找到已經建立的.audit.json檔案,使得file-stream-rotator可以讀取這些已經建立的日誌的檔案資訊,並對他們進行管理,所以winston-daily-rotate-file的配置如下: