最近接了個新需求昏名,讓在服務(wù)器通過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";
/**
* 確定目錄是否存在嗽交,如果不存在則創(chuàng)建目錄
*/
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" //后綴,每小時創(chuàng)建一個新的日志文件
},
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
});
//創(chuàng)建log的根目錄'logs'
if (basePath) {
confirmPath(basePath);
//根據(jù)不同的logType創(chuàng)建不同的文件目錄
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";
//請求參數(shù)
if (method === "GET") {
logText += "request query: " + JSON.stringify(req.query) + "\n";
} else {
logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
}
//服務(wù)器響應(yīng)時間
logText += "response time: " + resTime + "\n";
return logText;
};
//格式化響應(yīng)日志
var formatRes = function(res, resTime) {
var logText = new String();
//響應(yīng)日志開始
logText += "\n" + "*************** response log start ***************" + "\n";
//添加請求日志
logText += formatReqLog(res, resTime);
//響應(yīng)狀態(tài)碼
logText += "response status: " + res.res.statusCode + "\n";
//響應(yīng)內(nèi)容
logText += "response body: " + "\n" + JSON.stringify(res.body) + "\n";
//響應(yīng)日志結(jié)束
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";
//錯誤信息結(jié)束
logText += "*************** error log end ***************" + "\n";
return logText;
};
module.exports = log;
這里邊就是寫個三個函數(shù),
- 格式化請求日志 formatReqLog沃疮;
- 格式化響應(yīng)日志 formatRes盒让;
- 格式化錯誤日志 formatError;
在app.js中配置使用
const log = require("./config/log");
// logger
app.all("*", async (req, res, next) => {
//響應(yīng)開始時間
const start = new Date();
//響應(yīng)間隔時間
var ms;
try {
//開始進(jìn)入到下一個中間件
await next();
//記錄響應(yīng)日志
ms = new Date() - start;
log.i(req, ms);
} catch (error) {
//記錄異常日志
ms = new Date() - start;
log.e(req, error, ms);
}
console.log(`${req.method} ${req.url} - ${ms}ms-${res.statusCode}`);
});
代碼沒啥可講的司蔬,照著使用就行邑茄,這里我來談?wù)劜冗^的坑吧
故障1: pm2 + log4js啟動項(xiàng)目時候報錯
Nodejs application Error: bind EADDRINUSE when use pm2 deploy
sudo lsof -i -P | grep 3000
故障2: log4js搭配pm2集群異常日志
參考如下鏈接:log4js搭配pm2集群異常日志的解決方案
這是pm2在cluster模式下啟動俊啼,導(dǎo)致log4js不正常輸出日志肺缕,有兩種解決方案嗎,
- 只需要在log_config.js里添加如下命令就行
disableClustering: true
i. 安裝pm2的pm2-intercom
進(jìn)程間通信模塊
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"
}
]
}
兩種解決方法的區(qū)別是:(摘自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.
部署到服務(wù)器上就能正常輸出日志了同木,如下
歡迎溝通交流
<img src='https://user-gold-cdn.xitu.io/2018/6/19/16417078c2513e99'>
最后參考文章如下: