简体   繁体   中英

Log4Net C# - Multithread logging issue with an appender with a dynamic file name

I have an application that for each user, there is a different log file, and the name of each user's log file is set by the user's ID. I have an appender that its name is dynamic by a thread context property:

config file:

<appender name="WebClient" type="log4net.Appender.RollingFileAppender">
    <File type="log4net.Util.PatternString" value="C:\\Log\\%property{UserID}.log"/>
    <param name="AppendToFile" value="true" />
    <param name="RollingStyle" value="Size" />
    <param name="MaximumFileSize" value="2500KB" />
    <param name="MaxSizeRollBackups" value="50" />

    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{ClientLogDate} [%4t] %5p %m %n" />
    </layout>

    <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="WebClient" />
        <acceptOnMatch value="true" />
    </filter>
</appender>

In the C# function:

ThreadContext.Properties["ClientLogDate"] = DateTime.Now;
ThreadContext.Properties["UserID"] = p_strUserID;
XmlConfigurator.Configure();
ILog Logger = LogManager.GetLogger(WebClientLogger");
Logger.Error(p_strMessage);

The problem is when two or more users are logging at the same time, the function is called each time for each log writing, The user's ID is set, the appender is configured by the new log file's name (Of the user's ID). If there are two users (one with ID of 1234 and the second one with ID of 5678) and they both log at the same time, there are two log files created:

1234.log
5678.log

but when looking inside of the log files, it seems that the users doesn't write logs only to their files (for instance, user with ID of 1234 sometimes writes to the 5678.log file).

I need a solution when for each thread (each user have its own thread) the logging will be to the file of the user, and not for other files (maybe its because there are multi threads and one thread is configuring before the other thread writes the log). If it possible i need a solution with no lockings.

Thanks!!!

You might want to check out the configuration of the additivity attribute.

<logger name="YourLoggerName" additivity="false">
  <level value="ALL" />
  <appender-ref ref="YourAppenderName" />
</logger>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM