Common logging mistakes — Missing context and hints
Logs are often our only way to diagnose problems that arise while an application is running. A common mistake is leaving out the context that would let someone work out what may have happened without seeing the source code. I’ll illustrate this with a small shopping cart example written for the purpose.
public class ShoppingCart {
private List items;public void addItem(Object o) {
if(o instanceof Item) {
items.add(o);
} else {
LOGGER.warn("Object is not of type Item");
}
}
}The trouble with that log message is that it only tells you what happened. That’s useful only if you have the source code and understand the consequences. If a problem shows up several layers of abstraction higher, as it typically does, you’ll have a hard time finding the cause. A good message tells you what happened and what effect it had.
LOGGER.warn("Cannot add item {} to shopping basket because is not of type Item.", o);The new message keeps the original information and explains what happened. We couldn’t add the item, so it won’t be in the cart. If we know how that situation could have arisen, it’s worth logging that too. A hint like that can save a lot of work.
LOGGER.warn("Cannot add item {} to shopping basket because is not of type Item. It may be caused by using an old version of client. Please check the log, version 2.0 or higher is required by add item operation.", o);If messages like these might swamp the log and you need to save space, you can point readers to an explanation. Use a key in a log event glossary or link to a specific page that provides the same context.
LOGGER.warn("Cannot add item {} to shopping basket because is not of type Item. See WARN-123", o);LOGGER.warn("Cannot add item {} to shopping basket because is not of type Item. See http://bit.ly/1g3eFoK", o);With a little effort, it’s easy to provide enough context for someone unfamiliar with the source code to understand what happened, what effect it had, and ideally how it may have happened. Take logging seriously even if you always have the source code handy. In our example, the hint gives us a lasting explanation of an external condition that we’d have a hard time remembering later. It isn’t apparent from the code of the class itself.
Earlier articles on logging — A Few Tips for Better Logs
Related articles
Related CZ Podcast episodes
- #261 · Leadership
On leading people and teams. · Czech audio