Around IT in 256 seconds

Clean code, clean logs: easy to read, easy to parse (10/10)

May 19, 2010 | 2 Minute Read

There are two groups of receivers particularly interested in your application logs: human beings (you might disagree, but programmers belong to this group as well) and computers (typically shell scripts written by system administrators). Logs should be suitable for both of these groups. If someone looking from behind your back at your application logs sees:

from Wikipedia

then you were probably not reading my tips carefully enough. The reference to famous Clean code book in the title of this series is not accidental: logs should be readable and easy to understand just like the code should.

On the other hand, if your application produces half GiB of logs each hour, no man and no graphical text editor will ever manage to read them entirely. This is where old-school grep, sed and awk come in handy. If it is possible, try to write logging messages in such a way, that they could be understood both by humans and computers, e.g. avoid formatting of numbers, use patterns that can be easily recognized by regular expressions, etc. If it is not possible, print the data in two formats:

log.debug("Request TTL set to: {} ({})", new Date(ttl), ttl);
// Request TTL set to: Wed Apr 28 20:14:12 CEST 2010 (1272478452437)

final String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, true);"Importing took: {}ms ({})", durationMillis, duration);
//Importing took: 123456789ms (1 day 10 hours 17 minutes 36 seconds)

Computers will appreciate "ms after 1970 epoch" time format, while people would be delighted seeing "1 day 10 hours 17 minutes 36 seconds" text. BTW take a look at DurationFormatUtils, nice tool.

I thought this article is going to be short, but after writing it I decided to split it into 10 parts, each in separate post. Hope you enjoyed my logging series, although still not everything has been covered. This only proves how logging is important and how many pitfalls should be avoided. Remember, logging code should also be clean and reading your logs is supposed to be as pleasant as reading your code.

Tags: commons, logging

Be the first to listen to new episodes!

To get exclusive content: