使用布局时如何防止 logback 在每个日志的开头输出自己的状态

发布于 2024-09-10 16:13:34 字数 2286 浏览 6 评论 0原文

这看起来像是一个粗心错误,但我似乎找不到原因。使用 logback/slf4j 进行日志记录(最新版本 slf4j-api-1.6.1、logback core/classic 0.9.24)。用于测试的最简单的日志配置是:

<configuration>
 <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
  <layout class="ch.qos.logback.classic.PatternLayout">
   <!-- DONT USE THIS FORMATTER FOR LIVE LOGGING THE %L LINE NUMBER OUTPUTTER IS SLOW -->
   <pattern>%le %-1r [%c{1}:%L] %m%n</pattern>
  </layout>
 </appender>
 <root level="DEBUG">
  <appender-ref ref="stdout" />
 </root>
</configuration>

每个日志设置都以 logback 的内部状态行开始:

11:21:27,825 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
11:21:27,826 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml] at [file:.../logback-test.xml]
11:21:28,116 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
11:21:28,124 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
11:21:28,129 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [stdout]
11:21:28,180 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Pushing component [layout] on top of the object stack.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - This appender no longer admits a layout as a sub-component, set an encoder instead.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - To ensure compatibility, wrapping your layout in LayoutWrappingEncoder.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - See also http://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details
11:21:28,207 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
11:21:28,207 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [stdout] to Logger[ROOT]

根据文档,这是 logback 默认使用的格式。然后它完成读取配置(设置为输出不同的格式)并继续正确格式化的输出。有一个配置参数 不会影响此操作。

有谁知道如何关闭这个功能吗?

This seems like a carelessness error, but I can't seem to find the cause. Logging with logback/slf4j (most recent version slf4j-api-1.6.1, logback core/classic 0.9.24). Simplest log configuration for testing is:

<configuration>
 <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
  <layout class="ch.qos.logback.classic.PatternLayout">
   <!-- DONT USE THIS FORMATTER FOR LIVE LOGGING THE %L LINE NUMBER OUTPUTTER IS SLOW -->
   <pattern>%le %-1r [%c{1}:%L] %m%n</pattern>
  </layout>
 </appender>
 <root level="DEBUG">
  <appender-ref ref="stdout" />
 </root>
</configuration>

Every log setup starts with logback's internal status lines:

11:21:27,825 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
11:21:27,826 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml] at [file:.../logback-test.xml]
11:21:28,116 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
11:21:28,124 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
11:21:28,129 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [stdout]
11:21:28,180 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Pushing component [layout] on top of the object stack.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - This appender no longer admits a layout as a sub-component, set an encoder instead.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - To ensure compatibility, wrapping your layout in LayoutWrappingEncoder.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - See also http://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details
11:21:28,207 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
11:21:28,207 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [stdout] to Logger[ROOT]

which is, according to the docs, the format logback uses for default. It then finishes reading the config (which is set up to output a different format) and continues with the properly formatted output. There's a config parameter <configuration debug="false"> which does not affect this.

Anyone know how to shut this off?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

多像笑话 2024-09-17 16:13:34

如果将 configuration 元素的 debug 属性设置为 true,您将在控制台获取所有状态信息。如果这是您的问题,只需将其设置为 false 或将其删除即可。

如果您遇到任何 WARN 或更高级别的配置问题,您还将获得记录到控制台的所有状态信息(包括 INFO 级别的消息)。此问题的最佳解决方案是修复该问题(在您的情况下,将 元素替换为 元素)。

如果您由于某种原因无法解决问题,但想要从控制台中删除状态信息,则可以配置替代的 StatusListener。使用 NopStatusListener 完全删除状态信息:

<configuration>
  <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
  <!-- etc -->
</configuration>

If you set the debug attribute of the configuration element to true, you will get all status information to the console. If this is your problem, just set it to false or remove it.

If you have any configuration problems of level WARN or above, you will also get all status information logged to the console (including messages of level INFO). The best solution to this problem is to fix the problem (in your case replace the <layout> element with an <encoder> element).

If you for some reason cannot fix the problem, but want to remove the status-information from the console, you can instead configure an alternative StatusListener. Use the NopStatusListener to completely remove the status-information:

<configuration>
  <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
  <!-- etc -->
</configuration>
知足的幸福 2024-09-17 16:13:34

文档中所述,如果在解析配置期间出现警告或错误文件中,logback会自动在控制台打印状态数据。

遵循 http://logback.qos.ch/codes.html#layoutInsteadOfEncoder
logback 在其警告消息中提到的链接。一旦您按照其中提到的步骤操作,也就是说,如果您将替换为带有的元素,logback 将停止在控制台上打印消息。

As described in the docs, if warnings or errors occur during the parsing of the configuration file, logback will automatically print status data on the console.

Follow http://logback.qos.ch/codes.html#layoutInsteadOfEncoder i.e.
the link mentioned by logback in its warning message. Once you follow the steps mentioned therein, that is, if you replace <layout> element with <encoder>, logback will stop printing messages on the console.

不再让梦枯萎 2024-09-17 16:13:34

我遇到了同样的问题,我

        <!-- Stop output INFO at start -->
        <statusListener class="ch.qos.logback.core.status.NopStatusListener" />

在 logback 中添加了这一行,并且成功运行

I had the same problem i added this line

        <!-- Stop output INFO at start -->
        <statusListener class="ch.qos.logback.core.status.NopStatusListener" />

in the logback and it succefully worked

多像笑话 2024-09-17 16:13:34

我更喜欢使用状态侦听器来关闭自己的 logback 日志:

<configuration>
  <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
  ...
</configuration>

但是正如前面提到的 NopStatusListener 也可以防止显示警告和错误。因此,您可以编写自定义状态侦听器并手动更改其日志级别:

package com.your.package;

import ch.qos.logback.core.status.OnConsoleStatusListener;
import ch.qos.logback.core.status.Status;

import java.util.List;

public class PrintOnlyWarningLogbackStatusListener extends OnConsoleStatusListener {

    private static final int LOG_LEVEL = Status.WARN;

    @Override
    public void addStatusEvent(Status status) {
        if (status.getLevel() == LOG_LEVEL) {
            super.addStatusEvent(status);
        }
    }

    @Override
    public void start() {
        final List<Status> statuses = context.getStatusManager().getCopyOfStatusList();
        for (Status status : statuses) {
            if (status.getLevel() == LOG_LEVEL) {
                super.start();
            }
        }
    }

}    

然后在 logback.xml 文件中使用它:

<configuration>
  <statusListener class="com.your.package.PrintOnlyWarningLogbackStatusListener" />
  ...
</configuration>

I prefer to use status listener in order to switch off own logback logs:

<configuration>
  <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
  ...
</configuration>

But as was mentioned NopStatusListener also prevents showing warning and errors. So you can write your custom status listener and change log level for it manually:

package com.your.package;

import ch.qos.logback.core.status.OnConsoleStatusListener;
import ch.qos.logback.core.status.Status;

import java.util.List;

public class PrintOnlyWarningLogbackStatusListener extends OnConsoleStatusListener {

    private static final int LOG_LEVEL = Status.WARN;

    @Override
    public void addStatusEvent(Status status) {
        if (status.getLevel() == LOG_LEVEL) {
            super.addStatusEvent(status);
        }
    }

    @Override
    public void start() {
        final List<Status> statuses = context.getStatusManager().getCopyOfStatusList();
        for (Status status : statuses) {
            if (status.getLevel() == LOG_LEVEL) {
                super.start();
            }
        }
    }

}    

Then use it in your logback.xml file:

<configuration>
  <statusListener class="com.your.package.PrintOnlyWarningLogbackStatusListener" />
  ...
</configuration>
南风几经秋 2024-09-17 16:13:34

Ceki 答案是正确的:

(...)如果在解析配置文件的过程中出现警告或者错误,logback会自动在控制台打印状态数据。

一旦你做对了,日志的第一行就不会再有任何污染了。

自 2015 年 3 月起,在 Logback 1.1.2 中,您需要使用 子组件 - 现在是 已弃用,如果使用它,将会出现错误消息。您无法控制它,这是Logback默认行为。

一些内部类也被重命名,甚至其手册页中的示例也已过时!

这是来自他们的错误代码帮助页面的代码片段,其中包含配置记录器的正确方法。这完全解决了我的项目中的问题。
http://logback.qos.ch/codes.html#layoutInsteadOfEncoder

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
  <file>testFile.log</file>
  ...
  <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    <pattern>%msg%n</pattern>
  </encoder>
</appender>

Ceki answer is correct:

(...)if warnings or errors occur during the parsing of the configuration file, logback will automatically print status data on the console.

Once you get it right, there won't be any pollution in the first lines of your log anymore.

As of March 2015, in Logback 1.1.2, you need to use <encoder> sub-component - <layout> is now deprecated and if use it, error messages will appear. You cannot control this, it´s Logback default behavior.

Some internal classes have been renamed too, and even the examples in their manual page are outdated!

Here is the code snippet from their Errors Code Help page, which has the correct way to config the logger. This fixed the issue completely in my project.
http://logback.qos.ch/codes.html#layoutInsteadOfEncoder

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
  <file>testFile.log</file>
  ...
  <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    <pattern>%msg%n</pattern>
  </encoder>
</appender>
许仙没带伞 2024-09-17 16:13:34

我意识到史蒂夫找到了修复程序,但他没有在帖子中提及。如果其他人遇到同样的问题,这里就是解决方法。

""元素替换为 ".."

罪魁祸首是:

I realized Steve found the fix but he didn't mention it on the thread. In case if any other person hit the same issue here is the fix.

Replace "<layout>" elements with "<encoder>..</encoder>"

The culprit is:
<layout class="ch.qos.logback.classic.PatternLayout">

中性美 2024-09-17 16:13:34

我自己也遇到了同样的问题,即在开头记录了一堆与我的代码无关的行。这是我修复它的方法。

<configuration debug="false">

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level 
        %logger{36} - %msg%n</pattern> </encoder> -->
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} %-5level %logger{10} - %msg%n</pattern>
    </encoder>
</appender>

<root level="error">
    <appender-ref ref="STDOUT" />
</root>

<logger name="fun.n.games" level="DEBUG" />

这是通过 pom.xml 中的以下条目运行的

        <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

Struggled with the same problem myself i.e. there were a bunch of lines logged right at the beginning which were not related to my code. Here is how I fixed it.

<configuration debug="false">

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level 
        %logger{36} - %msg%n</pattern> </encoder> -->
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} %-5level %logger{10} - %msg%n</pattern>
    </encoder>
</appender>

<root level="error">
    <appender-ref ref="STDOUT" />
</root>

<logger name="fun.n.games" level="DEBUG" />

This is running with the following entry in the pom.xml

        <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
缱绻入梦 2024-09-17 16:13:34

这似乎在 0.9.29 中已修复。刚刚做了几次测试。不再有乔兰信息了。我猜是修复提交。

This seems to be Fixed in 0.9.29. Just made several tests. No Joran INFO anymore. I guess this is the fixing commit.

落叶缤纷 2024-09-17 16:13:34

我已经尝试了一切,但没有一个对我有用。我的问题是由于我的类路径中存在多个 logback.xml 文件。这是多模块化项目中的常见情况。
当classpath中只有一个logback.xml文件时,没有歧义,问题就解决了。

I've tried everything and nothing worked for me. My problem was due to multiple logback.xml files in my classpath. This is the common case in multi modular projects.
When there is only one logback.xml file in classpath, there is no ambiguity and the problem is solved.

青春如此纠结 2024-09-17 16:13:34

使用logback.groovystatusListener(NopStatusListener)(在src/test/resources/logback.groovy )有效。

(一个有效的用例是,例如,如果在 Eclipse 中使用 ANT,使用 logback 日志记录、groovy 类和单元测试,其中单元测试采用 src/test/resources/logback.groovy,但也会看到您无法排除的 src/main/resources/logback.groovy (或类似的)(如果据说 ANT 的类路径使用项目类路径)。

Using the logback.groovy: statusListener(NopStatusListener) (in the src/test/resources/logback.groovy) works.

(A valid use case is e.g. if working with ANT in Eclipse, using logback logging, groovy classes and unit tests where the unit tests take the src/test/resources/logback.groovy, but will also see the src/main/resources/logback.groovy (or similar) you cannot exclude (if ANT's classpath is said to use the projects classpath).)

無處可尋 2024-09-17 16:13:34

仅适用于由于 ch.qos.logback.access.tomcat.LogbackValve#LogbackValve(最新版本)记录的状态消息而登陆此处的人。只需设置 quiet 标志:

var v = new LogbackValve();
v.setQuiet(true); // disable status messages!
v.setFilename("logback-access.xml");

另请参阅文档 XML 配置。

Just for people landing here because of the status messages logged by ch.qos.logback.access.tomcat.LogbackValve#LogbackValve (recent versions). Just set the quiet flag:

var v = new LogbackValve();
v.setQuiet(true); // disable status messages!
v.setFilename("logback-access.xml");

See also the documentation for XML configuration.

别理我 2024-09-17 16:13:34

如果您需要日志文件而不是控制台,您可以通过在 logback.xml 中添加 statusListener 来重定向它:

<configuration>
  <statusListener class="ch.qos.logback.core.status.OnFileStatusListener" />
  ...
</configuration>

它将在工作目录的根目录中添加包含日志的“status.txt”文件。

您可以创建自己的侦听器,它将日志写入您喜欢的目的地:

public class OnLogsDirFileStatusListener extends OnFileStatusListener {

    private static final String DIR = "logs";

    public OnLogsDirFileStatusListener() {
        try {
            Files.createDirectories(Paths.get(DIR));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        setFilename(Path.of(DIR, "status.log").toString());
    }
}

然后在 logback.xml 中指定它:

<configuration>
  <statusListener class="path.to.your.listener.OnLogsDirFileStatusListener" />
  ...
</configuration>

In case you need logs in file instead of console you can redirect it by adding statusListener in logback.xml:

<configuration>
  <statusListener class="ch.qos.logback.core.status.OnFileStatusListener" />
  ...
</configuration>

It will add "status.txt" file with logs in root of your working directory.

You can create your own listener which will write logs to the destination you like:

public class OnLogsDirFileStatusListener extends OnFileStatusListener {

    private static final String DIR = "logs";

    public OnLogsDirFileStatusListener() {
        try {
            Files.createDirectories(Paths.get(DIR));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        setFilename(Path.of(DIR, "status.log").toString());
    }
}

and then specify it in your logback.xml:

<configuration>
  <statusListener class="path.to.your.listener.OnLogsDirFileStatusListener" />
  ...
</configuration>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文