Yes this question is similar to: How to log into separate files per thread with Log4Net? except I don't know the number of threads or their names until runtime. My windows app spawns a thread per user to do long running work for that user. I want a separate log file for every user/thread.
- What would the log4net config file look like (if one can be used for this type of thing)?
- What would the code look like to use the logger?
- When would I call
log4net.Config.XmlConfigurator.Configure()?
(Please give details on how to implement the logging.)
Here's a sample config (I can't get the thread_name property to work with multiple threads):
<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" />
...
And the code:
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
}
}
If this is not easily done with log4net I may switch logging frameworks to Nlog and use their %threadname keyword as part of the log file name which is stored in the config file.