简体   繁体   中英

Logging in node.js to a file, without another module

I'm running a node application as a daemon. When debugging the daemon, I need to see the output, so I'd like to redirect stdout and stderr to a file.

I'd expect I can just reassign stdout and stderr like in Python or C:

fs = require('fs');
process.stdout = fs.openSync('/var/log/foo', 'w');
process.stderr = process.stdout;
console.log('hello');

When I run the script directly, "hello" is printed to the console! Of course when I run in the background, I see output neither on the console (of course) or in /var/log/foo .

I don't want or need sophisticated logging. I just need to see the builtin messages that node already provides.

The console object grabs a reference to process.stdout and stderr when it is first created.
(you can see this in the source ).

Re-assigning them later does not affect console .

The usual way to redirect these streams is to launch the process with the streams redirected.

Alternatively, you can overwrite the console methods and make them write to your file instead.

Similar to this question , you can overwrite process.stdout.write which is called from console.log .

var fs = require('fs');
var oldWrite = process.stdout.write;

process.stdout.write = function (d) {
    fs.appendFileSync('./foo', d);
    oldWrite.apply(this, arguments);
};

console.log('hello');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM