Adding timestamps to all console messages

前端 未结 12 1089
鱼传尺愫
鱼传尺愫 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:12
    app.use(morgan('[:date[web]] :method :url :status :res[content-length] - :remote-addr - :response-time ms'))
    
    0 讨论(0)
  • 2021-01-31 07:13

    module: "log-timestamp" works for me.

    see https://www.npmjs.com/package/log-timestamp

    npm install log-timestamp
    

    Simple to use

    console.log('Before log-timestamp');
    require('log-timestamp');
    console.log('After log-timestamp');
    

    Result

    Before log-timestamp
    [2012-08-23T20:08:32.000Z] After log-timestamp
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 07:16

    This implementation is simple, supports original functionality of console.log (passing a single object, and variable substitution), doesn't use external modules and prints everything in a single call to console.log:

    var origlog = console.log;
    
    console.log = function( obj, ...placeholders ){
        if ( typeof obj === 'string' )
            placeholders.unshift( Date.now() + " " + obj );
        else
        {
            // This handles console.log( object )
            placeholders.unshift( obj );
            placeholders.unshift( Date.now() + " %j" );
        }
    
        origlog.apply( this, placeholders );
    };
    
    0 讨论(0)
  • 2021-01-31 07:21

    It turns out, you can override the console functions at the top of the app.js file, and have it take effect in every other module. I got mixed results because one of my modules is forked as a child_process. Once I copied the line to the top of that file as well, all works.

    For the record, I installed the module console-stamp (npm install console-stamp --save), and added this line to the top of app.js and childProcess.js:

    // add timestamps in front of log messages
    require('console-stamp')(console, '[HH:MM:ss.l]');
    

    My problem now was that the :date format of the connect logger uses UTC format, rather than the one I'm using in the other console calls. That was easily fixed by registering my own time format (and as a side effect, requiring the dateformat module that console stamp comes with, rather than installing another one):

    // since logger only returns a UTC version of date, I'm defining my own date format - using an internal module from console-stamp
    express.logger.format('mydate', function() {
        var df = require('console-stamp/node_modules/dateformat');
        return df(new Date(), 'HH:MM:ss.l');
    });
    app.use(express.logger('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));
    

    Now my log files look organized (and better yet, parseable):

    [15:09:47.746] staging server listening on port 3000
    [15:09:49.322] connected to database server xxxxx successfully
    [15:09:52.743] GET /product 200 - - 127.0.0.1 - 214 ms
    [15:09:52.929] GET /stylesheets/bootstrap-cerulean.min.css 304 - - 127.0.0.1 - 8 ms
    [15:09:52.935] GET /javascripts/vendor/require.js 304 - - 127.0.0.1 - 3 ms
    [15:09:53.085] GET /javascripts/product.js 304 - - 127.0.0.1 - 2 ms
    ...
    
    0 讨论(0)
  • 2021-01-31 07:22

    You can use a function util.log from https://nodejs.org/api/util.html.

    Be aware that it was deprecated since version 6.0.0.

    For higher versions you should "Use a third party module instead."

    0 讨论(0)
提交回复
热议问题