This should be a trivial question but I don't seem to get my mind around it. Is there any simple way to just redirect all my console.log
output to a file? console.log
formats the objects provided in a way that is nice and interacts properly with objects that are not trivial JSONable objects.
For example, if I do
var myerr = new Error('There has been an error');
console.log(myerr);
I get
[Error: There has been an error.]
While if I just do
process.stdout.write(JSON.stringify(myerr));
I get
{}
And if I do
process.stdout.write(myerr.toString());
I get
Error: There has been an error
So if I override my console.log
with a function that loops on its arguments with any of the tricks above and redirects the output to a file the log will not be exactly the same.
So I wonder: what does console.log
do to process the objects it is provided with before outputting them to the console? It just calls .toString()
on every object, wraps things with []
and sends everything to process.stdout.write
? Or does it do some other kind of preprocessing?
I think the simples way to use linux I/O redirection. Just run your application in this way:
node app.js > log.txt
all output messages from your app will be redirected to log.txt
The code of Console reads:
Console.prototype.log = function() {
this._stdout.write(util.format.apply(null, arguments) + '\n');
};
You can simply do
const util = require('util');
process.stdout.write(util.format.apply(null, arguments) + '\n');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With