views:

99

answers:

2

How can I achieve the following using log4j:

  • log only events coming from a specific category , i.e. com.example.app but not com.example.app.context or com.example.dao;
  • log all events with a level of WARN or higher.
+2  A: 

You need to set up the catergory filters in order with the appender threshold set to the higer filter limit.

   <appender name="LOG_FILE" class="org.apache.log4j.FileAppender">
      <param name="File" value="log_file.log" />
      <param name="Threshold" value="WARN"/>

      <layout class="org.apache.log4j.PatternLayout">
         <!-- The default pattern: Date Priority [Category] Message\n -->
         <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
      </layout>
   </appender>

   <category name="com.example.app">
         <priority value="DEBUG" />
         <appender-ref ref="LOG_FILE" />
   </category>

   <category name="com.example.app.context">
         <priority value="WARN" />
         <appender-ref ref="LOG_FILE" />
    </category>
Antz
I think to get the behavior the poster requested, you will set com.example.app to WARN and com.example.app.context to OFF. I don't think there is a way to turn com.example.app on and every com.example.app.* off, except by repeating each subpackage explicitly.
Keith Randall
To turn sub packages off (to a lower level than the parent, you also have to set additive to false).
Yishai
Thanks for your answer. However, I this way I would lose the < `WARN` logging from the `com.example.app.context` file, which I want to see.
Robert Munteanu
+2  A: 

In your log4j.properties file you can set the global log level for your app on the rootLogger:

log4j.rootLogger=DEBUG, APPENDER

You can use WARN, INFO, ERROR and FATAL instead of DEBUG.

A package with subpackages can be given its own log level like so:

log4j.logger.com.example.app=DEBUG

to remove logging from its sub-packages, set their loglevel to error or fatal:

#log4j.logger.com.example.app.context=ERROR
log4j.logger.com.example.app.dao=ERROR

Edit: commented out the app.context line so that it inherits the DEBUG level from its parent package.

rsp
Thanks for your answer. However, I this way I would lose the < `ERROR` logging from the `com.example.app.context` file, which I want to see
Robert Munteanu
If you want the `app.context` to inherit the loglevel from `app` just do not put a line with a new loglevel for `app.context` in your properties file. Could you edit your question and elaborate a bit on what you want exactly?
rsp