最近接了個新需求,讓在服務器經過Nodejs去打日誌文件,捕捉請求日誌。。。
而後我就想到了log4js……html
廢話很少說,上代碼node
npm install log4js --save
複製代碼
對log4js不熟的查看文檔 log4js;git
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;
複製代碼
這段代碼中有解釋,照着官方文檔配置就行;github
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;
複製代碼
這裏邊就是寫個三個函數,npm
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}`);
});
複製代碼
代碼沒啥可講的,照着使用就行,這裏我來談談踩過的坑吧json
Nodejs application Error: bind EADDRINUSE when use pm2 deployvim
sudo lsof -i -P | grep 3000
複製代碼
解決該問題戳這裏;segmentfault
參考以下連接:log4js搭配pm2集羣異常日誌的解決方案
bash
這是pm2在cluster模式下啓動,致使log4js不正常輸出日誌,有兩種解決方案嗎,服務器
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.
複製代碼
歡迎溝通交流
最後參考文章以下: