Log 4J - Appender selection based on message priority

Discussions

General J2EE: Log 4J - Appender selection based on message priority

  1. Is it possible to select the appender depending on message priority?

    For eg :

    If I have 2 appenders defined for "MyClass" category say File and Console.

    Can I instruct log4j to send to send all "FATAL" priority messages originating from "MyClass" to File and all "ERROR" priority messages originating from "MyClass" to Console.

    Thanks in advance.

    -Chetan
  2. I don't think there is any existing Log4J functionality to do what you want, but:

        - you can write your own appender that splits the output

        - since Log4J comes with source, you can always modify it to choose an appender in the manner you describe

  3. Thank you very much for the input.

    Changed the shipped code and was able to get it working the way we want, but is this a normal practice? I mean to say that what if tomorrow they come out with a new version of log4Jin that case we will have to "remember" to apply the patch before we put log4J's jar file in production.

    Let me know what do you think.

    -Chetan





  4. I'd recommend using a custom appender which would delegate the messages to other standard / cutom appenders based on the priority, this would reduce the risk of you needing to patch code to support future versions of log4j in you'r system
  5. Does it mean that I should have only one appender(the custom appender) defined in log4j's configuration file and then code to attach different appenders to various categories to be in this custom appender? (That sounds like a very fat appender code)

    Let me know what do you think.

    -Chetan.
  6. I'd think not... you are simply moving the hack you just put in outside of the Log4J standard API.
  7. and I agree, this code should be in an Appender. As long as the Appender interface doesn't change, your code will be safe from dependencies on changes in the Log4J main code.
  8. Yes it is possible. The key is to use filters on the appenders. It is only supported in the XML config file.
    Here is an example of a console appender that only prints debug priorities (other examples can be found in the log4j download):

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
                <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern"
    value="%d{dd.MM.yyyy HH:mm:ss} [%t] %-5p %c - %m%n"/>
                </layout>
    <filter class="org.apache.log4j.varia.PriorityMatchFilter">
                      <param name="PriorityToMatch" value="debug" />
                      <param name="AcceptOnMatch" value="true" />
    </filter>
    </appender>