29. Java Foundation - Log4j Configuration and Use

Posted by dvonj on Thu, 01 Aug 2019 08:12:05 +0200

I. Introduction Examples

1. Configure dependencies in maven's pom file as follows:

<!-- log4j support -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2. Create the log4j.properties file in the resource directory as follows:

# Set up
log4j.rootLogger = debug,stdout,D,E

# Output to console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

# Output logs above DEBUG level to=/home/duqi/logs/debug.log 
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = /home/duqi/logs/debug.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

# Output ERROR level logs to=/home/admin/logs/error.log 
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =/home/admin/logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

3. Examples of input logs

package com.javadu.log;

import org.apache.log4j.Logger; 

public class Log4JTest {
    private static final Logger logger = Logger.getLogger(Log4JTest.class);

    public static void main(String[] args) {
        // Record debug level information
        logger.debug("This is debug message.");
        // Recording info level information
        logger.info("This is info message.");
        // Recording error level information
        logger.error("This is error message.");
    }
}

II. Basic usage of Log4j

Log4j consists of three important components:

  • Priority of log information
    • The priority of log information is ERROR, WARN, INFO and DEBUG, which are used to specify the importance of the log information.
  • Output destination of log information
    • The output destination of the log information specifies whether the log will be printed to the console or to a file.
  • Output format of log information
    • Output format controls the display of log information

2.1 Define Configuration Files

In fact, you can also configure the Log4j environment in your code without using the configuration file at all. However, using configuration files will make your application more flexible.

Log4j supports two configuration file formats, one is the XML format file and the other is the Properties file (key = value). Here we describe how to use the Properties file as a configuration file:

Configure rootLogger with the following syntax:

That is, specify the priority of log records and the output destination:

log4j.rootLogger = [ level ] , appenderName, appenderName, ...

Among them, level is the priority of logging, which is divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you defined.
Log4j recommends using only four levels, with priority from high to low being ERROR, WARN, INFO and DEBUG, respectively. By defining the level here, you can control the switch to the corresponding level of log information in the application. For example, if the INFO level is defined here, all DEBUG level log information in the application will not be printed out.

AppnderName is where the log information is exported. You can specify multiple output destinations at the same time, such as stdout, D, and E.

The output destination of the configuration file, Appender, generally has the following configuration code format

log4j.appender.appenderName = fully.qualified.name.of.appender.class  
log4j.appender.appenderName.option1 = value1  
...  
log4j.appender.appenderName.option = valueN

Among them, Log4j provides Appenders as follows:

  • org.apache.log4j.ConsoleAppender (console)
  • org.apache.log4j.FileAppender (file)
  • Org. apache. log4j. Daily Rolling File Appender (produces a log file every day)
  • org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size)
  • org.apache.log4j.WriterAppender (sending log information in streaming format to any designated place)

Configure the format (layout) of log information with the following syntax:

log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class  
log4j.appender.appenderName.layout.option1 = value1  
...  
log4j.appender.appenderName.layout.option = valueN

There are several layout s provided by Log4j:

  • org.apache.log4j.HTMLLayout (laid out in HTML tables)
  • org.apache.log4j.PatternLayout (you can specify layout patterns flexibly)
  • org.apache.log4j.SimpleLayout (level and information string containing log information)
  • org.apache.log4j.TTCCLayout (including log generation time, threads, categories, etc.)

Log4J formats log information with print format similar to the printf function in C language. The print parameters are as follows:

  • % m The message specified in the output code
  • % p Output Priority, namely DEBUG, INFO, WARN, ERROR, FATAL
  • % r Number of milliseconds taken to output log information from application startup
  • % c Outputs the full name of the class to which it belongs.
  • % t outputs the thread name that produces the log event
  • % n outputs a return line break, Windows platform is "rn" and Unix platform is "n"
  • % d outputs the date or time of the log time point, the default format is ISO8601, or you can specify the format later, such as:% d{yyy MMM dd HH:mm:ss,SSS}. The output is similar: 22:10:28, 921, October 18, 2002.
  • % l Output the location of the log event, including the class name, the thread that occurred, and the number of lines in the code. Examples: Testlog4.main(TestLog4.java:10)

Topics: Programming log4j Apache Maven xml