4

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?

4 Answers 4

10

I think the simple way is to use linux I/O redirection. Just run your application in this way:

node app.js > log.txt 

Then all output messages from your app will be redirected to log.txt

Sign up to request clarification or add additional context in comments.

Comments

3

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'); 

1 Comment

Here is the complete code of node/console.js on [github][1] [1]: github.com/nodejs/node/blob/master/lib/console.js
0

Another great way to do this with more granular control on your logs is using winston. See the file transport here: https://github.com/winstonjs/winston/blob/master/docs/transports.md#file-transport

Comments

0

Here's another way to do it using ES6 proxies. Most credit goes to https://2ality.com/2015/10/intercepting-method-calls.html

function traceMethodCalls(obj) { return new Proxy(obj, { get(target, methodName, receiver) { // get origin method const originMethod = target[methodName]; return function(...args) { // write to file here // call origin method return originMethod.apply(this, args); }; } }); } console = traceMethodCalls(console); console.log("log"); console.warn("warn"); console.error("error"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.