Applications of Log4J with Use Cases

In this section, I’ll present a handful of Use Cases that I hope you’ll find useful. Each Use Case will present a problem, followed by the solution to that problem. Some of these you will have already seen in the Short Cut, but I wanted to consolidate the usage patterns I’ve found to be helpful here in one place.

Decouple an Object from its Logged Form

Problem

Every now and then, you may find that you want to just log an object, and let log4j figure out how to transform the object into something useful.

Solution

Log4j has an interface called an ObjectRenderer, which is at the center of log4j’s Object Rendering mechanism. Object Rendering is what log4j uses for every object that it is asked to log—if that object doesn’t get dropped, that is—and is log4j’s formal way to control the String representation of an object and allows for its configuration external to your application. Let’s take a closer look.

There are basically three paths log4j’s infrastructure takes when formatting a message to be logged:

  1. Object to be logged is already a String. Nothing further needs to be done.

  2. Object to be logged has no ObjectRenderer associated with it. Call toString() on the object.

  3. Object to be logged has an ObjectRenderer associated with it. Call doRender() on the object.

Most of the time, you will be passing objects of type java.lang.String to the various log4j API methods. But in those cases where you want to simply “throw” an object at the log4j API, Object Rendering ...

Get Log4J now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.