Logback XMLLayout

Logback XMLLayout outputs events into XML format that is log4j.dtd compliant (instead of an W3C XML Schema). The generated XML logs can be viewed using the opensource Log viewer tools such as Apache Chainsaw and vigilog.

1. XMLLayout Sample Configuration

The given configuration logs into the rolling files using the XML layout. It logs into c:/temp/logs/applicationLogs.xml file and rolls-over daily.

XMLLayout accepts two optional parameters:

  • locationInfo: when set to true, log location information is output into tyhe log entries. By default, it is set to false.
  • properties: when set to true, MDC information is output into tyhe log entries. By default, it is set to false.
<configuration>
	<property name="LOG_ROOT" value="c:/temp/logs" />
	<property name="XML_LOG_FILE" value="applicationLogs" />
	
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
		</encoder>
	</appender>
	
	<appender name="XML" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${LOG_ROOT}/${XML_LOG_FILE}.xml</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<!-- daily rollover -->
			<fileNamePattern>${LOG_ROOT}/${XML_LOG_FILE}-%d{yyyy-MM-dd}.%i.xml.gz</fileNamePattern>
			<!-- each archived file's size will be max 10MB -->
			<maxFileSize>10MB</maxFileSize>    
			<!-- 30 days to keep -->
			<maxHistory>30</maxHistory>
			<!-- total size of all archive files, if total size > 100GB, it will delete old archived file -->
			 <totalSizeCap>100GB</totalSizeCap>
		</rollingPolicy>
		<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
			<charset>UTF-8</charset>
			<layout class="ch.qos.logback.classic.log4j.XMLLayout">
				<locationInfo>true</locationInfo>
				<properties>true</properties>
			</layout>         
		</encoder>
	</appender> 
	
	<logger name="com.howtodoinjava.app" level="DEBUG" additivity="false">
        <appender-ref ref="XML"/>
  </logger>

	<root level="INFO">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="XML" />
	</root>
</configuration>

2. Dependencies

Logback requires three modules in the application runtime i.e. logback-corelogback-classic and slf4j-api.

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
	<version>1.2.10</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.10</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.32</version>
</dependency>

Note that logback-classic will transitively pull in the logback-core and slf4j-api, so adding logback-classic dependency is enough.

3. Demo

Let’s quickly write a few log statements, and see the output.

public class Main {
	public static void main(final String[] args) {
		Logger logger = LoggerFactory.getLogger(Main.class);

		logger.debug("Debug Message Logged !!!");
		logger.info("Info Message Logged !!!");
		logger.error("Error Message Logged !!!", new NullPointerException("Something is NULL"));

		Article a = Article.builder(1L).title("Test Article").tag("Data").build();
		logger.info("Article fecthed for id : {} is : {}", 1, a);
	}
}

Open the Log output file and verify the logs.

<log4j:event logger="com.howtodoinjava.demo.slf4j.Main"
             timestamp="1641553034276" level="INFO" thread="main">
  <log4j:message>Info Message Logged !!!</log4j:message>
  <log4j:locationInfo class="com.howtodoinjava.demo.slf4j.Main"
                      method="main" file="Main.java" line="16"/>
  <log4j:properties>
    <log4j:data name='MDC_KEY' value='VALUE' />
  </log4j:properties>
</log4j:event>

<log4j:event logger="com.howtodoinjava.demo.slf4j.Main"
             timestamp="1641553034282" level="ERROR" thread="main">
  <log4j:message>Error Message Logged !!!</log4j:message>
  <log4j:throwable><![CDATA[	at com.howtodoinjava.demo.slf4j.Main.main(Main.java:17)
]]></log4j:throwable>
  <log4j:locationInfo class="com.howtodoinjava.demo.slf4j.Main"
                      method="main" file="Main.java" line="17"/>
  <log4j:properties>
    <log4j:data name='MDC_KEY' value='VALUE' />
  </log4j:properties>
</log4j:event>

<log4j:event logger="com.howtodoinjava.demo.slf4j.Main"
             timestamp="1641553034288" level="INFO" thread="main">
  <log4j:message>Article fecthed for id : 1 is : Article(id=1, title=Test Article, tags=[Data])</log4j:message>
  <log4j:locationInfo class="com.howtodoinjava.demo.slf4j.Main"
                      method="main" file="Main.java" line="20"/>
  <log4j:properties>
    <log4j:data name='MDC_KEY' value='VALUE' />
  </log4j:properties>
</log4j:event>

4. Conclusion

In this logback XML Layout tutorial, we learned to create logs in XML files with rolling capabilities. These XML formatted logs can be viewed using the free log viewing tools.

Note that if logs are being generated in very high amounts then we should be logging plain string logs and use specialized tools (such as Splunk) for log processing.

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode