我有一個Node.js應用程序與systemd設置。 NGINX後面運行的應用程序。
我想在日誌訪問NGINX文件中添加Node.js應用程序的控制檯輸出?
我該怎麼做?如何在日誌訪問NGINX文件中添加控制檯輸出Node.js應用程序?
在此先感謝。
我有一個Node.js應用程序與systemd設置。 NGINX後面運行的應用程序。
我想在日誌訪問NGINX文件中添加Node.js應用程序的控制檯輸出?
我該怎麼做?如何在日誌訪問NGINX文件中添加控制檯輸出Node.js應用程序?
在此先感謝。
更簡單的方法是掛鉤console.log
,並呼籲console.log
作爲一般。
var util = require('util');
var JFile = require("jfile");
var nxFile = new JFile('/var/log/nginx/access.log');
...
process.stdout.write = (function(write) {
return function(text, encoding, fd) {
write.apply(process.stdout, arguments); // write to console
nxFile.text += util.format.apply(process.stdout, arguments) + '\n'; // write to nginx
}
})(process.stdout.write);
您也可以通過改變在stdout
代碼限定鉤console.error
到strerr
上方。
P.S.我沒有nginx來驗證代碼。所以代碼可以包含錯誤:)
使用JFile包,文件記錄可以流暢如下:
nxFile.text+='\n'+message;
添加功能上都(終端+ nginx的日誌)記錄,然後使用它代替直接使用console.log
:
var customLog=function(message){
console.log(message);
logNginx(message);
}
然後,實施logNginx這就是所謂的內部的CustomLog:
var JFile=require('jfile'); // "npm install jfile --save" required
let nxFile=new JFile('/var/log/nginx/access.log'); // check path before if exist in your system . IF no , change it with the available path
function logNginx(message){
nxFile.text+='\n'+message; //append new line in nginx log file
}
不要忘記安裝JFile npm install jfile
這使得處理文件迅速完成。
您可以在您的nginx腳本中添加以下代碼。這應該工作
env NODE_BIN=/usr/bin/node
env SCRIPT_FILE="server.js"
env LOG_FILE=/var/log/logfilename.log
env RUN_AS="root"
$RUN_AS -- $NODE_BIN $SCRIPT_FILE >> $LOG_FILE 2>&1