Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect console.log output to file

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?

like image 874
Matteo Monti Avatar asked Dec 18 '22 17:12

Matteo Monti


2 Answers

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

like image 128
sergiy.dragunov Avatar answered Dec 29 '22 12:12

sergiy.dragunov


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');
like image 43
randominstanceOfLivingThing Avatar answered Dec 29 '22 12:12

randominstanceOfLivingThing