gok*_*ter 6 .net logging log4net multithreading
是的,这个问题类似于: How to log into separate files per thread with Log4Net? 除了直到运行时我不知道线程的数量或它们的名称。我的 Windows 应用程序为每个用户生成一个线程,为该用户执行长时间运行的工作。我想为每个用户/线程创建一个单独的日志文件。
log4net.Config.XmlConfigurator.Configure()?
(请详细说明如何实现日志记录。)
这是一个示例配置(我无法让 thread_name 属性与多个线程一起使用):
<log4net debug="false">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--need to replace LogDir in code like this: log4net.GlobalContext.Properties["LogDir"] = "c:\programdata\myapp"-->
<file type="log4net.Util.PatternString" value="%property{LogDir}\logs\mylogfile_%property{thread_name}.log" />
...
Run Code Online (Sandbox Code Playgroud)
和代码:
public class MyMultiThreadedClassForUsers
{
private log4net.ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Start()
{
log4net.GlobalContext.Properties("LogDir") = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
log4net.Config.XmlConfigurator.Configure()
List<IUser> users = GetAllUsersFromDB();
foreach (IUser user in users) {
System.Threading.Thread t = new System.Threading.Thread(CallBackMethod);
t.Name = user.FirstName;
t.Start();
}
}
private void CallBackMethod()
{
// this log message should be sent to a log file named after the current thread System.Threading.Thread.CurrentThread.Name
// Examples: mylogfile_bob.log, and mylogfile_fred.log, etc...
Log.Info("Starting work on thread " + System.Threading.Thread.CurrentThread.Name);
// do long running work here
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用 log4net 不容易做到这一点,我可以将日志记录框架切换到 Nlog 并使用它们的 %threadname 关键字作为存储在配置文件中的日志文件名的一部分。
请尝试这个:
http://geekswithblogs.net/rgupta/archive/2009/03/03/dynamic-log-filenames-with-log4net.aspx
如果您需要使用 log4net 生成动态日志文件名称,那么您可以使用以下配置
Run Code Online (Sandbox Code Playgroud)<appender name="RollingFileAppenderV1" type="log4net.Appender.RollingFileAppender"> <file type="log4net.Util.PatternString" value="F:\HornetFeed\%property{LogName}" /> <appendToFile value="true" /> <rollingStyle value="Size" /> ... <filter type="log4net.Filter.PropertyFilter"> <Key value="Version" /> <StringToMatch value="1" /> ... <= Note the "%property{LogName}" syntax
请注意 %property{LogName} 这是一个 log4net 属性,我们可以使用 C# 代码在运行时设置它。
Run Code Online (Sandbox Code Playgroud)log4net.GlobalContext.Properties["LogName"] = "file1.log";
请记住在实例化 log4net 记录器之前设置 GlobalContext 属性。即在此调用之前:
Run Code Online (Sandbox Code Playgroud)log4net.ILog log = LogManager.GetLogger(typeof(Program));
然后:
Run Code Online (Sandbox Code Playgroud)///Helper method to log errors: internal static void LogError(Exception ex) { string state = "1"; if (log4net.ThreadContext.Properties["Version"] != null) state = log4net.ThreadContext.Properties["Version"].ToString(); log4net.ThreadContext.Properties["Version"] = "0"; logger.HandleException(ex, "Error"); log4net.ThreadContext.Properties["Version"] = state; }
'希望有帮助
归档时间: |
|
查看次数: |
6584 次 |
最近记录: |