Using Logback

In this lesson, you will learn about using Logback.

Logback #

Logback is intended as a successor to the popular log4j project that is used for logging to console and file. The main advantage of using logback over log4j is that its internals has been re-written to perform about ten times faster and has a smaller memory footprint as well.

Here, we can find a reason to use logback over log4j.

Dependency to add #

Maven #

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

Gradle #


compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'

A sample logback.xml for logging to console and writing to file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<appender name="CONSOLE"
		class="ch.qos.logback.core.ConsoleAppender">
		<append>false</append>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>info</level>
		</filter>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg - \(%file:%line\) %n</pattern>
		</encoder>
		<immediateFlush>false</immediateFlush>
	</appender>
	<appender name="WARN" class="ch.qos.logback.core.FileAppender">
		<file>logs/warn.log</file>
		<append>false</append>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>warn</level>
		</filter>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg - \(%file:%line\) %n</pattern>
		</encoder>
	</appender>
	<appender name="DEBUG"
		class="ch.qos.logback.core.FileAppender">
		<file>logs/debug.log</file>
		<append>false</append>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>debug</level>
		</filter>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg - \(%file:%line\) %n</pattern>
		</encoder>
	</appender>
	<appender name="INFO" class="ch.qos.logback.core.FileAppender">
		<file>logs/info.log</file>
		<append>false</append>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>info</level>
		</filter>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg - \(%file:%line\) %n</pattern>
		</encoder>
	</appender>
	<appender name="ERROR"
		class="ch.qos.logback.core.FileAppender">
		<file>logs/error.log</file>
		<append>false</append>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>error</level>
		</filter>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg - \(%file:%line\) %n</pattern>
		</encoder>
	</appender>

	<root level="DEBUG">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="INFO" />
		<appender-ref ref="DEBUG" />
		<appender-ref ref="WARN" />
		<appender-ref ref="ERROR" />
	</root>

</configuration>

Get hands-on with 1400+ tech skills courses.