I have a complete, deployed, Express-based project, with many console.log() and console.error() statements throughout. The project runs using forever, directing the st
I'm trying overwriting the console object - seems to be working well. To use, save the code below in a file, and then import to overwrite the proxy object, and then use as normal.
(Note this requires babel transpilation and won't work in environments that don't support the JavaScript Proxy constructor such as IE 11).
import console from './console-shadow.js'
console.log(...)
console.warn(...)
console.error(...)
// console-shadow.js
// Only these functions are shadowed by default
const overwrites = ['log', 'warn', 'info', 'error']
export default new Proxy(
// Proxy (overwrite console methods here)
{},
// Handler
{
get: (obj, prop) =>
prop in obj
? obj[prop]
: overwrites.includes(prop)
? (...args) => console[prop].call(console, new Date(), ...args)
: console[prop],
}
)
Basically I overwrite the console object with a JavaScript proxy object. When you call .log, .warn, etc. the overwritten console will check if what you are calling is a function, if so it will inject a date into the log statement as the first parameter, followed by all your parameters.
I think the console object actually does a lot, and I don't fully understand it. So I only intercept console.log, console.info, console.warn, console.error calls.