【问题标题】:Write logs to a file and console in spring boot project using log4j2.xml使用 log4j2.xml 将日志写入 Spring Boot 项目中的文件和控制台
【发布时间】:2019-09-16 15:27:14
【问题描述】:

我尝试创建简单的 Spring Boot 应用程序,其中日志应在控制台和项目文件夹之外的文件中打印。日志能够在控制台中打印但不能写入文件。我指定了文件位置(文件没有创建,我认为文件会自动生成)

这是添加的依赖项

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Add Log4j2 Dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
</dependencies>

这里是 log4j.xml 文件(位置 src/main/resources/log4j2.xml)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>

    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT"
            follow="true">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>

        <!-- Rolling File Appender -->
        <RollingFile name="FileAppender"
            fileName="/home/ubuntu/Documents/eclipse/logs/log4j2-demo.log"
            filePattern="logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" />
                <SizeBasedTriggeringPolicy size="10MB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
    </Appenders>

    <Loggers>

        <Root level="debug">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </Root>
    </Loggers>
</Configuration>

我在主类中添加了日志功能

    import org.apache.logging.log4j.LogManager;

    import org.apache.logging.log4j.Logger;

    import org.springframework.boot.SpringApplication;

    import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LoggingApplication {

    private static final Logger logger = LogManager.getLogger(LoggingApplication.class);


    public static void main(String[] args) {
        logger.info("in main class");
        logger.info("info logging is printed");
        logger.debug("logger debud is worked");
        logger.warn("logging warn is worked");
        SpringApplication.run(LoggingApplication.class, args);
    }

}

这是控制台:

【问题讨论】:

  • 我会尝试从 in the documentation 概述的类路径中删除 logback binder。在文档中,他们建议从您的 Maven 依赖项中排除日志记录启动器。
  • 我要做的另一件事是直接使用来自slf4j 的记录器API,而不是直接使用log4j。 Spring boot 已经配置为将 slf4j 与类路径上的任何绑定器一起使用。因此,您的输出中出现重复绑定错误。因此,我将使用org.slfj.Logger 作为您的记录器类并使用org.slf4j.LoggerFactory.getLogger() 创建它。与直接使用 log4j 类相比,这样做的好处是您可以在 slf4j 下切换活页夹,而无需更改所有代码。
  • @TaylorO'Connor 考虑将评论总结为答案,因为它们是正确的,并且将使这篇文章的未来读者受益。

标签: spring-boot log4j2


【解决方案1】:

我要做的第一件事是尝试按照in the documentation 的概述从类路径中删除 logback binder。

因此,您的 pom.xml 配置最终会包含一个排除项,例如:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

此外,我建议不要直接使用 log4j API 类,而是使用 sfl4j API。 spring-boot 已经配置为将 SL4J 与您在类路径上配置的任何绑定器一起使用(在本例中为 log4j)。

因此,我不会使用org.apache.logging.log4j.Logger,而是将org.slfj.Logger 用于您的记录器类,并使用org.slf4j.LoggerFactory.getLogger() 创建它。与直接使用 log4j 类相比,这样做的好处是您可以在 slf4j 下切换活页夹,而无需更改所有代码。以防万一您以后决定要使用 logback 或其他东西。

如果您对 pom 进行更改并使用 slf4j API,我认为 spring-boot 自动配置将加载您的配置并开始记录到文件附加程序以及控制台.

【讨论】:

    【解决方案2】:

    你可以这样做:

    application.properties

    #####LOGGING. . . .
    logging.level.org.springframework.web=ERROR
    logging.level.com.hsc.adauth.*=DEBUG
    
    # Logging pattern for the console
    logging.pattern.console="%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
    
    # Logging pattern for file
    logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
    
    #output to a temp_folder/file(give your file path here)
    logging.file=${java.io.tmpdir}/application.log
    

    您也可以使用 AOP 来集中登录您的应用程序.....

    【讨论】:

    • logging.file 应该是logging.file.name
    【解决方案3】:

    请遵循以下方法,这里我为单个记录器配置了两个附加程序。如果您使用该记录器名称记录任何内容,则所有日志消息都将发送到这两个地方。在您的情况下,控制台和文件。

     <logger name="pushnotification" level="debug" additivity="false">
                <appender-ref ref="NOTIFICATION-FILE-APPENDER" />
        <appender-ref ref="NOTIFICATION-CONSOLE-APPENDER" />
            </logger>
    
        <appender name="NOTIFICATION-CONSOLE-APPENDER" class="ch.qos.logback.core.ConsoleAppender">
                <encoder
            class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>[%date{yyyy-MM-dd HH:mm:ss}][%level][%c][%t] - %msg%n
            </pattern>
        </encoder>
            </appender>
    
        <appender name="NOTIFICATION-FILE-APPENDER"
                class="ch.qos.logback.core.rolling.RollingFileAppender">
                <file>${logs.home}/applogs/notification.log</file>
                <append>true</append>
            </appender>
    

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 2019-01-10
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多