Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Patterns: Logs are Instant Insight

Has this ever happened to you: a program crashes, and all you get is a black screen or a set of meaningless numbers?

I know it happens to me.

Even the better programs designed by, say, Microsoft, we get an error report containing numbers that mean absolutely nothing to human beings – it’s designed for computers only.

And yet, Microsoft has basically the right idea.

Logs tell us what’s happening

At its most basic, a log is a message that a program prints out for later reference. These messages can be as simple or complex as the programmer desires, but the programmer has to decide when these logs are printed and what they’ll say.

Commonly (assuming you don’t have your own log utilities), we use formatted text strings passed out to the standard error stream. These logs look a bit like:

fprintf(stderr, “%s:%d\tERROR HAPPENED HERE\n”, __FILE__, __LINE__);

This log message consists of a few key parts:

  • fprintf – a function that allows us to print to any stream we choose (files, output or input streams, etc)
  • stderr – the standard error output stream
  • A formatted string detailing the error information
    • __FILE__ is a macro that returns the name of the file in which this error is thrown
    • __LINE__ is a macro that returns the line number on which this error is written

With logs like these, we can rapidly pinpoint where errors have occurred and what kind of error has occurred.

Logs: For good times and bad

Most programmers only think of log messages when something goes wrong, but I argue that logs are essential in both paths of the tree:

  • If it fails, you want to know where, why, and how it failed
  • If it didn’t fail, you want to know that it worked
  • If it failed where you didn’t expect, you want to know that the “it worked” message didn’t happen

These logs allow the programmer to determine how much information he wants to see, and where in the code these messages should appear. As a result, the flow of information out of the program is determined by the sort of programmer who is likely to be maintaining the code in the future.

Lesson: Logs can provide a wealth of debugging and operations information, so long as the programmer designs that functionality into the code.

photo by: