Debug logging in Java
Some people really dislike debug log messages in production code. Though they can be extremely useful, I think a lot of developers are turned off to the fact that when logging is done poorly, it really makes the code look like a mess. For example, we’ve all seen code like this:
The developer basically just dumped the stack to debug a specific problem they were having. This is one of a combination of factors that make code painful to read when logging is involved:
- poor/no grammar
- multiple log statements per method
- excessive string concatenation
Sometimes, I like to create a helper method for logging in Java to make things more readable:
The next thing to do is to follow certain guidelines with respect to uniformity and sentence structure. For example:
I think this ends up being a lot more useful in terms of code clarity and actual output. Loggers like slf4j and log4j2 can already do this out of the box and even provide support for deferred lambda expressions: