简体   繁体   English

Log4Net C#-具有动态文件名的附加程序的多线程日志记录问题

[英]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. 我有一个应用程序,对于每个用户,都有一个不同的日志文件,每个用户的日志文件的名称由用户的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: 在C#函数中:

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). 问题是当两个或多个用户同时登录时,每次写入日志时都会调用该函数,设置了用户的ID,并通过新日志文件的名称(用户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: 如果有两个用户(一个ID为1234,第二个ID为5678)并且他们都同时登录,则会创建两个日志文件:

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). 但是当查看日志文件内部时,似乎用户不仅将日志写入他们的文件(例如,ID为1234的用户有时会写入5678.log文件)。

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. 您可能要签出additivity属性的配置。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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