Search code examples
node.jsnginxsystemd

How to add console outputs Node.js app in the log access NGINX file?


I have an Node.js app setting up with systemd. The app running behind NGINX.
I would like to add console output of my Node.js application in the log access NGINX file ?
How can I do this ?

Thanks in advance.


Solution

  • 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 :)