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.