The art of logging

Writing logs is hard.

Logging is the time-machine for your future self, of future colleague.

But it's difficult to imagine what you'd like to know in the future. So you may end up writing logs for everything, because you can never know too much, right?

Well, you can get a lot of noise in your logs.

Logs also adds clutter to the code. Almost like comments, if you commented each and every step - why don't you just read the code? Why do you think they call it code?

function getClosestAddress(coordinate) {
    // reverse lookup lat/lon
    const addresses = geocoder.reverseLookup(coordinate.lat, coordinate.lon);
    
    // assume list already sorted, return first item
    return addresses[0];
}

Does the comments add any value?

Let's consider the same block of code, with comments replace with logs.

function getClosestAddress(coordinate) {
    logInfo('reverse lookup lat/lon');
    const addresses = geocoder.reverseLookup(coordinate.lat, coordinate.lon);
    
    logInfo('assume list already sorted, return first item');
    return addresses[0];
}

No material difference. Code now looks a little less readable, since comments are usually dimmed in the editor.

But now your logs can tell you how the function was called, how far it got. That can be valuable, only the messages logged are pretty useless when things go wrong.

If the function works most of the time, but fails occasionally then you'd like to know the coordinate details and get a hint of the result you get back from the geocoder

function getClosestAddress(coordinate) {
    logInfo(`reverse lookup ${coordinate.lat}/${coordinate.lon}`);
    const addresses = geocoder.reverseLookup(coordinate.lat, coordinate.lon);
    
    logInfo(`${addresses?.length || 0} sorted, return first item`);
    return addresses[0];
}

Adding more value to the logs, but what does it do to the code?

You need to be aware of possible null values when writing logs, provide sensible fallback values.

Logging is almost a parallel program, next to your actual program.

Scale this up to 20-50-200 lines of code, and you're in for a real threat.

Yuck!

Martin H. Normark

Martin H. Normark

Product and UX Hacker. Web and iOS developer.
Denmark