Spring-boot读书笔记一Introduction of logging framework of Log4j2

Log4j2 is a powerful and flexible logging framework for Java applications. Here's an overview of its key components and features:

Core Components

  • Logger - The main interface for logging messages. Loggers are named entities that capture log events.
  • Appender - Defines where log messages are sent (console, files, databases, etc.).
  • Layout - Controls the format of log messages (JSON, XML, pattern-based, etc.).
  • Configuration - Defines loggers, appenders, and their relationships through XML, JSON, YAML, or properties files.

Key Features

  • Asynchronous Logging - High-performance logging with minimal impact on application threads
  • Automatic Reloading - Configuration changes are detected and applied without restarting
  • Plugin Architecture - Extensible system for custom appenders, layouts, and filters
  • Lambda Support - Lazy evaluation of log messages for better performance
  • Garbage-Free Logging - Reduces memory allocation and GC pressure

Log Levels (Hierarchy)
FATAL > ERROR > WARN > INFO > DEBUG > TRACE

Basic Configuration Example
For your Spring Boot application, you can configure Log4j2 using log4j2.xml:


<?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="FileAppender" fileName="logs/application.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    
    <Loggers>
        <Logger name="com.example" level="DEBUG"/>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="FileAppender"/>
        </Root>
    </Loggers>
</Configuration>

Common Appenders

  • ConsoleAppender - Outputs to console/terminal
  • FileAppender - Writes to files
  • RollingFileAppender - Rotates log files based on size/time
  • AsyncAppender - Wraps other appenders for asynchronous logging
  • JDBCAppender - Logs to databases
  • SMTPAppender - Sends logs via email

Performance Benefits

  • Log4j2 offers significant performance improvements over Log4j 1.x:
  • 10x faster than Log4j 1.x and Logback
  • Garbage-free logging in steady state
  • Asynchronous loggers for high-throughput applications

For Spring Boot applications, Log4j2 integrates seamlessly and can replace the default Logback implementation by excluding it from dependencies and adding Log4j2 starter.

posted @ 2025-12-31 01:14  kkbln  阅读(1)  评论(0)    收藏  举报