How to Intercept Console Output

Intercept calls to console.log in Chrome

You need to call console.log in the context of console for chrome:

(function () {
var log = console.log;
console.log = function () {
log.call(this, 'My Console!!!');
log.apply(this, Array.prototype.slice.call(arguments));
};
}());

Modern language features can significantly simplify this snippet:

{
const log = console.log.bind(console)
console.log = (...args) => {
log('My Console!!!')
log(...args)
}
}

Is it possible to intercept Console output?

Yes, very much possible:

var consoleOut = new StringWriter();
Console.SetOut(consoleOut);
Console.WriteLine("This is intercepted."); // This is not written to console
File.WriteAllText("ConsoleOutput.txt", consoleOut.ToString());

Later on if you want to stop intercepting the console output, use modification below:

var stdOut = Console.Out;
// Above interceptor code here..
Console.SetOut(stdOut); // Now all output start going back to console window

Or the OpenStandardOutput does the same without the need to save the standard stream first:

// Above interceptor code here..
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput); // Now all output starts flowing back to console

Intercept console logs to file Nodejs

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.

How to overwrite / intercept console.log and output original log to console

You're looking for:

logger.apply(console, arguments);

...which calls the original function with this set to console and with arguments spread out as discrete arguments.


Side note: If you want to be broadly-compatible, you'll need to replace the ES2015+ code here:

window["log"].push({arguments});

with ES5-compatible code:

window["log"].push({arguments: arguments});

How to collect all console outputs or access current content of console in frontend

It's a better approach, if you do not rely on the console. It's up to you, but I say that letting an error reaching the console is not a best practice. You can catch the errors before they arrive on the console anyway.

  • For HTTPClient errors, you can use an error Iterceptor
  • For Angular "code" errors, I recommend using a Global Error Handler


Related Topics



Leave a reply



Submit