繁体   English   中英

spring 中的自定义日志级别使用 log4j2 引导

[英]Custom log level in spring boot using log4j2

长话短说:我无法在 spring 引导中获得自定义级别。

不要求使用 log4j; 互联网基本上将我指向了这个方向。

我遇到的问题:

1 - 将 log4j2 添加到项目中

我已将 log4j2 starter 添加到 depdencencies:

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

...并从 spring-boot-starter-parent 中排除 logback,如所有教程中所述:

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

..然后我添加一个属性logging.config: userstream/src/main/resources/log4j2.xml指向我保存log4j2配置的位置。

2 配置 log4j2 (因为我不知道 - 复杂!)

我发现我开始很简单,因为我想要的只是一个名为“BUSINESS”的额外日志级别,用于记录不是 WARN 也不是 INFO 的事件:

<?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN">
        <CustomLevels>
            <CustomLevel name="BUSINESS" intLevel="850" />
        </CustomLevels>
    </Configuration>

...(现在请帮助我 -我需要在此处配置什么才能使其运行?

3 调用它(应该像这样工作,但现在不行!)

private static final Logger LOGGER = LogManager.getLogger(UserStreamApplication.class);
 ....
LOGGER.log(Level.forName("BUSINESS", 850), "mystreamFunction called by user"+ uid);

从几个小时以来一直在上下运行,每个配置看起来都不同,每个教程都有主观上不同的方法。 根本不想弄乱 fileappenders 和 logformats 等。 只想在我可以使用的 INFO 和 WARN 之间有一个级别。 吻!

我请各位老将 log4j 勇士和 spring-boot 超级巨星帮忙!

项目 1 看起来是正确的,除非您的日志配置将位于名为 log4j2.xml 的应用程序中,那么您不需要将 logging.config 添加到您的配置中。 如果这样做,则应使用类路径 url 引用它,如 logging.config 中所示:classpath:log4j2-myapp.xml。

对于第 2 项,您没有指定要登录的位置。 最简单的配置是

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <CustomLevels>
      <CustomLevel name="BUSINESS" intLevel="850" />
    </CustomLevels>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

您编码的日志记录看起来是正确的。 也就是说,“业务”对于一个级别来说是一个奇怪的名称,因为级别通常是针对事件的相对重要性。 业务听起来更像是一个可能适用于多个级别的标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM