As you already know, developers have a lot of logging tools at their disposal. In this topic, we are going to learn more about a popular logging library named Logback. It was created as a successor to the Log4j 1.x library and is based on similar concepts. Logback is fast in both synchronous and asynchronous logging and offers many useful features, which makes it a good choice for a project of any scale.
The most important difference between using a Logback logger and simply printing a message to System.out is that each logger belongs to a logger context. The logger context allows enabling or disabling certain log messages and is responsible for creating logger instances and arranging them into a hierarchy. Let's take a closer look at all these features.
Adding Logback to a project
To get started with Logback, you need to add the logback-classic dependency to your project. In this topic, we use Logback 1.6.8, which requires Java 11 or higher.
If you are using Maven, open the pom.xml file and add these lines:
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.6.8</version>
</dependency>
</dependencies>If you use Gradle with the Kotlin DSL, add the following line to your build.gradle.kts file:
dependencies {
implementation("ch.qos.logback:logback-classic:1.6.8")
}If your project uses the Groovy DSL (the build.gradle file), the line looks like this:
dependencies {
implementation 'ch.qos.logback:logback-classic:1.6.8'
}This library transitively pulls in two other dependencies: slf4j-api and logback-core.
SLF4J (Simple Logging Facade for Java) is a facade, or abstraction, for various logging libraries, including Logback. It provides a simple logging API, and Logback implements it natively. This means you can call the SLF4J logger with Logback as its underlying implementation without any overhead.
The logback-core library lays the foundation for Logback and provides a few ready-made appenders. An appender is a component that writes log events to some destination:
ConsoleAppenderwrites log events toSystem.outorSystem.err;FileAppenderwrites log events to a file;RollingFileAppenderwrites log events to a file and can switch to another file when a certain condition is met, for example, when the file gets too large or a new day starts.
The logback-classic library adds appenders that send log events to external systems. For example, SMTPAppender collects log events in a buffer and sends its contents by email when an event specified by the user occurs, for example, an error.
Appenders that write log events to a database, such as DBAppender, are not part of logback-classic. They are provided by the separate logback-db project, so you need to add its logback-classic-db dependency if you want to store logs in database tables.
Basic logging
Let's create a class Example in the com.example package and declare two Logger objects:
package com.example
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Example {
private val LOG_1: Logger = LoggerFactory.getLogger(Example::class.java)
private val LOG_2: Logger = LoggerFactory.getLogger("com.example.Example")
init {
LOG_1.info("Information from LOG_1")
LOG_2.warn("Warning from LOG_2")
LOG_1.info("Are the loggers the same? {}", LOG_1 === LOG_2)
}
}
fun main() {
Example()
}As you can see, we don't refer to any Logback class directly. Instead, we call SLF4J classes and interfaces, and SLF4J, in turn, delegates logging operations to Logback.
To create a logger, we use the getLogger method of LoggerFactory, which accepts either a Class or a String as an argument. In both cases, the argument is used as the name of the logger: for a class, it is the fully qualified class name. If a logger with the same name already exists, the method returns it, and if there is no logger with this name, a new one is created. That's why LOG_1 and LOG_2 in our example are the same object.
A Logger object has the methods trace, debug, info, warn, and error for outputting a message of the corresponding level.
If we run the code above, we'll get this output:
By default, each log line has the following elements: timestamp, thread name, level, logger name, and message. We will learn how to change this default format later in this topic.
Message parameterization
Logback lets you add the values of objects and variables to a log message. To do this, put the {} placeholder in the message and pass the value as the next argument. This helps you see, for example, what data your program was working with when something went wrong.
Here is an example:
package com.example
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Example {
private val LOG: Logger = LoggerFactory.getLogger(Example::class.java)
init {
val result = "Any operation"
LOG.info("To track the value of a variable. The result is {}", result)
}
}
fun main() {
Example()
}The value of the variable is inserted in place of the placeholder:
We can also use parameterization to log an error along with relevant information:
package com.example
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Example {
private val LOG: Logger = LoggerFactory.getLogger(Example::class.java)
init {
val number = 1
val divisor = 0
try {
val result = number / divisor
} catch (e: ArithmeticException) {
LOG.error("Something went wrong with divisor {}", divisor, e)
}
}
}
fun main() {
Example()
}Here, we pass the exception object as the last argument of the error method. Logback recognizes it as an exception and prints its stack trace after the message. You don't need a placeholder for the exception, but it must be the last argument passed to the logging method.
You can read more about parameterized logging in the Logback documentation.
Fine-tuning the logger configuration
Logback is usually configured with an XML file. To configure our loggers, create a file named logback.xml and place it in the src/main/resources folder of your project. This is what a basic configuration file looks like:
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>All logger settings are placed between the <configuration> tags.
Next comes the <appender> tag. As you already know, an appender defines where the logs will be written. The name attribute specifies the name of the appender, and the class attribute specifies the class that implements it. Here, we use ConsoleAppender, which outputs logs to the console.
The <encoder> tag specifies the format of the log messages. A log message in the format we defined above looks like this:
01:15:54 INFO com.example.Example - Customized message formatThe <root> tag configures the predefined root logger. Here, we set its level with level="info" and attached our appender to it with <appender-ref ref="console" />.
Another standard appender is FileAppender. As you can guess from its name, this appender writes logs to a file:
<configuration>
<appender name="file" class="ch.qos.logback.core.FileAppender">
<file>${user.dir}/logs/example.log</file>
<encoder>
<pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="file" />
</root>
</configuration>This is the simplest setup for FileAppender. The new element here is the <file> tag, which specifies the file to write logs to. Don't worry if this file doesn't exist: it will be created when the application starts. The ${user.dir} variable refers to the working directory of the application, which is usually the project folder when you run the program from the IDE, so the log file will appear in its logs folder.
Logger levels
Logback allows you to set the logging level for individual packages and classes. To do this, add a <logger> tag to the logback.xml file and specify two attributes: name and level. In the name attribute, specify the fully qualified name of a package or class in your project, and in the level attribute, specify the logging level you need.
Let's look at an example. Here are two classes in the com.example package:
package com.example
import org.slf4j.LoggerFactory
class Example {
private val LOG = LoggerFactory.getLogger(Example::class.java)
fun log() {
LOG.warn("WARN level message")
LOG.info("INFO level message")
}
}
class LoggerLevelClass {
private val LOG = LoggerFactory.getLogger(LoggerLevelClass::class.java)
fun log() {
LOG.debug("DEBUG level message")
LOG.info("INFO level message")
}
}
fun main() {
Example().log()
LoggerLevelClass().log()
}For these classes, we set up the following logger levels:
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example" level="warn"/>
<logger name="com.example.LoggerLevelClass" level="info"/>
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>A logger outputs only the messages whose level is higher than or equal to the level of the logger. The levels are ordered as follows: TRACE < DEBUG < INFO < WARN < ERROR.
Loggers in Logback form a hierarchy based on their names. For example, a logger named com.logback.first is the parent of a logger named com.logback.first.second, which, in turn, is the parent of the com.logback.first.second.third logger. At the top of every hierarchy is the root logger. If a logger has no level of its own, it inherits the level of its nearest ancestor. This means that you can set logger levels for entire packages.
In our example, the com.example.Example logger has no level of its own, so it inherits the warn level from the com.example logger. The com.example.LoggerLevelClass logger has its own info level. If we run the code, we will see only two messages, one from each class:
12:30:45.123 [main] WARN com.example.Example - WARN level message
12:30:45.125 [main] INFO com.example.LoggerLevelClass - INFO level messageThe INFO message of the Example class is filtered out because its level is lower than WARN, and the DEBUG message of LoggerLevelClass is filtered out because its level is lower than INFO.
Conclusion
In this topic, you've found out what Logback is and what features it provides to developers. With Logback, you can see what actions your program performed. You can also configure loggers to suit your needs, set logging levels for packages and classes separately, and easily track errors and their causes.