Logback with logback.xml Configuration Example

Project structure

In the following tutorial we will show you how to configure logback with logback.xml file. We will show you how to print the logging to the console and configure logback to print the logging to a file.

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   +--logging
|                       |--LogBackExample.java
|       +--resources
|           |--logback.xml

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

    <name>LOGBACK - example xml file</name>




Example log4j2.xml file

Create a logback.xml file and put it into the resources folder.

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

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n</pattern>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n</pattern>

    <logger name="com.memorynotfound" level="TRACE"/>

    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />


We will not explain the pattern used here. To learn more read the Logback pattern layout guide.

Note: In the above configuration the default log level is DEBUG. This means that every log level greater or equal than DEBUG will be printed to log output. But we defined a log level package logger for our project which defines level TRACE which will override the root logger.

Testing log4j2 configuration

package com.memorynotfound.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogBackExample {

    private static final Logger LOG = LoggerFactory.getLogger(LogBackExample.class);

    public static void main(String... args){
        LOG.trace("This will be printed on trace");
        LOG.debug("This will be printed on debug");
        LOG.info("This will be printed on info");
        LOG.warn("This will be printed on warn");
        LOG.error("This will be printed on error");


As said in the note we override the root logger with a package logger equal to TRACE as such, all levels greater or equal than trace will be printed.

2015-01-03 15:41:07 | TRACE | [main] c.m.l.LogBackExample:11 - This will be printed on trace
2015-01-03 15:41:07 | DEBUG | [main] c.m.l.LogBackExample:12 - This will be printed on debug
2015-01-03 15:41:07 | INFO  | [main] c.m.l.LogBackExample:13 - This will be printed on info
2015-01-03 15:41:07 | WARN  | [main] c.m.l.LogBackExample:14 - This will be printed on warn
2015-01-03 15:41:07 | ERROR | [main] c.m.l.LogBackExample:15 - This will be printed on error


You may also like...