Home > Java > javaTutorial > How to solve the error when integrating log4j with springboot

How to solve the error when integrating log4j with springboot

王林
Release: 2023-05-11 10:07:05
forward
1860 people have browsed it

    1. Adding dependencies

    1.1. Adding dependencies

    You need to introduce dependency support for log4j. It is recommended that you determine the version to use.

    <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.11.2</version>
    </dependency>
    Copy after login

    1.2. Eliminate dependencies

    springboot has built-in support for logs by default, and all of them need to be removed, otherwise it will affect the dependency of log4j.

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
            <exclusions>
                <exclusion>
                   <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
    </dependency>
    Copy after login

    2. Configuration log

    2.1. Log printing record

     Configure related configurations according to your own needs. What needs to be noted here is to use xml files for configuration. There are pitfalls in using properties. The file name is customized. There are no requirements. It will be specified in the configuration file.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration  scan="true" scanPeriod="10 seconds">
        <contextName>beordie</contextName>
        <property name="path" value="E:\file\javalearn\blog\src\main\resources\logs" />
        <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
        <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
        <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
        <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                <level>info</level>
            </filter>
            <encoder>
                <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
                <charset>UTF-8</charset>
            </encoder>
        </appender>
    
        <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${path}/debug.log</file>
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>debug</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${log}/info.log</file>
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>info</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${log}/warn.log</file>
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>warn</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${log}/error.log</file>
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>ERROR</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <springProfile name="dev">
            <logger name="com.beordie" level="debug"/>
        </springProfile>
    
        <root level="info">
            <appender-ref ref="CONSOLE" />
            <appender-ref ref="DEBUG_FILE" />
            <appender-ref ref="INFO_FILE" />
            <appender-ref ref="WARN_FILE" />
            <appender-ref ref="ERROR_FILE" />
        </root>
    </configuration>
    Copy after login

    2.2. Specify the configuration file

    You also need to specify the configuration in the project configuration file of spring boot.

    logging:
      config: classpath:log4j.xml
    Copy after login

    Complete the overall configuration of the log here. Start the project and get the log object through the following statement to print the log.

    private final Logger LOGGING = LoggerFactory.getLogger(ArticleController.class);
    Copy after login

    Supplement: log4j tuning and precautions

    Log mode-synchronization/asynchronous

    log4j2 provides AsyncAppender, AsyncLogger and global asynchronous, enable The method is as follows:

    • Synchronous mode: The default configuration is synchronous mode, that is, no AsyncAppender and AsyncLogger are used.

    • Global asynchronous: The configuration is configured in a synchronous manner. Global asynchronous can be turned on by adding jvm startup parameters without modifying the configuration and application.

    • Mixed asynchronous: Use a mixed configuration of asynchronous Logger and synchronous Logger, and do not enable global asynchronous, that is, part of the Logger configuration is AsyncLogger and part of Logger.

    Notes on using log mode:

    • If you use asynchronous, it is recommended to use AsyncLogger implementation instead of AsyncAppender.

    • If you use synchronization, you can only use one of AsyncLogger, AsyncAppender and global async. You cannot configure AsyncAppender and AsyncLogger at the same time, or enable global async when async is configured.

    Log rolling and clearing strategy

    log4j2 provides a file size-based rolling strategy and a time-based rolling strategy, or both can be used together , here are the size-based rolling policy configuration and the size/time-based dual rolling policy configuration:

    • Size-based rolling policy: roll according to size, enable compression, and retain at most N File

    • Based on size/time dual rolling rolling strategy: rolling based on size and time, enabling compression, controlling the maximum number of logs retained per unit time and controlling the total log retention time.

    The above is the detailed content of How to solve the error when integrating log4j with springboot. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template