HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Log4j2 Multiple appenders example

By Lokesh Gupta | Filed Under: Log4j2

Given log4j2.xml is reference to configure multiple appenders such as console appender and file appenders. This also configure the dynamic log root path.

Log4j multiple appenders configuration

Sample log4j configuration is given blow. It does following things:

  1. Uses dynamic log root path where log files will be created. Pass environment variable as -DAPP_LOG_ROOT=c:/temp to configure it.
  2. Demo the usage of property constants defined in config file e.g. LOG_PATTERN in below file.
  3. It uses LevelRangeFilter to log different log level statements in different files i.e. debug logs in one file and error logs in separate file.
  4. All logs will be shown in console also.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">

    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
    </Properties>

    <Appenders>

        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
        
		<RollingFile name="debugLog" fileName="${sys:APP_LOG_ROOT}/application-debug.log" 
			filePattern="${sys:APP_LOG_ROOT}/application-debug-%d{yyyy-MM-dd}-%i.log">
			<LevelRangeFilter minLevel="DEBUG" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="infoLog" fileName="${sys:APP_LOG_ROOT}/application-info.log" 
			filePattern="${sys:APP_LOG_ROOT}/application-info-%d{yyyy-MM-dd}-%i.log" >
			<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="errorLog" fileName="${sys:APP_LOG_ROOT}/application-error.log" 
			filePattern="${sys:APP_LOG_ROOT}/application-error-%d{yyyy-MM-dd}-%i.log" >
			<LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="springLog" fileName="${sys:APP_LOG_ROOT}/spring.log" 
			filePattern="${sys:APP_LOG_ROOT}/spring-%d{yyyy-MM-dd}-%i.log" >
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="1"/>
		</RollingFile>
		
		<RollingFile name="aopLog" fileName="${sys:APP_LOG_ROOT}/application-aop.log" 
			filePattern="${sys:APP_LOG_ROOT}/application-aop-%d{yyyy-MM-dd}-%i.log" >
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="1"/>
		</RollingFile>
		
    </Appenders>

    <Loggers>
    
    	<Logger name="com.howtodoinjava.app.aop" additivity="false">
    		<AppenderRef ref="aopLog" />
            <AppenderRef ref="Console" />
        </Logger>
        
        <Logger name="com.howtodoinjava.app" additivity="false">
	        <AppenderRef ref="debugLog" />
	        <AppenderRef ref="infoLog"  />
            <AppenderRef ref="errorLog" />
            <AppenderRef ref="Console"  />
        </Logger>
        
        <Logger name="org.springframework" additivity="false">
            <AppenderRef ref="springLog" />
            <AppenderRef ref="Console"/>
        </Logger>
                
        <Root level="all">
            <AppenderRef ref="Console"/>
        </Root>

    </Loggers>

</Configuration>

Drop me your questions in comments section.

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

3
Leave a Reply

This comment form is under antispam protection
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Nishant

Is there a way in Log4j2 to allow logging specific content to a separate file (audit log)?

For example, if value x changes, log to file1 that value of x has changed. This file1 is intended to capture audit logs if value of x changes. If this is supported, I would like to scale this to actual business logic for an audit log.

Vote Up0Vote Down  Reply
5 months ago
Sopan Shirhdonkar

Hi, I am using log4j2 with xml config.

I want to write logs depending upon the class name, i.e. for each testng class a separate log file.

While running multiple classes from testng, it just writes into the first class name.
I have written a static method which returns me the logger in utils class.

    public static Logger getDynamicLogger(Class className) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        System.setProperty("logFilename", className.getSimpleName() + "-" + formatter.format(date));
   
        SimpleDateFormat pkgFormatter = new SimpleDateFormat("dd-MMMM-yy");
        System.setProperty("logFileFolder",pkgFormatter.format(date));
      
        ThreadContext.put("className",className.getName());
        Reporter.log(className.getName(),true);
        return LogManager.getLogger(className);
    }

Any idea for this

Vote Up0Vote Down  Reply
1 year ago
Kaushik Vankayala

Hello,

I am looking for some insight or help regarding the log4j2 configuration or code to write the custom logs to a remote redhat linux and a windows machine. Could you please provide me some help?

I have seen some log4j links, forums suggesting to use the log4j at sender side and also receiver side. But my application uses log4j2, so could you please care to help?

Regards

Kaushik

Vote Up0Vote Down  Reply
1 year ago

Search Tutorials

Log4j2 Tutorial

  • Log4j2 – Introduction
  • Log4j2 – JSON Config
  • Log4j2 – Properties Config
  • Log4j2 – XML Config
  • Log4j2 – RollingFileAppender
  • Log4j2 – Multiple appenders
  • Log4j2 – LevelRangeFilter
  • Log4j2 – HTMLLayout
  • Log4j2 – Fish Tagging
  • Log4j2 – Conversion Patterns
  • Log4j2 – JUnit

Log4j Tutorial

  • Log4j – Introduction
  • Log4j – Properties Config
  • Log4j – XML Config
  • Log4j – Maven Config
  • Log4j – Logging Levels
  • Log4j – ConsoleAppender
  • Log4j – RollingFileAppender
  • Log4j – SocketAppender
  • Log4j – JDBCAppender
  • Log4j – XMLLayout
  • Log4j – HTMLLayout
  • Log4j – Runtime Reload
  • Log4j vs. SLF4j
  • Log4j – RESTEasy + Tomcat 7

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz