Tuesday, June 19, 2012

Log4Net Logging

Isn't it interesting that by far the most popular .NET logging library is one "owned" now by Apache?  And which had its beginning in Java?

Here is an excellent page to quickly get you up and started with Log4Net:
http://www.justinrhinesmith.com/blog/2008/05/12/quick-and-easy-log4net-setup/
(thank you Justin)

And here is the answer to the question which usually follows:
Note: In log4net speak, an output destination is called an appender.
More than one appender can be attached to a logger.

Is it possible to direct log output to different appenders by level?

Yes it is. Setting the Threshold option of any appender will filter out all log events with a lower level than the value of the threshold option.

For example, setting the threshold of an appender to DEBUG will also allow INFO, WARN, ERROR and FATAL messages to log along with DEBUG messages. (DEBUG is the lowest level). Similarly, setting the threshold of an appender to ERROR will filter out DEBUG, INFO and WARN messages but not ERROR or FATAL messages.  See Example 1.

If you must filter events by exact level match, then you can attach a Filter, such as a  LevelMatchFilter, to any appender to filter out logging events by exact level match. See Example 2.

For more on the matter of Threshod vs. Filter vs. Evaluators, see further below.


Example 1:



<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <threshold value="INFO" />
        .....other elements specific to FileAppender.....
    </appender>
    <appender name="" type="log4net.Appender.SmtpAppender">
        <threshold value="ERROR" />
          .....other elements specific to  SmtpAppender .....
    </appender>
</log4net>


Example 2:


<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
         <filter type="log4net.Filter.LevelMatchFilter">
              <acceptOnMatch value="true" />
              <levelToMatch value="INFO" />
         </filter>
        .....other elements specific to FileAppender.....
    </appender>
    <appender name="" type="log4net.Appender.SmtpAppender">
         <filter type="log4net.Filter.LevelMatchFilter">
              <acceptOnMatch value="true" />
              <levelToMatch value="ERROR" />
         </filter>
          .....other elements specific to  SmtpAppender .....
    </appender>
</log4net>

Threshold vs. Filter vs. Evaluator

Threshold is the simplest, Filter gives you more flexibility, and Evaluator is only available with certain appenders, such as the one for sending emails. For more see:
Threshold vs. Filter vs. Evaluator


Finally...


What to actually write to the log? see:
http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html



For more on Log4Net, be sure to check out:

and of course:

No comments: