What is Logback.xml Logging Framework? ConsoleAppender, FileAppender and RollingFileAppender Tutorial

Are you aware of Logback Logging Framework? Well, most of the people mainly use log4j and slf4j into their project. Since last 6 months I’ve been using Logback.xml logging framework and I would say I saw quite a few performance improvements in my production application.

In this tutorial we will go over practical example of Logback logging framework.

What is logback.qos.ch?

Logback is kind of a new version of Log4j. It was developed from where log4j development stopped.

Logback Logging Framework Details

On Crunchify, we have published multiple tutorials on Log4j if you are interested:

Here we will go over all detailed steps on how to setup Logback Logging Framework for your Enterprise Java Project. We are going to create below new files.

  1. Under resources folder logback.xml file
  2. Java Class CrunchifyLogbackLogging.java

Let’s get started

Step-1 Create logback.xml file

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

        <appender name="CRUNCHIFYOUT" class="ch.qos.logback.core.ConsoleAppender">
                <layout class="ch.qos.logback.classic.PatternLayout">
                        <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}
                                %X{sourceThread} - %msg%n</Pattern>
                </layout>
        </appender>

        <appender name="CRUNCHIFYFILE" class="ch.qos.logback.core.FileAppender">
                <file>/Users/ashah/Documents/crunchify.log</file>

                <encoder>
                        <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
                </encoder>
        </appender>

        <appender name="CRUNCHIFYROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <file>/Users/ashah/Documents/crunchify-rolling.log</file>

                <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                        <Pattern>
                                %d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n
                        </Pattern>
                </encoder>

                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                        <!-- We are rolling over daily -->
                        <fileNamePattern>crunchify.log.timeroll.%d{yyyy-MM-dd}.log</fileNamePattern>

                        <!-- keep 10 days' worth of history capped at 1GB total size -->
                        <maxHistory>10</maxHistory>
                        <totalSizeCap>1GB</totalSizeCap>

                </rollingPolicy>
        </appender>

        <!-- default is DEBUG -->
        <root level="DEBUG">
                <appender-ref ref="CRUNCHIFYOUT" />
                <appender-ref ref="CRUNCHIFYFILE" />
                <appender-ref ref="CRUNCHIFYROLLING" />
        </root>

</configuration>

Let’s understand logback.xml file first.

  • At the bottom of a file you see we have 3 appender references appender-ref under root element.
  • We are using log level as DEBUG. That means print everything with level DEBUG and above.

CRUNCHIFYOUT appender is of class ch.qos.logback.core.ConsoleAppender. Which means, all logging data will be printed to Eclipse Console.

CRUNCHIFYFILE is of type ch.qos.logback.core.FileAppender. That means, all logging data will also be printed to localfile. In our case it’s /Users/ashah/Documents/crunchify.log.

CRUNCHIFYROLLING is of type ch.qos.logback.core.rolling.RollingFileAppender. As you see in rollingPolicy, we are rolling file every day and keeping maximum 10 files. Also, there is total filesize Capacity limit which is 1 GB in our example. New file will be created at location /Users/ashah/Documents/crunchify-rolling.log.

Step-2 Write Java program to test it out.

package crunchify.com.tutorial;

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

/**
 * @author Crunchify.com 
 * Program: Very simple Logback.xml test class with ConsoleAppender, FileAppender and RollingFileAppender 
 * Version: 1.0.0
 * 
 */

public class CrunchifyLogbackLogging {

        private final Logger crunchifyLogging = LoggerFactory.getLogger(CrunchifyLogbackLogging.class);

        public static void main(String[] args) {

                CrunchifyLogbackLogging crunchifyLogger = new CrunchifyLogbackLogging();
                
                crunchifyLogger.getStartedwithLogBackTesting();

        }

        private void getStartedwithLogBackTesting() {

                for (int i = 1; i <= 10; i++) {
                        crunchifyLogging.debug("......This is test by Crunchify on Logback DEBUG...... ");
                        crunchifyLogging.info("......This is test by Crunchify on Logback INFO......");
                        crunchifyLogging.error("......This is test by Crunchify on Logback ERROR......");
                        crunchifyLogging.warn("......This is test by Crunchify on Logback WARN......");
                }

        }
}

This is a very simple Java Test class, in which we are using error, info, debug and warn all 4 logging level. We are looping through 10 times.

Step-3

Once you run above program, logback framework will create two new files as mentioned above.

Checkout your Eclipse Console. You will see below logs:

15:36:12,978 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
15:36:12,978 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
15:36:12,978 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/Users/ashah/Documents/site/Bitbucket/crunchifytutorials/target/classes/logback.xml]
15:36:13,077 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
15:36:13,077 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
15:36:13,087 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [CRUNCHIFYOUT]
15:36:13,143 |-WARN in ch.qos.logback.core.ConsoleAppender[CRUNCHIFYOUT] - This appender no longer admits a layout as a sub-component, set an encoder instead.
15:36:13,143 |-WARN in ch.qos.logback.core.ConsoleAppender[CRUNCHIFYOUT] - To ensure compatibility, wrapping your layout in LayoutWrappingEncoder.
15:36:13,143 |-WARN in ch.qos.logback.core.ConsoleAppender[CRUNCHIFYOUT] - See also http://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details
15:36:13,144 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.FileAppender]
15:36:13,147 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [CRUNCHIFYFILE]
15:36:13,147 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
15:36:13,148 |-INFO in ch.qos.logback.core.FileAppender[CRUNCHIFYFILE] - File property is set to [/Users/ashah/Documents/crunchify.log]
15:36:13,151 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
15:36:13,152 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [CRUNCHIFYROLLING]
15:36:13,159 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@2096171631 - setting totalSizeCap to 1 GB
15:36:13,161 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@2096171631 - No compression will be used
15:36:13,163 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@2096171631 - Will use the pattern crunchify.log.timeroll.%d{yyyy-MM-dd}.log for the active file
15:36:13,166 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'crunchify.log.timeroll.%d{yyyy-MM-dd}.log'.
15:36:13,166 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
15:36:13,171 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Thu Sep 07 11:42:27 CDT 2017
15:36:13,173 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[CRUNCHIFYROLLING] - Active log file name: /Users/ashah/Documents/crunchify-rolling.log
15:36:13,173 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[CRUNCHIFYROLLING] - File property is set to [/Users/ashah/Documents/crunchify-rolling.log]
15:36:13,173 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
15:36:13,174 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [CRUNCHIFYOUT] to Logger[ROOT]
15:36:13,174 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [CRUNCHIFYFILE] to Logger[ROOT]
15:36:13,174 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [CRUNCHIFYROLLING] to Logger[ROOT]
15:36:13,174 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
15:36:13,175 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@7e0babb1 - Registering current configuration as safe fallback point

15:36:13.181 [main] DEBUG c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback DEBUG...... 
15:36:13.186 [main] INFO  c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback INFO......
15:36:13.187 [main] ERROR c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback ERROR......
15:36:13.187 [main] WARN  c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback WARN......
15:36:13.188 [main] DEBUG c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback DEBUG...... 
15:36:13.188 [main] INFO  c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback INFO......
15:36:13.188 [main] ERROR c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback ERROR......
15:36:13.188 [main] WARN  c.c.tutorial.CrunchifyLogbackLogging
                                 - ......This is test by Crunchify on Logback WARN......

In addition to that you could also check local file logs and as you see, logback.xml file has created all new files and started printing logs inside it.

Logback.xml file creates new file appender files

Enjoy, you have setup logback.xml and all 3 appenders correctly: ConsoleAppender, FileAppender, RollingFileAppender.

Bonus point:

Do you want to setup RollingFileAppender with FixedWindowRollingPolicy? Well use below appender and put it into logback.xml file and you are should be all good 🙂

<appender name="CRUNCHIFYROLLINGFIXEDWINDOW" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/Users/ashah/Documents/crunchify-rolling-fixwindows.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <FileNamePattern>crunchify.log.fixedsize.{yyyy-MM-dd}%i.log</FileNamePattern>
        <MinIndex>1</MinIndex>
        <MaxIndex>15</MaxIndex>
    </rollingPolicy>
    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>20MB</MaxFileSize>
    </triggeringPolicy>
</appender>

Also, just add appender-ref under root element.

<appender-ref ref="CRUNCHIFYROLLINGFIXEDWINDOW" />

The post What is Logback.xml Logging Framework? ConsoleAppender, FileAppender and RollingFileAppender Example appeared first on Crunchify.