Adding timestamps to all console messages

前端 未结 12 1337
鱼传尺愫
鱼传尺愫 2021-01-31 06:51

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

12条回答
  •  眼角桃花
    2021-01-31 07:15

    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.

提交回复
热议问题