Around IT in 256 seconds

Clean code, clean logs: concise and descriptive (5/10)

May 07, 2010 | 1 Minute Read

Each logging statement should contain both data and description. Consider the following examples:

log.debug("Message processed");
log.debug("Message with id '{}' processed", message.getJMSMessageID());

Which log would you like to see while diagnosing failure in an unknown application? Believe me, all the examples above are almost equally common. Another anti-pattern:

if(message instanceof TextMessage)
log.warn("Unknown message type");

Was it so hard to include actual message type, message id, etc. in warning string? I know something went wrong, but what, what was the context? Third anti-pattern is "magic-log". Real life example: most programmers in the team knew that 3 ampersands followed by exclamation mark, followed by hash, followed by pseudorandom alphanumeric string log means "Message with XYZ id received". Nobody bothered to change the log, simply someone hit the keyboard and chose some unique "&&&!#" string, so that it can be easily found by himself.

As a consequence, the whole logs file looks like a random sequence of characters. Somebody might even consider that file to be a valid Perl program. But the logs file should be readable, clean and descriptive. Don't use magic numbers, log values, numbers, ids and include their context. Show the data being processed and show its meaning. Show what the program is actually doing. Good logs can serve as a great documentation of the application code itself.

Did I mention not to log passwords and any personal information? Don't!

Tags: logging

Be the first to listen to new episodes!

To get exclusive content: