chapter six

6 Let’s get started with Apache Log4j

 

This chapter covers

  • How to write log statements with Log4j
  • Configuring Log4j for console and file output
  • Formatting log messages with layouts
  • Filtering log messages based on levels and logger names

Apache Log4j is a robust logging framework provided by the Apache Software Foundation (ASF). Log4j, like most ASF projects, is fully open source. You can find it here:

Installation is easy: either download it from the website or add it to your project using Maven or Gradle. I recommend using Maven, as it makes updating Log4j easier in the future.

You’ll need two packages. First, there is log4j-api. This artifact contains all the necessary Log4j interfaces. Second, you’ll need log4j-core, which includes the actual implementation of those interfaces. The separation is intentional, even if it feels a bit inconvenient at first. We’ll cover the benefits of this approach when we talk about "Logging Facades.

To include Log4j using Maven, it’s as simple as adding the following lines to your pom.xml.

6.1 Basic usage

6.1.1 Creating a logger instance

6.1.2 Writing log statements

6.1.3 Using Log4j log levels

6.1.4 Using parameter substitution in Log4j

6.2 Basic configuration of Log4j

6.2.1 How Log4j loads a configuration file

6.2.2 The structure of a Log4j configuration file

6.2.3 Appenders

6.2.4 Logger

6.3 Layouts

6.3.1 Date and time patterns

6.3.2 Message parts

6.3.3 Shortening logger names

6.4 A complete configuration example

6.5 Summary