2

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?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562

3 Answers3

4

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.

josh-cain
  • 4,997
  • 7
  • 35
  • 55
3

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.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
1

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

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
AlexR
  • 114,158
  • 16
  • 130
  • 208
  • Thanks! I haven't tried it yet, but I wanted to a. make sure I'm right before deploying, and b. have a verified answer published online. – Adam Matan Jul 30 '12 at 13:25