perennial_
perennial_

Reputation: 1846

Intercept console logs to file Nodejs

I am working on a game using NodeJs, and realized it would be immensly helpful to have access to old console.log output. The mechanics and calculations get rather complicated, and it would be nice to have access to them later to search through and do some data analysis on them to find the correct values for my modifiers (battle mechanics). At the same time, I want to see console.log in the console as well.


I know this isn't possible with regular javascript, (see This), but I was hoping npm had a package of some way to intercept logs and log them to a file on the server. Any thoughts?

Upvotes: 4

Views: 6019

Answers (3)

Gajus
Gajus

Reputation: 73928

The purest form would be by overriding stdout and stderr methods, e.g.

process.stdout.write = (data) => {
  w(data);
};

process.stderr.write = (data) => {
  w(data);
};

Here w is whatever mechanism that you would like to use to record this data, e.g.

const w = (...args) => {
  appendFileSync(
    path.resolve(__dirname, "test.json"),
    JSON.stringify(args, null, "  ")
  );
};

Beware that you cannot output anything from this function as that would cause an infinite loop.

The above behaviour would discard any output though. If you want the program to continue producing output, then you need to call the original write methods, e.g.

const stdoutWrite = process.stdout.write.bind(process.stdout);
const stderrWrite = process.stderr.write.bind(process.stderr);

process.stdout.write = (data, callback) => {
  w(data);

  return stdoutWrite(data, callback);
};

process.stderr.write = (data, callback) => {
  w(data);

  return stderrWrite(data, callback);
};

Upvotes: 2

Mauri Edo
Mauri Edo

Reputation: 397

An NPM option to log to stdout and to a file at the same time could be Winston. Winston is a logging library that allows you to define your own loggers, specifying their transports (a transport being what do you do with these log lines). In your case, you could define a logger with two transports, stdout and a log file. Example (inspired by the Winston documentation):

const winston = require('winston');

let logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)(),
        new (winston.transports.File)({ filename: 'somefile.log' })
    ]
});

logger.info('hello, world!');

If you run this code above, you'll see the logs in the console and in somefile.log.

Upvotes: 8

jshawl
jshawl

Reputation: 3483

You can intercept console.log like so

var cl = console.log

console.log = function(...args){
  // your custom logging logic here
  cl.apply(console, args)
}

Upvotes: 14

Related Questions