首页 > 解决方案 > Log4j 引入配置文件并将所有内容打印到控制台

问题描述

我正在尝试使用 Log4j 记录信息。我创建了 log4j.properties:

# Root logger option
log4j.rootLogger=INFO, file, stdout
# configuration to print into file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\log\\logging.log
log4j.appender.file.MaxFileSize=12MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# configuration to print on console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

包括记录器:

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

并尝试记录:

   logger.debug("Debugging log");
    logger.info("Info log");
    logger.warn("Hey, This is a warning!");
    logger.error("Oops! We have an Error. OK");
    logger.fatal("Damn! Fatal error. Please fix me.");

然而,一切都登录到控制台(调试被忽略)。

我的属性文件在\src\main\resources文件夹中,我尝试过使用基于 xml 的配置,但结果是一样的,没有运气将它打印到文件中。

我在配置上有什么错误吗?或者问题的根源在哪里?

感谢帮助

编辑:

我正在使用 maven 和 spring-boot,我有这个依赖:

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

标签: javaspring-bootlogginglog4j

解决方案


请阅读此文档以获取自定义文件命名https://docs.spring.io/spring-boot/docs/1.2.1.RELEASE/reference/htmlsingle/#boot-features-custom-log-levels

可以肯定的是,我假设您使用的是Log4jnot Log4j2

起初,根日志记录级别INFO不正确。应该是DEBUG在这种情况下。这里有一篇关于级别层次结构的不错的 SO Post log4j logging hierarchy order

所以,根记录器应该如下

log4j.rootLogger=DEBUG, file, stdout

最后,似乎排除 XML 不正确。您将在此处找到用于记录文档的配置 Log4j https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html请注意,在此文档中,参考是 Log4j2。对于我们的案例,我们需要添加 Log4J 依赖项。这是我的 XML:

<dependencies>
    <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>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

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

推荐阅读