chapter seven

7 Advanced Log4j

 

This chapter covers

  • Creating a simple application with logging
  • Filtering log messages based on intent
  • Creating message classes for reusing logging code
  • Making use of the ThreadContext for adding contextual information
  • Using the fluent logging API

In this chapter, we will build a simple application that uses a similar structure to a real application. Within this codebase, we will implement some advanced logging features. That way, logging is not theoretical, and you can adapt the ideas into your own projects.

I will not explain all the details of the application, but the nuts and bolts: How the general behavior works so that you can understand the logging behaviors. For the rest, I will add comments in the code repository.

The application is a simple command-line system. It lets us add and remove people from the passenger list. In addition, we will be able to see whether this flight is fully booked.

7.1 The Airplane App

To run this application, please start it using your favorite editor or by executing this command in the shell:

mvn exec:java -Dexec.mainClass="de.grobmeier.manning.log4j.basic.AirplaneBasicApp"

You’ll find several versions of the code in this book’s code repository. I want to encourage you to run the code and specifically play around with the configurations I provided as we go through the chapter.

7.1.1 Defining a structure for the app

7.1.2 The presentation layer

7.1.3 Reacting to user input

7.1.4 The service layer

7.1.5 Data storage

7.2 Logging intent with Filters and Markers

7.2.1 Why Markers and Filters?

7.2.2 Adding Markers

7.2.3 Configuring Filters on the Appender

7.2.4 Routing with Markers

7.2.5 Configuring Filters on the Logger

7.2.6 Marker Hierarchy: Parents

7.3 Reuse logging code with Messages

7.3.1 A simple custom Message

7.3.2 Advanced Messages

7.4 Logging contextual information with ThreadContext

7.6 Summary