0
votes

log4net v. 2.0.8

I've got some problems in multiple logging with log4net. I'm developing an application that works with n devices and I would like to have a single log file for each device.

log4net.config

<log4net>

<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="%envFolderPath{LocalApplicationData}/Foo/Device%property{DeviceID}/log.txt"/>
  <appendToFile value="true"/>
  <maxSizeRollBackups value="10"/>
  <maximumFileSize value="10MB"/>
  <layout type="log4net.Layout.PatternLayout">
    <param name="Header" value="BEGIN LOGGING AT %date *** %property *** %newline" type="log4net.Util.PatternString" />
    <param name="Footer" value="END LOGGING AT %date *** %property *** %newline" type="log4net.Util.PatternString" />
    <param name="ConversionPattern" value="%date [%thread] %-5level %-5class{1}  %-5method(%line) %message %newline" />
  </layout>
  <filter type="log4net.Filter.PropertyFilter">
     <key value="Version" />
     <stringToMatch value="1" />
  </filter>
</appender>

<root>
  <level value="ALL" />
  <appender-ref ref="LogFileAppender" />
</root>

and this is the code

  public DeviceClass(string deviceID)
    {
        InitializeComponent();

        GlobalContext.Properties["DeviceID"] = deviceID;
        logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        logger.Debug("Hello world");

The problem is that if I have for example two devices I got just the first log file with the messages from all devices.

1

1 Answers

0
votes

I'm not a Log4Net expert, but I believe that the log manager is going to initialize the logger and all of its appenders the first time that you call GetLogger for the given type/name (type under covers is translated to a string name). That being the case, it wouldn't re-initialize one per device. My suggestion for you is to try creating a composite of the type name and device ID using something like:

logger = LogManager.GetLogger($"{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}{deviceId}");