Clean code, clean logs: easy to read, easy to parse (10/10)
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);
log.info("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.
- Clean code, clean logs: use appropriate tools (1/10)
- Clean code, clean logs: logging levels are there for you (2/10)
- Clean code, clean logs: do you know what you are logging? (3/10)
- Clean code, clean logs: avoid side effects (4/10)
- Clean code, clean logs: concise and descriptive (5/10)
- Clean code, clean logs: tune your pattern (6/10)
- Clean code, clean logs: log method arguments and return values (7/10)
- Clean code, clean logs: watch out for external systems (8/10)
- Clean code, clean logs: log exceptions properly (9/10)
- Clean code, clean logs: easy to read, easy to parse (10/10)