Tomcat: Filter log4j by logger name

南笙酒味 提交于 2019-12-13 02:46:20

问题


I am working with an external package which uses a log4j quite verbosely. I've looked at the code and found the expected log4j lines:

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:

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

I guessed thatcategory name property is equivalent to the logger name. Is it true? If not, how can I filter by logger name?


回答1:


You are right, logger == category. Do you have problems with your configuration? Generally it looks OK and should work.




回答2:


Actually, you can use <logger> as an element name, e.g.

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




回答3:


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

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



来源:https://stackoverflow.com/questions/11722440/tomcat-filter-log4j-by-logger-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!