Logback Encoder Example

In this example, we are going to discuss the Encoders in the Logback. In a few words, Encoders are responsible to convert the events into byte array. Logback, as a successor of the popular Log4j project, is designed to be the next generation logging framework with many advantages over other logging frameworks. If you don’t have overall knowledge about the Logback and its components, you can look at this example about the Logback: Logback Additivity Example

1. What is the Encoder?

Encoders in the Logback transform any logging event into a byte array and write that byte array into an OutputStream. It seems like Layouts in the Logback. But layouts transform an incoming event into a String and has no control over when events get written out, layouts can not aggregate events into batches. Contrast this, the major capability of the encoders is to have total control of what and when bytes gets written to the OutputStream maintained by the owning appender.

Encoders were introduced in logback version 0.9.19. In previous versions of logback, users would nest a PatternLayout within FileAppender. Since logback 0.9.19, FileAppender and sub-classes expect an encoder and no longer take a layout. At the present time, PatternLayoutEncoder is the only widely used encoder. It wraps a PatternLayout which does most of the work. Thus, it may seem that encoders do not bring much to the table except needless complexity. However, it is hoped that with the advent of new and powerful encoders this impression will change.

1.1 PatternLayoutEncoder

Many appenders relied on the Layout instances to control the format of log output. LayoutWrappingEncoder is the class that represents the way for encoders to inter-operate with layouts. PatternLayoutEncoder extends the LayoutWrappingEncoder and is restricted to wrapping instances of PatternLayout.

You see an example configuration of the PatternLayoutEncoder below. The pattern property represents the PatternLayout which is the most commonly used layout in the Logback. The immediateFlush property ensures that logging events are immediately written to disk and will not be lost in case your application exits without properly closing appenders. Like this scenario: Assume that your application is inserting the records to the database but you don’t commit yet. If the application closes up unexpectedly, you will lose your records. Because the process has not reached the commit statement. The value of immediateFlush is set to true by default. if the outputPatternAsHeader property is set to ‘true’, Logback can insert the pattern used for the log output at the top of log files. This feature is disabled by default.

<appender name="FILE" class="ch.qos.logback.core.FileAppender"> 
    <pattern>%d %-5level [%thread] %logger{0}: %msg%n</pattern>

2. Overview

In this post, I intend to show you how to configure the Logger object programmatically without using any XML or Groovy Script. We make a file appender and establish the layout of the log messages with PatternLayoutEncoder.

Initially, we create a Maven project with Logback dependencies in our preferred IDE Eclipse. You can examine how to create a Maven Project in the Eclipse in this post: Logback File Appender Example.

3. Implementation

As already mentioned, FileAppender and sub-classes expect an encoder. Consequently, when used in conjunction with FileAppender or its subclasses a PatternLayout must be wrapped within an encoder. In the sample below, we create the PatternLayoutEncoder and set the pattern property.


package com.javacodegeeks.examples.logbackencoderexample;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;

public class ApplicationStarter {

	public static void main( final String[] args ) {

		// Create the root logger.
		final Logger rootLogger = ( Logger ) LoggerFactory.getLogger( Logger.ROOT_LOGGER_NAME );
		final LoggerContext loggerContext = rootLogger.getLoggerContext();

		// Create the PatternLayoutEncoder
		final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		encoder.setContext( loggerContext );
		encoder.setPattern( "[%thread] %-5level %logger{35} - %msg%n" );
		encoder.setOutputPatternAsHeader( true );

		// Create the FileAppender
		final FileAppender fileAppender = new FileAppender();
		fileAppender.setContext( loggerContext );
		fileAppender.setFile( "c:/logs/encoderInfo.log" );
		fileAppender.setEncoder( encoder );

		// Add the file appender to the root logger.
		rootLogger.addAppender( fileAppender );

		// write info log.
		rootLogger.info( "pattern layout encoder info" );

After the execution, here is the output of the log file:


#logback.classic pattern: [%thread] %-5level %logger{35} - %msg%n
[main] INFO  ROOT - pattern layout encoder info

Please notice that there is a header line at the top of the file that includes pattern info used for the log output. Because we set the OutputPatternAsHeader property to true.

When we wish to obtain the identical result with the XML file, we can make an XML file like below:


<?xml version="1.0" encoding="UTF-8"?>
	<appender name="AUDIT_FILE" class="ch.qos.logback.core.FileAppender">
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">			
			<pattern>[%thread] %-5level %logger{35} - %msg%n</pattern>
	<root level="INFO">
		<appender-ref ref="AUDIT_FILE" />

4. Download the Eclipse Project

This code demonstrates how to configure the PatternLayoutEncoder in the Logback framework. Download link is below.

You can download the full source code of this example here : logbackencoderexample

Ilker Konar

I am a senior software developer with experience mostly in java-related technologies with appliance in the telecommunication industry. I have been programming for more than fifteen years. I am passionate about programming. I like learning new frameworks, languages and design patterns.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
6 years ago

How can I combine the use of custom layout and patterns in logback?
In the logback.xml, I use ch.qos.logback.core.rolling.RollingFileAppender under which only either of the following 2 encoders are only getting used. So, I am unable to use the pattern if I go via the custom layout class I have written

{“@timestamp”: “%d{yyyy-MM-dd HH:mm:ss.SSS}”, “priority”: “%p”, “application”: “payment”,
“class”: “%C”, “file”: “%F:%L”, “payload”: %m }%n

Back to top button