杰瑞科技汇

log4j.xml java

Of course! Here is a comprehensive guide to log4j2.xml, the primary configuration file for the Log4j 2 logging framework in Java.

We'll cover:

  1. What is log4j2.xml?
  2. Basic Structure of the File
  3. Key Components Explained (Loggers, Appenders, Layouts)
  4. Complete, Practical Examples (from simple to advanced)
  5. How to Use it in Your Java Code
  6. Best Practices

What is log4j2.xml?

log4j2.xml is an XML configuration file used by the Apache Log4j 2 library to control how your application logs messages. It allows you to define:

  • Where logs go (Console, File, Database, etc.) - these are Appenders.
  • What logs are captured (for specific packages or classes) - these are Loggers.
  • What the log messages look like (Simple text, JSON, with timestamps, etc.) - these are Layouts.

By changing this file, you can configure your logging without recompiling your Java code.


Basic Structure of the File

A log4j2.xml file has a root element <Configuration>. Inside it, you typically define three main sections:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN"> <!-- status can be OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE -->
    <!-- 1. Properties (Optional): Define reusable variables -->
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
        <Property name="APP_LOG_FILE">logs/my-app.log</Property>
    </Properties>
    <!-- 2. Appenders: Define the "where" of logging -->
    <Appenders>
        <!-- ... appenders like Console, File, etc. ... -->
    </Appenders>
    <!-- 3. Loggers: Define the "what" and "how" of logging -->
    <Loggers>
        <!-- ... loggers like Root, specific package loggers ... -->
    </Loggers>
</Configuration>

Key Components Explained

A. <Appenders>: Where the logs go

An Appender is a component that sends log events to a destination.

  • Console: Outputs logs to the standard output (your terminal/IDE console).
    • PatternLayout: The most common layout. It formats the log string using a pattern.
  • File: Writes logs to a file. It will create the file if it doesn't exist.
  • RollingFile: An advanced file appender that archives log files when they reach a certain size or date.
  • RollingRandomAccessFile: A high-performance version of RollingFile, often preferred for high-throughput applications.
  • Syslog: Sends logs to a syslog server.
  • JDBC: Writes logs to a database table.

B. <Loggers>: What gets logged

A Logger is responsible for capturing log events based on their name and level.

  • Root Logger: The main logger that catches all log events in your application if no more specific logger handles them. It's required.
    • level: The minimum severity level it will handle (e.g., INFO, DEBUG, WARN, ERROR, FATAL).
    • AppenderRef: A reference to an Appender defined in the <Appenders> section.
  • Logger: A specific logger for a package or class. It inherits from the Root Logger but can have its own level and appenders.
    • name: The name, typically a fully qualified package name (e.g., com.mycompany.myapp) or class name.
    • level: Can override the Root Logger's level for this specific logger.
    • additivity="false": A crucial attribute. If true, logs are passed to the parent logger (and its appenders) in addition to this logger's appenders. If false, logs are only sent to this logger's appenders. This prevents duplicate logs.

C. <Layouts>: What the log message looks like

A Layout formats the log event into a string. It's always nested inside an Appender.

  • PatternLayout: The most flexible layout. It uses conversion characters to build the pattern.
    • %d{pattern}: Date. Example: %d{yyyy-MM-dd HH:mm:ss.SSS}.
    • %t: Name of the thread generating the log.
    • %p or %level: Log level (e.g., DEBUG, INFO).
    • %c or %logger: Logger name. {36} truncates it to 36 characters.
    • %m or %msg: The log message.
    • %n: Platform-dependent newline character.
    • %L: Line number in the source code.
    • %M: Method name.

Complete, Practical Examples

Example 1: Simple Console Logging

This is the most basic setup. It logs everything at INFO level or higher to the console.

<?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>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Output:

14:30:15.123 [main] INFO  com.mycompany.myapp.MyApplication - Application starting...
14:30:15.456 [main] INFO  com.mycompany.myapp.MyApplication - Application started successfully.

Example 2: File and Console Logging with Different Levels

This example logs DEBUG and higher to a file, but only INFO and higher to the console. It also demonstrates a specific logger for a database package.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
        <Property name="APP_LOG_FILE">logs/application.log</Property>
    </Properties>
    <Appenders>
        <!-- Console Appender for INFO and above -->
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
        <!-- Rolling File Appender for DEBUG and above -->
        <RollingFile name="FileAppender" fileName="${APP_LOG_FILE}"
                     filePattern="logs/application-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- Specific logger for the database package -->
        <Logger name="com.mycompany.myapp.dao" level="debug" additivity="false">
            <AppenderRef ref="FileAppender"/>
        </Logger>
        <!-- Root logger catches everything else -->
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="FileAppender"/>
        </Root>
    </Loggers>
</Configuration>

How this works:

  1. Log messages from com.mycompany.myapp.dao will be logged at DEBUG level and only go to the FileAppender (because additivity="false").
  2. All other log messages (from other packages) will be handled by the Root logger. They will be logged at INFO level or higher.
  3. The Root logger sends these messages to both the Console and the FileAppender.

Example 3: Advanced (JSON for ELK/Splunk)

If you're using a log aggregation system like the ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk, JSON format is ideal.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="JSONConsole" target="SYSTEM_OUT">
            <JsonLayout compact="true" eventEol="true"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="JSONConsole"/>
        </Root>
    </Loggers>
</Configuration>

Output:

{"timestamp":"2025-10-27T10:00:00.123+00:00","level":"INFO","thread":"main","logger":"com.mycompany.myapp","message":"Application starting...","contextMap":{},"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger"}

How to Use it in Your Java Code

  1. Add Log4j2 Dependency (using Maven):

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.23.1</version> <!-- Use the latest stable version -->
    </dependency>
  2. Place log4j2.xml: Put the log4j2.xml file in the src/main/resources directory of your Maven project. It will be automatically copied to the root of the classpath ().

  3. Use the Logger in your code:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    public class MyApplication {
        // Get a logger instance for this class
        private static final Logger logger = LogManager.getLogger(MyApplication.class);
        public void run() {
            // Log messages at different levels
            logger.info("Application starting...");
            try {
                // Some business logic
                logger.debug("Performing a debug operation.");
                // ...
            } catch (Exception e) {
                logger.error("An error occurred!", e); // The exception will be printed with the stack trace
            }
            logger.info("Application finished.");
        }
        public static void main(String[] args) {
            MyApplication app = new MyApplication();
            app.run();
        }
    }

Best Practices

  1. Use RollingFile Appenders: Never use a simple File appender in production. Your log files will grow indefinitely and consume all your disk space. RollingFile manages this for you.
  2. Set additivity="false": Be explicit. When you create a specific logger, decide if its logs should also go to the parent logger. Setting additivity="false" prevents unexpected duplicate log entries.
  3. Use Descriptive Logger Names: Always use LoggerManager.getLogger(MyClass.class). This makes it easy to filter logs in a complex application.
  4. Log at the Right Level:
    • TRACE: Very detailed information, for developers.
    • DEBUG: Detailed information on the flow of the application.
    • INFO: Highlights the progress of the application at a coarse-grained level. (e.g., "User logged in", "Order processed").
    • WARN: Potentially harmful situations. (e.g., "Using a deprecated feature").
    • ERROR: Error events that might still allow the application to continue running.
    • FATAL: Very severe errors that might lead to application termination.
  5. Don't Log Sensitive Data: Be careful not to log passwords, API keys, or personal information in your logs.
  6. Place Configuration in Classpath: Always place log4j2.xml in src/main/resources so it's on the classpath. Log4j will automatically find it. Avoid hardcoding the file path.
分享:
扫描分享到社交APP
上一篇
下一篇