Installation and configuration explanation of Log4j and Log4j2

What is a log?

A log is a file that records detailed information about events or behaviors that occur when a system or application is running. It usually includes information such as timestamp, event type, event description, etc., so that troubleshooting, performance optimization, security auditing, etc. can be performed when needed. Logs can help developers and system administrators diagnose application problems, understand system operation, and archive and monitor events.

What is log4j?

log4j is a Java logging framework that can record application logs in a very flexible way. It provides a way to configure log output and log levels at runtime, allowing developers to easily control log output. It also supports a variety of log output formats and output targets, such as output to the console, files, databases, etc. . log4j is very mature and widely used in various Java applications.

Why use log4j?

log4j is a Java logging framework used to record log information in applications. It can help programmers manage and output logs, improving code readability, maintainability and scalability.

The main concepts of log4j include:

  1. Logger: Logger, used to record log information. Each Logger can have its own log level and Appender.

  2. Level: Log level, used to specify the importance of log information. Including TRACE, DEBUG, INFO, WARN, ERROR and FATAL levels.

  3. Appender: Log outputter, used to output log information to different destinations, such as console, file, database, etc.

  4. Layout: Log layout, used to specify the format of log information.

  5. Filter: Log filter, used to filter unnecessary log information based on conditions.

  6. Configuration: Log configuration, used to configure loggers, outputters, layouts, filters, etc. Can be configured through configuration files, code or annotations.

Advantages of log4j

Log4j is an open source project for the Java programming language that integrates with Java applications and provides custom logging capabilities. Here are some advantages of using Log4j:

  1. Flexibility: Log4j can be configured and used according to specific needs, and you can control the log level, output destination and format, etc.

  2. Performance: Log4j has efficient logging capabilities that enable fast and efficient logging in applications.

  3. Maintainability: Log4j can help developers quickly discover and solve log problems in applications, helping to improve code quality and maintainability.

  4. Scalability: Log4j allows developers to implement custom logging functions that can be expanded and customized according to different needs.

  5. Community support: Log4j is a widely used and supported open source project, with extensive documentation and community resources available for reference and use.

The main concepts of log4j2 include:

Following are the main concepts of log4j2:

  1. Logger: A component responsible for recording log information. Different loggers are usually distinguished by their names.

  2. Appender: Responsible for outputting the log information generated by the logger to the specified destination, such as the console, file, etc.

  3. Layout: Responsible for outputting the information generated by the logger in a specified format. The layout can be customized.

  4. Filter: Responsible for filtering log information and outputting only log information that meets specific conditions.

  5. Configuration: Responsible for configuring the logging system, including defining loggers, appenders, layouts, filters, etc.

  6. Level: Responsible for defining the importance of log information, such as TRACE, DEBUG, INFO, WARN, ERROR, FATAL, etc.

  7. Marker: Responsible for adding additional marks to log information to facilitate subsequent processing and classification.

  8. ContextMap: Responsible for storing key information in the context in the form of key-value pairs to facilitate subsequent query and analysis.

Advantages of log4j2

log4j2 is a logging framework from the Apache Software Foundation and has the following advantages:

  1. High performance: log4j2 uses asynchronous log writing to achieve better performance.

  2. Flexibility: log4j2 provides a variety of output modes and filters to meet various scenarios and needs.

  3. Plug-in: log4j2 supports plug-in extensions and can be quickly integrated into different systems through plug-ins.

  4. Multi-thread safety: log4j2 is thread-safe, and data inconsistency will not occur in multi-threads.

  5. Supports multiple programming languages: log4j2 supports multiple programming languages and can be used in languages such as Java, Scala and Kotlin.

Download and installation configuration of log4j and log4j2

The following are the download and installation steps for log4j:

  1. Visit the Apache log4j official website to download the latest version of log4j.

Log4j 1.2.17 official website download address

Log4j2 official website download address

  1. Unzip the downloaded zip file.
  2. Unzip the files into the created lib folder
    1. Copy the [log4j-api-2.14.1.jar] and [log4j-core-2.14.1.jar] files after decompression of log4j2 to the lib directory created by the project.
    2. Copy the [log4j-1.2.17.jar] file after decompression of log4j to the lib directory created by the project.
  3. Add the log4j configuration file log4j.properties or log4j.xml to the project.
  4. The first configuration file (log4j2 configuration file):
    1. Create a new configuration file under src [log4j.xml]
    2. Log4j2 configuration files can only use: .xml, .json, .jsn.
    3. <?xml version="1.0" encoding="UTF-8"?>
      
      <!-- The level of internal Log4j events recorded to the console by status, which can be defaulted -->
      <!-- monitorInterval sets the interval for checking file changes, unit S, check once per second -->
      <configuration status="WARN" monitorInterval="1">
      
          <!--Log printing level: fatal > error > warn > info > debug > trace -->
      
          <!-- Global variable, reference the variable through ${name} -->
          <Properties>
              <!-- Log printing path -->
              <Property name="LOG_HOME">../logs/fc-asset</Property>
              <!-- History log printing path -->
              <Property name="HISTORY_LOG_HOME">${LOG_HOME}/history</Property>
              <!-- Unified log printing format: 2020-07-01 21:14:48, 987 [main] [INFO] [com.fc.asset.FcAssetApplication] [FcAssetApplication.java:15] - message -->
              <Property name="LOG_PATTERN"
                        value="?te{yyyy-MM-dd HH:mm:ss, SSS} [%thread] [%-5level] [%logger{36}] [%file:%line] - %msg%n" />
          </Properties>
      
          <!-- Responsible for transmitting logs to the configuration destination, configuring log printing content, format, method, storage strategy, etc. -->
          <Appenders>
              <!-- Console log printing configuration -->
              <console name="Console" target="SYSTEM_OUT">
                  <!-- Print format -->
                  <PatternLayout charset="UTF-8" pattern="${LOG_PATTERN}"/>
              </console>
      
              <!-- File printing configuration, supports file rolling archiving and caching; filePattern sets the rolling unit to S, %i represents a positive integer starting from 1, %3i can be 3 digits -->
              <RollingRandomAccessFile name="normalLog" fileName="${LOG_HOME}/fc-asset.log"
                                       filePattern="${HISTORY_LOG_HOME}/fc-asset_%d{yyyy-MM-dd HH:mm:ss}_%i.log">
                  <!-- Print format -->
                  <PatternLayout charset="UTF-8" pattern="${LOG_PATTERN}"/>
                  <!-- Rolling strategy -->
                  <Policies>
                      <!-- Generate a new log file every time the file exceeds 1KB -->
                      <SizeBasedTriggeringPolicy size="1KB"/>
                      <!-- Generate a new log file every 2 seconds and correct the time -->
                      <TimeBasedTriggeringPolicy interval="2" modulate="true"/>
                  </Policies>
                  <!-- The same second log file can only be split into two at most -->
                  <DefaultRolloverStrategy max="2"/>
              </RollingRandomAccessFile>
          </Appenders>
      
          <!-- Log printing configuration, Appender will take effect only if Appender is configured here -->
          <Loggers>
              <!-- Only print logs containing the contents of com.fc.asset, the printing level is trace, and feed them back to Root -->
              <Logger name="com.fc.asset" level="trace" additivity="true">
                  <AppenderRef ref="normalLog"/>
              </Logger>
              <!-- Root sets the printing level to trace and prints the console -->
              <Root level="trace">
                  <AppenderRef ref="Console"/>
              </Root>
          </Loggers>
      </configuration>
  5. The second configuration file (log4j 1.2.17 configuration file):

    1. Create a new configuration file under src [log4j.properties]

    2. The following is a simple log4j.properties configuration file example:

      # Define root logging level and output destination
      log4j.rootLogger=DEBUG, stdout
      
      #Define console output destination
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c{1} - %m%n
      
      # Define log output level
      log4j.logger.com.example=DEBUG
      

      This configuration file sets the root logging level to DEBUG and outputs logs to the console (stdout). The log output format uses ISO8601 time format, including thread name, log level, class name and log content. For classes under the com.example package, DEBUG level logs will be recorded.

Next chapter: Use of log4j and log4j2