Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to AND log4net filters together

I would like to create an appender that logs only for a particular level AND only for a particular logger. From what I'm seeing, and based on this tutorial, the filters are ORed together. How can I AND the log4net filters together? Here's an example of what I'm doing:

<appender name="MyAppender">
      <!--log only INFO level-->
      <filter type="log4net.Filter.LevelMatchFilter">
          <levelToMatch value="INFO" />
      </filter>

      <!--log only UserController logger-->
      <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="MyLogger" />
      </filter>

      <!-- do not log anything else -->
      <filter type="log4net.Filter.DenyAllFilter" />
</appender>
like image 941
Alex Avatar asked Dec 27 '11 23:12

Alex


People also ask

What are log4net Appenders?

For log4net to know where to store your log messages, you add one or more appenders to your configuration. An appender is a C# class that can transform a log message, including its properties, and persist it somewhere. Examples of appenders are the console, a file, a database, an API call, elmah.io, etc.

How do I add a console to log4net?

Add log4net. Set Copy to Output Directory to Copy Always. This is important because we need the log4net. config file to be copied to the bin folder when you build and run your app. To get you started quickly, copy this log4net config and put it in your new log4net.

Does log4net support structured logging?

log4net doesn't support the concept of structured logging. Like shown in the conversionPattern element in the XML configuration, you have some variables to play with when writing to the storage. But including properties like FirstName in the Serilog example isn't available.

Where do I put log4net in web config?

Now, add the section "<log4net></log4net>" after the <configSections/> element in your app. config file. Next, inside the "<log4net></log4net>" section, place the configuration details as shown in the code snippet given below. That's all you need to do to configure log4net.


1 Answers

You can write a custom AndFilter, which is fairly easy. You can use the code posted here - https://stackoverflow.com/a/8859037/984438

Usage will be like:

<filter type="Namespace.AndFilter, Assembly">
      <!--log only INFO level-->
      <filter type="log4net.Filter.LevelMatchFilter">
          <levelToMatch value="INFO" />
      </filter>

      <!--log only UserController logger-->
      <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="MyLogger" />
      </filter>
      <acceptOnMatch value="true"/>
</filter>
<!-- do not log anything else -->
<filter type="log4net.Filter.DenyAllFilter" />
like image 168
Narayan Akhade Avatar answered Oct 01 '22 14:10

Narayan Akhade