最近接了個新需求,讓在伺服器通過Nodejs去打日誌檔案,捕捉請求日誌。。。
然後我就想到了log4js……
廢話不多說,上程式碼
安裝log4js
npm install log4js --save
複製程式碼
對log4js不熟的檢視文件 log4js;
在config資料夾下新建log_config.js檔案:
var log4js = require("log4js");
var path = require("path");
var fs = require("fs");
var basePath = path.resolve(__dirname, "../logs");
var errorPath = basePath + "/errors/";
var resPath = basePath + "/responses/";
var errorFilename = errorPath + "/error";
var resFilename = resPath + "/response";
/**
* 確定目錄是否存在,如果不存在則建立目錄
*/
var confirmPath = function(pathStr) {
if (!fs.existsSync(pathStr)) {
fs.mkdirSync(pathStr);
console.log("createPath: " + pathStr);
}
};
log4js.configure({
appenders: {
errorLog: {
type: "dateFile", //日誌型別
filename: errorFilename, //日誌輸出位置
alwaysIncludePattern: true, //是否總是有字尾名
pattern: "-yyyy-MM-dd.log" //字尾,每小時建立一個新的日誌檔案
},
responseLog: {
type: "dateFile",
filename: resFilename,
alwaysIncludePattern: true,
pattern: "-yyyy-MM-dd.log"
}
},
categories: {
errorLog: { appenders: ['errorLog'], level: 'error' },
responseLog: { appenders: ["responseLog"], level: "info" },
default: { appenders: ['responseLog','errorLog',], level: 'trace' }
},
// pm2: true,
// pm2InstanceVar: 'INSTANCE_ID',
disableClustering: true
});
//建立log的根目錄'logs'
if (basePath) {
confirmPath(basePath);
//根據不同的logType建立不同的檔案目錄
confirmPath(errorPath);
confirmPath(resPath);
}
module.exports = log4js;
複製程式碼
這段程式碼中有解釋,照著官方文件配置就行;
在config資料夾下新建log.js檔案:
var log4js = require("./log_config");
var errorLog = log4js.getLogger("errorLog"); //此處使用category的值
var resLog = log4js.getLogger("responseLog"); //此處使用category的值
var log = {};
log.i = function(req, resTime) {
if (req) {
resLog.info(formatRes(req, resTime));
}
};
log.e = function(ctx, error, resTime) {
if (ctx && error) {
errorLog.error(formatError(ctx, error, resTime));
}
};
//格式化請求日誌
var formatReqLog = function(req, resTime) {
let getClientIp = function (req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress || '';
};
let ip = getClientIp(req).match(/\d+.\d+.\d+.\d+/);
var logText = new String();
//訪問方法
var method = req.method;
logText += "request method: " + method + "\n";
//請求原始地址
logText += "request originalUrl: " + req.originalUrl + "\n";
//客戶端ip
logText += "request client ip: " + ip + "\n";
//請求引數
if (method === "GET") {
logText += "request query: " + JSON.stringify(req.query) + "\n";
} else {
logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
}
//伺服器響應時間
logText += "response time: " + resTime + "\n";
return logText;
};
//格式化響應日誌
var formatRes = function(res, resTime) {
var logText = new String();
//響應日誌開始
logText += "\n" + "*************** response log start ***************" + "\n";
//新增請求日誌
logText += formatReqLog(res, resTime);
//響應狀態碼
logText += "response status: " + res.res.statusCode + "\n";
//響應內容
logText += "response body: " + "\n" + JSON.stringify(res.body) + "\n";
//響應日誌結束
logText += "*************** response log end ***************" + "\n";
return logText;
};
//格式化錯誤日誌
var formatError = function(ctx, err, resTime) {
var logText = new String();
//錯誤資訊開始
logText += "\n" + "*************** error log start ***************" + "\n";
//新增請求日誌
logText += formatReqLog(ctx, resTime);
//錯誤名稱
logText += "err name: " + err.name + "\n";
//錯誤資訊
logText += "err message: " + err.message + "\n";
//錯誤詳情
logText += "err stack: " + err.stack + "\n";
//錯誤資訊結束
logText += "*************** error log end ***************" + "\n";
return logText;
};
module.exports = log;
複製程式碼
這裡邊就是寫個三個函式,
- 格式化請求日誌 formatReqLog;
- 格式化響應日誌 formatRes;
- 格式化錯誤日誌 formatError;
在app.js中配置使用
const log = require("./config/log");
// logger
app.all("*", async (req, res, next) => {
//響應開始時間
const start = new Date();
//響應間隔時間
var ms;
ms = new Date() - start;
try {
//開始進入到下一個中介軟體
await next();
//記錄響應日誌
log.i(req, ms);
} catch (error) {
//記錄異常日誌
log.e(req, error, ms);
}
console.log(`${req.method} ${req.url} - ${ms}ms-${res.statusCode}`);
});
複製程式碼
程式碼沒啥可講的,照著使用就行,這裡我來談談踩過的坑吧
故障1: pm2 + log4js啟動專案時候報錯
Nodejs application Error: bind EADDRINUSE when use pm2 deploy
sudo lsof -i -P | grep 3000
複製程式碼
故障2: log4js搭配pm2叢集異常日誌
參考如下連結:log4js搭配pm2叢集異常日誌的解決方案
這是pm2在cluster模式下啟動,導致log4js不正常輸出日誌,有兩種解決方案嗎,
- 只需要在log_config.js裡新增如下命令就行
disableClustering: true
複製程式碼
i. 安裝pm2的pm2-intercom
程式間通訊模組
ii. 然後需要在log_config.js裡新增如下命令就行
pm2: true,
pm2InstanceVar: 'INSTANCE_ID'
複製程式碼
iii. pm2.json 如下
{ "apps": [
{ "name": "testing",
"script": "pm2.js",
"instances": 0,
"instance_var": "INSTANCE_ID", // 新增這一行
"exec_mode": "cluster"
}
]
}
複製程式碼
兩種解決方法的區別是:(摘自log4js作者的原話,能得到他的幫助,我特開心?)
you don’t need `disableClustering` and `pm2` in your config.
`pm2: true` turns on support for using pm2-intercom, `disableClustering: true` turns off all clustering support so it won’t use pm2-intercom.
Use one or the other, but not both.
複製程式碼
部署到伺服器上就能正常輸出日誌了,如下
歡迎溝通交流
最後參考文章如下: