最近在爲服務端添加日誌,主要是利用PM2和winston、log4js,現將遇到的問題記錄下來。html
PM2被用於生產環境下進程管理,可以及時獲取業務代碼中日誌信息。node
PM2 可以得到項目中 winston.log.error
or console.log.info
信息。基本配置以下,訪問localhost:8087,會在error_file
打印出一條日誌。git
PS:建議不用直接使用console.log來輸出日誌信息,減小性能損耗。github
// pm2.js apps : [ { name : projectName, script : 'app.js', env: { NODE_ENV: 'development', PORT: 8087 }, log_file : logFile, error_file : errorFile, out_file : outFile, merge_logs : true, log_date_format : 'YYYY-MM-DD HH:mm Z' } ] // app.js const Koa = require('koa'); const app = new Koa(); const winston = require('winston'); app.use(async ctx => { if (ctx.request.path === '/') { winston.log.error('測試日誌'); } ctx.body = 'Hello World'; }); app.listen(8087);
log4js 在cluster模式時,worker進程將日誌發送給master進程,而後記錄到文件。但pm2 在cluster模式時,是將全部進程當作worker進程。致使log4js 在 PM2 cluster下不輸出日誌。json
測試代碼以下:app
// logger.js const log4js = require('log4js'); log4js.configure({ appenders: { out: { type: 'file', filename: 'pm2logs.log' } }, categories: { default: { appenders: ['out'], level: 'info' } } }); const logger = log4js.getLogger('app'); setTimeout(() => { logger.info("I'm forever blowing bubbles"); }, 1000);
pm2.json 文件以下koa
{ "apps": [ { "name": "testing", "script": "logger.js", "instances": "max", "exec_mode": "cluster" } ] }
修復方法以下,須要安裝pm2的pm2-intercom進程間通訊模塊async
const log4js = require('log4js'); // NOTE: for PM2 support to work you'll need to install the pm2-intercom module // `pm2 install pm2-intercom` log4js.configure({ appenders: { out: { type: 'file', filename: 'pm2logs.log' } }, categories: { default: { appenders: ['out'], level: 'info' } }, pm2: true, pm2InstanceVar: 'INSTANCE_ID' }); const logger = log4js.getLogger('app'); setTimeout(() => { logger.info("I'm forever blowing bubbles"); }, 1000);
pm2.json 以下性能
{ "apps": [ { "name": "testing", "script": "pm2.js", "instances": 0, "instance_var": "INSTANCE_ID", "exec_mode": "cluster" } ] }
PM2 cluster or Node cluster 真有好處嗎?好處能有多大?測試
經過什麼樣的壓力測試才能檢驗出性能,才能查看系統的魯棒性?
如何作小流量?