【问题标题】:Log4j2 does not write to log file, nor does it create itLog4j2 不会写入日志文件,也不会创建它
【发布时间】:2018-06-12 07:04:58
【问题描述】:

我知道之前有人问过这个问题,但是我仍然无法让 log4j2 写入文件(甚至没有创建文件)。但是它确实会显示在控制台上。

我已将 log4j2.xml 放在 src/main/resources 中:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="error.log" immediateFlush="false"
            append="false">
            <PatternLayout
                pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="all">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>

我的 main 方法,它调用日志记录函数

@SpringBootApplication
public class SpringApplication1 {


    public static final Logger logger = LogManager.getLogger(SpringApplication1.class);
    public static void main(String[] args) {

        SpringApplication.run(SpringApplication1.class, args);
        logger.info("testing info");
        logger.error("this is an error");

    }

我的 pom.xml 中有这两个依赖项

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

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

【问题讨论】:

    标签: log4j2


    【解决方案1】:

    spring-jcl 需要在类路径中。

    Spring Boot 的默认日志机制是 logback。

    一种方法是使用Spring Boot Log4j starter。要使用 log4j,应排除 logback:

    <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>
    

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 2014-05-16
      相关资源
      最近更新 更多