Pattern Layout

Pattern Layout

It able to prepare logging messages w.r.t the provided pattern. To represent Pattern Layout, Log4j has provided a predefined class in the form of “org.apache.log4j.PatternLayout”.

To define pattern for the logging messages, we must use “ConversionPattern” property from PatternLayout class.

log4j.properties

log4j.rootLogger = ALL, FILE
log4j.appender.FILE = org.apache.log4j.FileAppender
log4j.appender.FILE.file = /home/ashok/loggers/ashok.log
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-c %p : Hey %m%n
package com.ashok.log4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class TestLog4J {
	private static final Logger LOG = LoggerFactory.getLogger(TestLog4J.class);
	public static void main(String[] args) {
		LOG.trace("This is trace message"); 
		LOG.debug("This is debug message");
		LOG.info("This is info message"); 
		LOG.warn("This is warn message"); 
		LOG.error("This is error message"); 
	}
}

Output

02/12/2019 16:15:885 com.ashok.log4j.Log4jTest TRACE : Hey this is trace message
02/12/2019 16:15:886 com.ashok.log4j.Log4jTest DEBUG : Hey this is debug message
02/12/2019 16:15:886 com.ashok.log4j.Log4jTest INFO : Hey this is info message
02/12/2019 16:15:886 com.ashok.log4j.Log4jTest WARN : Hey this is warn message
02/12/2019 16:15:886 com.ashok.log4j.Log4jTest ERROR : Hey this is error message

Note

We will use these patterns in general in PatternLayout for ConversionPattern property.

%d ----> Date
%c ----> Class to which we are providing Logging
%P ----> Logging Level
%L ----> Line NUmber
%m ----> Logging Message
%n ----> New Line Character
Pattern Layout
Scroll to top