
Question:
I have an Node.js app setting up with systemd. The app running behind NGINX.<br /> I would like to add console output of my Node.js application in the log access NGINX file ?<br /> How can I do this ?
Thanks in advance.
Answer1:More simple way is hook console.log
and call console.log
as usually.
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);
Also you can define hook to console.error
by change stdout
to strerr
in code above.
P.S. I don't have nginx to verify code. So code can contains errors :)
Answer2:Brief :
Using <a href="https://github.com/abdennour/jfile" rel="nofollow">JFile</a> package , file logging can be smooth as following :
nxFile.text+='\n'+message;
Details :Add function that logs on both (Terminal+nginx log) , then use it instead of using console.log
directly :
var customLog=function(message){
console.log(message);
logNginx(message);
}
Then , implement <strong>logNginx</strong> which is called inside <strong>customLog</strong> :
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
}
<hr />Don't forget to install JFile npm install jfile
which makes handling files done quickly .
You can add the following code in your nginx script . This should work
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