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 you 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.

1. How Does Log4j Works?

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

1.1 Syntax Of log4j.properties.

  1. Below is an example of log4j.properties file.
    # Define root logger, logger level is INFO, appender name is appender1
     log4j.rootLogger = INFO, appender1
    
    # Set appender1 to be a Console appender that 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
  2. The rootLogger is the default logger for all java classes which do not has it’s own logger.
  3. If you want to define a logger object for your special java class, you can use the below code in this properties file.
    # Define com.dev2qa.java.basic.log4jexample class logger
    log4j.logger.com.dev2qa.java.basic.log4jexample = warn, appender1
  4. The above logger’s name is com.dev2qa.java.basic.log4jexample. Generally, it will take effect to Log4jExample java class.

1.2 Appenders.

  1. You can assign multiple appenders to a logger object 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.
  3. You can refer to appender documents for a detailed introduction.

1.3 Logger Level.

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

1.4 Layout.

  1. Besides PatternLayout, there are below layouts that can be used with Appenders.
  2. DateLayout.
  3. XMLLayout.
  4. HTMLLayout.
  5. SimpleLayout.
  6. CSVLayout.
  7. You can refer to layout documents for a detailed introduction.

2. log4j Example In Java Project.

  1. After configuration, you can now use it in your java project with the below steps.
  2. Open your Eclipse and create a java project.
  3. Save above log4j.properties in the java project resources folder.
    add-log4j.properties-file-in-java-project-resources-folder
  4. Create a java classcom.dev2qa.java.basic.log4jexample.Log4jBasicExample and copy & paste the below code into it.
    public static void main(String[] args) {
            
        //You can specify log4j.properties location if you do not save it in the 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.");
    }
    
  5. Run it, you can get the below output in the 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.

3. Specify log4j.properties File Not In ClassPath Folder.

  1. If you want to use another log4j.properties file that is not saved in the CLASSPATH directory, you can remove the comment in the above java code. Below is the java code.
    PropertyConfigurator.configure("C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/java/basic/log4jexample/log4j.properties");
  2. The properties file is just saved in the same folder as the java file.
    specify-another-log4j.properties-not-saved-in-classpath-directory
  3. The properties file content has been changed to below.
  4. In the below log4j.properties file content, we have specify Log4jExample class a special logger and appender.
  5. And 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
  6. 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.");
    }
  7. 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.
  8. You can also find the output data in C:/WorkSpace/logData.log. Below is the log data content.
    # 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.
  9. From the above result, we can see all child loggers will extend the root logger, so when executing the child logger’s log method, the log data will also be printed out to the root logger’s appender.

Leave a Comment

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.