Java Logging Framework Log4j

Java 常用类库Java Common Class Libraries


Log4j is an open-source logging framework under the Apache Software Foundation, designed specifically for Java applications.

Log4j provides flexible logging capabilities, allowing developers to control the output format, level, and target location of log information.

Main Features:

  • Highly configurable
  • Supports multiple log levels
  • Can output logs to multiple destinations (console, file, database, etc.)
  • Thread-safe
  • Excellent performance

Log4j Core Components

Logger (Log Recorder)

Logger is the core component of Log4j, responsible for capturing log information. Applications record logs by calling methods on the Logger.

Log Levels (from high to low):

  1. FATAL - Very serious errors that may cause the application to crash
  2. ERROR - Error events, but the application can still continue running
  3. WARN - Potentially harmful situations
  4. INFO - Coarse-grained runtime information
  5. DEBUG - Fine-grained debugging information
  6. TRACE - More fine-grained information than DEBUG

Appender (Output Source)

Appender defines the destination of log output. Common Appenders include:

  • ConsoleAppender: Output to the console
  • FileAppender: Output to a file
  • RollingFileAppender: Output to a file, supports file rolling
  • JDBCAppender: Output to a database

Layout

Layout controls the format of log information. Commonly used Layouts include:

  • PatternLayout: Uses a pattern string to define the format
  • SimpleLayout: Simple format (level + message)
  • HTMLLayout: HTML table format

Basic Usage of Log4j

Add Dependency

For Maven projects, add to pom.xml:

Example

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Configuration File (log4j.properties)

Example

# Set root log level to INFO, output sources are console and file
log4j.rootLogger=INFO, console, file

# Console output configuration
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# File output configuration
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/application.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Java Code Example

Example

import org.apache.log4j.Logger;

public class Log4jExample {
    // Get Logger instance
    private static final Logger logger = Logger.getLogger(Log4jExample.class);
   
    public static void main(String[] args) {
        // Log messages at different levels
        logger.trace("This is a TRACE message");
        logger.debug("This is a DEBUG message");
        logger.info("This is an INFO message");
        logger.warn("This is a WARN message");
        logger.error("This is an ERROR message");
        logger.fatal("This is a FATAL message");
       
        try {
            int result = 10 / 0;
        } catch (Exception e) {
            logger.error("An error occurred: ", e);
        }
    }
}

Advanced Configuration of Log4j

Set Different Log Levels by Package/Class

Example

# Set the log level for the com.example package to DEBUG
log4j.logger.com.example=DEBUG

Using Multiple Loggers

Example

// Get different Logger instances
Logger mainLogger = Logger.getLogger("main");
Logger dbLogger = Logger.getLogger("database");

mainLogger.info("Application started");
dbLogger.debug("Database connection established");

Asynchronous Logging

For applications with high performance requirements, AsyncAppender can be used to implement asynchronous logging:

Example

log4j.appender.async=org.apache.log4j.AsyncAppender
log4j.appender.async.appender-ref=file

New Features in Log4j 2.x

Log4j 2.x is an upgraded version of Log4j, providing more improvements:

  • Significant performance improvement
  • Supports plugin architecture
  • More flexible configuration methods (XML, JSON, YAML)
  • Supports lambda expressions
  • Automatically reloads configuration files

Log4j 2.x Basic Configuration Example (log4j2.xml)

Example

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="logs/application.log">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>

Best Practices

  1. Use log levels reasonably: Use INFO or WARN in production, and DEBUG in development
  2. Avoid excessive logging: Only log necessary information to avoid performance issues
  3. Use meaningful log messages: Messages should contain enough context information for troubleshooting
  4. Log the stack trace when handling exceptions: Use the logger.error("message", exception) format
  5. Regularly archive and clean up logs: Prevent log files from becoming too large

Summary

Log4j is a widely used logging framework in the Java ecosystem. Mastering its usage is crucial for developing high-quality Java applications. With proper configuration and usage, Log4j can help developers:

  • Quickly locate and resolve issues
  • Monitor application runtime status
  • Record important business operations
  • Improve the maintainability of applications

For new projects, it is recommended to consider using Log4j 2.x, which offers better performance and more features.

Java 常用类库Java Common Class Libraries

Other Extensions