Search code examples
c#log4netlog4net-configurationlog4net-appender

Log4net multiple appenders different log levels


I think I am not configuring (or understanding) something properly. I have a two Appenders that I want to log the same entries but at different log levels. I have created a helper method for my logging.

public class LogHelper
{
    public static ILog GetLogger([CallerFilePath]string filename = "")
    {
        return LogManager.GetLogger(filename);
    }
}

then, in my classes, I call

private ILog log = LogHelper.GetLogger();

Here is my app.config:

  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="%property{StoragePath}\logs\" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="MMddyyyy'.log'" />
    <staticLogFileName value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{dd/MM/yyyy HH:mm:ss} %level - %message%newline%exception" />
    </layout>
  </appender>
  <appender name="WebApiAppender" type="<footype>">
    <threshold value="USERPLAY"/>
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="USERPLAY" />
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%m %property{Stream}" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingFileAppender" />
    <appender-ref ref="WebApiAppender" />
  </root>

The logging all works, but my threshold on my WebApiAppender is not being honored. It is defaulting to the Root level. This generated far more info that I want hitting my webapi. any help is greatly appreciated.

EDIT:

Also note that I use some custom log levels. Thus the 'USERPLAY' in the threshold

Custom Log Levels:

static readonly Level ReconnectLevel = new Level(65000, "RECONNECT");
static readonly Level UserPlayLevel = new Level(45001, "USERPLAY");
static readonly Level ScheduledPlayLevel = new Level(45002, "SCHEDULEDPLAY");
static readonly Level UserStopLevel = new Level(45003, "USERSTOP");
static readonly Level ScheduledStopLevel = new Level(45004, "SCHEDULEDSTOP");
static readonly Level LocalBreakLevel = new Level(47000, "LOCALBREAK");
static readonly Level StationIdLevel = new Level(47001, "STATIONID");
static readonly Level GameEndLevel = new Level(47002, "GAMEEND");
static readonly Level WebApiLevel = new Level(35000, "WEBAPI");

Solution

  • Have you added your custom level into the config file? Log4net needs to know where your custom level is compared to the predefined ones it already knows about.

    <level>
       <name value="USERPLAY" />
       <value value="35000" />
    </level>