Log4j2日志记录配置未创建日志文件

h9a6wy2h  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(365)

对于一个非常基本的spring-boot应用程序,我尝试使用log4j 2 yaml配置登录到一个日志文件。但是没有创建日志文件。我试着四处看看,但是似乎没有一个解决方案起作用。

pom档案具有下列相依性:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</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>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
</dependencies>

完成日志记录的代码(也是应用程序中唯一的代码):

import com.example.demo.model.DemoData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Log4j2
@RestController
public class DemoController {

    @Value("${messageFromProperties}")
    private String messageFromProperties;

    @Value("${messageFromYaml}")
    private String messageFromYaml;

    @GetMapping("/demo")
    public ResponseEntity<DemoData> getDemoMessage(){

        DemoData demoData = new DemoData(messageFromProperties, messageFromYaml);
        log.error("ERROR!!!");
        log.debug("DEBUG!!!");
        log.info("INFO!!!");

        return ResponseEntity.ok().body(demoData);
    }
}

属性文件:

messageFromProperties: Message from properties
messageFromYaml: Message from YAML!!!

logging:
  config: classpath:log4j2.yml

log4j2.yml 文件内容。文件存在于“resources”目录中

Configuration:
  status: debug

  appenders:
    RollingFile:
      - name: LogToRollingFile
        fileName: "logs/demo.log"
        filePattern: "logs/$${date:yyyy-MM}/demo-%d{MM-dd-yyyy}-%i.log.gz"
        PatternLayout:
          pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: 10MB
        DefaultRollOverStrategy:
          max: 10

  Loggers:
    logger:
      - name: com.example
        level: debug
        AppenderRef:
          - ref: LogToRollingFile
    Root:
      level: debug
      AppenderRef:
        - ref: LogToRollingFile

我看到控制台中正在打印内容:

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.2)

17:25:49.535 [http-nio-8080-exec-2] ERROR com.example.demo.controller.DemoController - ERROR!!!
aurhwmvo

aurhwmvo1#

如果您可以将记录器配置放在单独的XML文件中,则可以尝试以下操作:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="debug_logs" value="logs/debug_logs"/>
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%12.12thread] %-50logger{36} : %msg%n</Pattern>
        </layout>
    </appender>

    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${debug_logs}/debug.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%12.12thread] %-50logger{36} : %msg%n</Pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${debug_logs}/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!--Max Size of each file to start Archive -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>

            <!-- Days till log history to keep -->
            <maxHistory>30</maxHistory>
            <totalSizeCap>150MB</totalSizeCap>
        </rollingPolicy>

    </appender>

    <!-- LOG everything at INFO level -->
    <root level="INFO">
        <appender-ref ref="RollingFile"/>
        <appender-ref ref="Console"/>
    </root>
</configuration>

一旦将此配置(logback.xml)放在与applciation.properties相同的目录中,就可以在类的顶部使用@Slf4j注解(由Lombok提供),并使用log对象记录任何所需的内容。
如果一切正常,您应该可以在/logs/debug_logs/debug.log的文件夹(与项目位于同一目录)中看到日志。

相关问题