简体   繁体   English

Tomcat:按记录器名称过滤log4j

[英]Tomcat: Filter log4j by logger name

I am working with an external package which uses a log4j quite verbosely. 我正在使用一个非常冗长地使用log4j的外部软件包。 I've looked at the code and found the expected log4j lines: 我查看了代码,发现了预期的log4j行:

private Logger log = Logger.getLogger("SomeLoggerName");
...
log.info("Trivial message");
log.info("More trivial data");

Since I can't change the code, I've tried to change log4j.xml : 由于我无法更改代码,因此我尝试更改log4j.xml

<category name="SomeLoggerName">
  <level value="${log4j_level:-WARN}"/>
  <appender-ref ref="FileLogger"/>
</category>

I guessed that category name property is equivalent to the logger name. 我猜想category name属性等于记录器名称。 Is it true? 是真的吗 If not, how can I filter by logger name? 如果没有,如何按记录器名称过滤?

Actually, you can use <logger> as an element name, eg 实际上,您可以使用<logger>作为元素名称,例如

<logger name="SomeLoggerName">
  <level value="${log4j_level:-WARN}"/>
  <appender-ref ref="FileLogger"/>
</logger>

I think category is there for backward compatibility and its use is deprecated. 我认为category是为了向后兼容,并且不赞成使用它。

If you're just looking to turn down verbosity, I'd just turn up the priority level: 如果您只是想降低冗长程度,请提高优先级:

<category name="SomeLoggerName">
  <level value="WARN"/>
</category>

Otherwise, you might want to add a filter to your existing appender. 否则,您可能想要向现有的附加程序添加过滤器 First, implement a log4j filter. 首先,实现一个log4j过滤器。 In your case it would be a simple comparison to determine whether or not the log event was from the unwanted class. 在您的情况下,确定日志事件是否来自不需要的类将是一个简单的比较。 Something like this would work: 这样的事情会起作用:

public class MyAuditFilter extends Filter{

    @Override
    public int decide(LoggingEvent event) {
        if(event.getClass.getCanonicalName().equalsIgnoreCase("class.you.don't.want"))
            return Filter.DENY;
        else
            return Filter.ACCPET;
    }
}

Once you have your filter implemented, just add it to your log4j appender like so: 一旦实现了过滤器,就可以将其添加到log4j追加器中,如下所示:

<appender name="myAppender" class="my.appender.class">
  .
  .
  <filter class="my.namespace.MyAuditFilter">
    <param name="AcceptOnMatch" value="True"/>
  </filter>
  .
  .
</appender>

If you need more control, the filter will be able to give you extremely fine-grained control over your logging. 如果您需要更多控制,则过滤器将能够为您提供对日志记录的极细粒度控制。

You are right, logger == category. 您是对的,logger ==类别。 Do you have problems with your configuration? 您的配置有问题吗? Generally it looks OK and should work. 通常看起来不错,应该可以工作。

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

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