How To Configure Log4j In Java Project Examples

You have learned that there are a lot of objects inside log4j, such as Logger object, Layout object and Appender object. But before your can use them in your java project, you should configure them commonly through a configuration file. This article will show you how to configure them.

Generally the configuration file’s name is log4j.properties. It is located in the CLASSPATH ( system environment virable ) pointed directory. It is a key value pair format properties file, file content like log4j.rootLogger = INFO,FILE; When log4j library is loaded in java project, LogManager will search log4j.properties file and read the data in it. Then it will use the configuration data to create related java objects to print the log data to the configured target.

Syntax Of log4j.properties.
# Define root logger, logger level is INFO, appender name is appender1
 log4j.rootLogger = INFO, appender1

# Set appender1 to be a Console appender which will print log data to console.
 log4j.appender.appender1=org.apache.log4j.ConsoleAppender

# Define appender1's layout
 log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
 log4j.appender.appender1.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
  1. The rootLogger is the default logger for all java classes which do not has it’s own logger.
  2. If you want to define logger object for your special java class, you can use below code in this properties file.
    # Define com.dev2qa.java.basic.log4jexample class logger
    log4j.logger.com.dev2qa.java.basic.log4jexample = warn, appender1

    This logger’s name is com.dev2qa.java.basic.log4jexample. Generally it will take effect to Log4jExample java class.
Appenders
  1. You can assign multiple appenders to a logger objects like log4j.logger.[loggerName]= loggerLevel, appender1,appender2,....n
  2. Besides ConsoleAppender there are below appenders we can use in the configuration file. AsyncAppender, AppenderSkeleton, DailyRollingFileAppender, ExternallyRolledFileAppender, FileAppender, JMSAppender, JDBCAppender, LF5Appender, NullAppender, NTEventLogAppender, RollingFileAppender, SocketAppender, SMTPAppender, SyslogAppender, SocketHubAppender, TelnetAppender, WriterAppender.

You can refer to appender documents for detail introduction

READ :   Log4j Overview And Installation In Java Project
Logger Level

There are below logger levels that can be configured in the configuration file.
All, FATAL, ERROR, WARN, INFO, DEBUG
You can refer to Log4j Layer Objects Introduction to see detail explanation.

Layout

Besides PatternLayout, there are below layout that can be used with Appenders.

  1. DateLayout.
  2. XMLLayout.
  3. HTMLLayout.
  4. SimpleLayout.
  5. CSVLayout.

You can refer layout documents for detail introduction.

log4j Example In Java Project

After configuration, you can now use it in your java project with below steps.

  1. Open your Eclipse and create a java project.
  2. Save above log4j.properties in java project resources folder.
    add log4j.properties file in java project resources folder
  3. Create a java file com.dev2qa.java.basic.log4jexample.Log4jBasicExample with below code.
    	public static void main(String[] args) {
    		
    		//You can specify log4j.properties location if you do not save it in CLASSPATH directory.
    		//PropertyConfigurator.configure("C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/java/basic/log4jexample/log4j.properties");
    		
    		Logger logger = Logger.getLogger(Log4jBasicExample.class);
    		
    		logger.debug("This is debug message.");
    		logger.info("This is info message.");
    		logger.warn("This is warn message.");
    		logger.error("This is error message.");
    		logger.fatal("This is fatal message.");
    	}
    
  4. Run it, you can get below output in eclipse console.
     INFO [main] (Log4jBasicExample.java:19) - This is info message.
     WARN [main] (Log4jBasicExample.java:20) - This is warn message.
    ERROR [main] (Log4jBasicExample.java:21) - This is error message.
    FATAL [main] (Log4jBasicExample.java:22) - This is fatal message.
Specify log4j.properties File Not In ClassPath Folder 

If you want to use another log4j.properties file which is not saved in CLASSPATH directory, you can remove comment in above java code.

PropertyConfigurator.configure("C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/java/basic/log4jexample/log4j.properties");

The properties file is just saved in same folder as the java file.
specify another log4j.properties not saved in classpath directory

The properties file content has been changed to below.

  1. We have specify Log4jExample class a special logger and appender.
  2. The root logger will use a FileAppender to save log data to file.
    # Define com.dev2qa.java.basic.log4jexample class logger
    log4j.logger.com.dev2qa.java.basic.log4jexample = warn, appender1
    # Set appender1 to be a Console appender which will print log data to console.
    log4j.appender.appender1=org.apache.log4j.ConsoleAppender
    # Define appender1's layout
    log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
    log4j.appender.appender1.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
     
     # Define root logger, logger level is INFO, appender name is appender2
     log4j.rootLogger = info, appender2
     # Appender2 will save log data to file.
     log4j.appender.appender2=org.apache.log4j.FileAppender
     log4j.appender.appender2.File=C:/WorkSpace/logData.log
     log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
     log4j.appender.appender2.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

Below is the java code.

	public static void main(String[] args) {
		
		PropertyConfigurator.configure("C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/java/basic/log4jexample/log4j.properties");
		 
		Logger rootLogger = Logger.getRootLogger();
		
		// Get this class related logger object.
		Logger logger = Logger.getLogger(Log4jBasicExample.class);
		
		logger.debug("This is debug message.");
		logger.info("This is info message.");
		logger.warn("This is warn message.");
		logger.error("This is error message.");
		logger.fatal("This is fatal message.");
		
		rootLogger.debug("This is rootLogger debug message.");
		rootLogger.info("This is rootLogger info message.");
		rootLogger.warn("This is rootLogger warn message.");
		rootLogger.error("This is rootLogger error message.");
		rootLogger.fatal("This is rootLogger fatal message.");
	}

Run above java code, you will find below Log4jExample logger output in Eclipse console.

WARN [main] (Log4jBasicExample.java:21) - This is warn message.
ERROR [main] (Log4jBasicExample.java:22) - This is error message.
FATAL [main] (Log4jBasicExample.java:23) - This is fatal message.

You can also find the output data in C:/WorkSpace/logData.log file as below.

# Below is output by child logger Log4jExample.
WARN [main] (Log4jBasicExample.java:21) - This is warn message.
ERROR [main] (Log4jBasicExample.java:22) - This is error message.
FATAL [main] (Log4jBasicExample.java:23) - This is fatal message.

# Below is output by root logger.
INFO [main] (Log4jBasicExample.java:26) - This is rootLogger info message.
WARN [main] (Log4jBasicExample.java:27) - This is rootLogger warn message.
ERROR [main] (Log4jBasicExample.java:28) - This is rootLogger error message.
FATAL [main] (Log4jBasicExample.java:29) - This is rootLogger fatal message.

From the above result, we can see all child logger will extend root logger, so when execute child logger’s log method, the log data will also be printed out to the root logger’s appender.

Download “HowToConfigureLog4jExamples.zip” HowToConfigureLog4jExamples.zip – Downloaded 317 times – 2 KB

Leave a Reply

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

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