Better native logging in Node.js

Published on November 21, 2017 under Blog

I often have to read through piles of logs for different programs. Levels of sophistication and approaches to logging differ from program to program, but I think everyone would agree that there is a certain bare minimum of data your logs should contain to be useful. Not only that, I'd go further and say that it's your obligation as a developer of an open-source/public project to make your logs look nice.

Better native Node.js logs

There are a lot of amazing logging libraries out there (pino, bunyan, winston, etc.). The only issue is that these libraries tend to require some time to setup and understand, and it's totally alright if you're not willing to put in the effort.

That said, there are still ways you can improve your console output without using external libraries. Here's a nice 13 line function that makes your logs look much nicer:

let log = () => {
    let now = new Date();
    let options = {
        hour12: false,
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    let timeString = now.toLocaleString('en-us', options);
    let args = [];
    console.log.apply(null, [`[${timeString}]`].concat(args));

This function is simply a wrapper for console.log(...). It prepends a (configurable) timestamp to your console output and makes it easier to follow the timeline of your logs. Some usage examples:

log('Logging is cool!');
// [Nov 21, 2017, 00:46] Logging is cool!

log('Hello', {a: 1, b: 2, c: 3});
// [Nov 21, 2017, 00:47] Hello { a: 1, b: 2, c: 3 }

log(new Error('I am an error.'));
// [Nov 21, 2017, 00:48] Error: I am an error.
//     at Glitter.connect (...)
//     at Object.<anonymous> (...)
//     at Module._compile (...)
//     ...

// [Nov 21, 2017, 00:49]

That's not much, but it's already a step in the right direction. Replace your plain logging with my function and I'll love you forever.

For bonus points, export this function as a part of your Util module to make it easier to use. For even more bonus extra points, use a proper logging library.

End of Article

Timur Kuzhagaliyev Author

I'm a computer science graduate from UCL & Caltech, working as a systems engineer at Jump Trading. Before Jump, I was doing computer vision for Video Quality Analysis team at Amazon.