Logback: A Better Log4j for Enterprise Application Logging

Log & Roll with Logback

Thilina Ashen Gamage
5 min readJul 31, 2017
Image Source: Lynda.com

From STDOUT to Logging

Remember the days we debug Java programs with System.out.println(error) inside an error handling block? Recording such event occurrences and run-time information to the console or a file is very important in order to monitor and analyse the programs we write. This concept of recording the occurrences of run-time events of a software is called logging. Although you can have your own implementations to record these information programmatically to the console/file, it will consume time and resources from your main program. Also it will be a bottleneck when the number of records increases.

This is where the logging tools and frameworks come into the scenario. Without using our own implementations, we can use the logging frameworks which are lighter, faster, and easier in comparison to our implementations.

Characteristics of a good Logging framework

  1. Be fast, efficient, and optimum — In a practical environment, there can be situations where the program generates hundreds or thousands of logging messages within a second and the logger should be able to handle them all balancing logging speed and buffering amounts at an optimum level.
  2. Consume less memory
  3. Easily configurable
  4. Support standard logging levels (ERROR, WARN, INFO, DEBUG, TRACE)
  5. Support different destination formats (console, text file, HTML doc, database, SMTP server, or JMS queue destination)
  6. Support flexible file rolling

Logback is a logging framework which satisfies all above criteria and can be recognized as the best logging framework available for Java programs. Now we will see the features of Logback by implementing a sample Maven project in IntelliJ IDEA IDE.

Step 1: Create a Maven project

Create a new Maven project from scratch and add the following dependencies and plugins to the pom.xml file. Choose ‘Enable Auto-Import’ Maven projects prompt at the beginning (to manually enable this, go to File > Settings > search and select ‘Maven’ > choose ‘Importing’ > enable ‘Import Maven projects automatically’).

For our sample project, we need only the logback-classic module. But note that Logback offers the following 3 modules for different purposes.

  1. logback-core — lays the foundation for logback-classic and logback-access. To perform logging, you need the more specialized logback-classic or logback-access.
  2. logback-classic — corresponds to a significantly improved version of log4j. It natively implements the SLF4J API so that you can readily switch back and forth between logback and other logging systems such as log4j or java.util.logging (JUL) introduced in JDK 1.4.
  3. logback-access — integrates with Servlet containers (Jetty, Tomcat…) to provide HTTP-access log functionality. Read more about this module here.

Step 2: Project Directory Structure

The directory structure of the sample project looks like the following.

├───.idea
├───src
│ ├───main
│ │ ├───java
│ │ │ └───com
│ │ │ └───ashenlive
│ │ │ ├───HelloLogBack.java
│ │ │ └───StartupSizeTimeBasedTriggeringPolicy.java
│ │ └───resources
│ │ │ └───logback.xml
│ └───test
├───target
└───Logs

Step 3: Write a Simple Program

Logback supports 5 major logging levels: TRACE, DEBUG, INFO, WARN and ERROR, with the following level hierarchy.

TRACE < DEBUG < INFO < WARN < ERROR

For an example, ERROR is the highest logging level. If you set the logging level of your program to ERROR, you will only see the logging messages with ERROR type. If you set the logging level as TRACE, you will see the logging messages belonging to all 5 logging level types. Here is a table explaining these options.

For now, let’s write a simple program with various log levels to see how the logging works. Later, we can change our project’s log level in logback.xml file and see what messages are logged or ignored during the run-time.

You can read more about Logback’s architecture from its official docs.

Step 4: Configure to roll over file at startup

This feature can be implemented by creating a trigger at startup using the following class and adding a configuration in logback.xml file.

Step 5: Create logback.xml configuration file

Logback supports configurations in XML and Groovy formats. For this sample project, let’s use an XML configuration file. Make sure you place this logback.xml file inside your ~/src/main/resources directory.

With above configuration, you will get the following features;

  1. Sending log messages to console
  2. Sending log messages to file
  3. Roll over file at program startup
  4. Roll over file daily
  5. Roll over file when the file size exceeds a max size
  6. Clean old files by checking history
  7. Always write to a known file and when rolling happens, it copies data to a new file and again starts writing to the known file

Now you can run your main class and see how the logging process happens. As an optional step, let’s see how we can change the log file name dynamically during the run-time of our program.

Step 6: Programmatically set log file names / parameter values

To set the log file name programmatically, define it as a system property in logback.xml and set its value inside your program with MDC;

If you carefully check this, you can understand that with MDC.put() method, we are sending parameters to our configuration file dynamically. When we need to change values in our configuration dynamically, what we have to do is, mention it as $(parameterName) in the logback.xml and send values using MDC.put("parameterName", “parameterValue") method.

We have used the siftingappender to achieve this purpose. Read more about its implementation from Logback’s official docs.

Step 7: Programmatically define System properties

Without defining system properties in a file, we can set them during the run-time too. Just add the following line to your code with the system property’s name and value.

System.setProperty("propertyName", "propertyValue");

This method can be used to change values in our logback.xml configuration too. You can refer to them with$(propertyName) in your XML file.

References:

  1. https://springframework.guru/logback-enterprise-logging-framework-2/
  2. https://springframework.guru/logback-configuration-using-xml/
  3. https://www.mkyong.com/logging/logback-xml-example/
  4. https://logback.qos.ch/manual/architecture.html

--

--

Thilina Ashen Gamage

Advocate of Cloud, Microservices, & Clean Code | 1.5M+ Reach | For more exciting content, stay in touch: https://medium.com/@ThilinaAshenGamage