Log4j2 Tutorial 5 – XML Configuration File to Log Into File and Console Using Log4j2 Together

Introduction

We have already learnt the basics but important concepts of Log4j2 in series of tutorials in Log4j2 Tutorials. Now we know to create an XML configuration file to print logs in to a File and on to the console.

But sometimes it is good to print logs in to console and file as well. So now we will configure an XML document that will be capable to print logs into a file and on a console as well.

If you are thinking it will be complex then you are not correct. It will be just a combination of above mentioned two posts.

Did you know that I have started a YouTube channel as well and I need your support to make it successful. Please do watch content then comment, like, share, and obviously subscribe.

Required Dependencies

Always use the latest version of dependencies. I am using the below version of Log4j2 which is the latest at the time of writing this post.



    org.apache.logging.log4j
    log4j-core
    2.14.1

XML configuration file with File and Console Appender

We know that to print in to console we need to use console appender and File appender to print logs in to a file. We can use both into same configuration file as below:-



	
		
			
				%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
				
			
		
		
			
		
	
	
		
			
			
		
	

Example Program

package appCode;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ModuleA {
	
	// Creating a logger
	private static Logger logger = LogManager.getLogger();

	// Log messages
	public static void main(String[] args) {
		
		logger.debug("It is a debug logger.");
		logger.error("It is an error logger.");
		logger.fatal("It is a fatal logger.");
		logger.info("It is a info logger.");
		logger.trace("It is a trace logger.");
		logger.warn("It is a warn logger.");
		
	}
}

When we run above program then we can see logs printed in console and file both as below:-

Console Output

2021-04-13 07:41:54,448 [main] DEBUG: It is a debug logger.
2021-04-13 07:41:54,451 [main] ERROR: It is an error logger.
2021-04-13 07:41:54,453 [main] FATAL: It is a fatal logger.
2021-04-13 07:41:54,454 [main] INFO : It is a info logger.
2021-04-13 07:41:54,454 [main] TRACE: It is a trace logger.
2021-04-13 07:41:54,455 [main] WARN : It is a warn logger.

File Output

GitHub Link to clone project

Log4j2 Example Codes

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Leave a Reply

Your email address will not be published. Required fields are marked *