每个线程null.log文件的log4net日志文件

时间:2016-01-31 23:20:43

标签: c# multithreading log4net

我已经在这里使用了其他帖子来实现这一目标。但我有一种刺激,我似乎无法解决。我需要一个记录器用于我的主进程,然后为我启动的每个线程提供一个单独的记录器。下面的测试示例运行良好,除了我得到main.log(按预期工作),还有一个创建的文件[null].log(空的)。 [null].log来自何处? (认为​​发布整个内容可能会提供另一个完整的工作示例,即每个线程日志'搜索时)。

<log4net>
  <logger name="ThreadLogger">
    <appender-ref ref="ThreadAppender"/>
    <level value="ALL"/>
  </logger>
    <logger name="MainLogger">
      <appender-ref ref="MainAppender"/>
      <level value="ALL"/>
  </logger>
  <appender name="ThreadAppender" type="log4net.Appender.FileAppender">
    <file type="log4net.Util.PatternString" value="c:\Temp\%property{LogName}.log" />
    <immediateFlush value="true"/>
    <appendToFile value="true" />
    <layout type="log4net.Layout.SimpleLayout" />
  </appender>
  <appender name="MainAppender" type="log4net.Appender.FileAppender">
    <file type="log4net.Util.PatternString" value="c:\Temp\main.log"/>
    <immediateFlush value="true"/>
    <appendToFile value="true" />
    <layout type="log4net.Layout.SimpleLayout" />
  </appender>
</log4net>

class Program
{
        private static ILog mainlogger = null; //log4net.LogManager.GetLogger("MainLogger");

        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            mainlogger = log4net.LogManager.GetLogger("MainLogger"); //(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            mainlogger.Debug("Main thread start");
            while (true)
            {
                mainlogger.Debug("main thread running");
                StartNewThread();
                System.Threading.Thread.Sleep(20000);
            }
        }

        private static int i = 0;
        public static void StartNewThread()
        {   
            Console.WriteLine("Stating new thread " + i.ToString());

            string logFileName = @"threadlog_" + i.ToString();

            ILoggerRepository loggerRepository = LogManager.CreateRepository(logFileName + "Repository");
            ThreadContext.Properties["LogName"] = logFileName;
            log4net.Config.XmlConfigurator.Configure(loggerRepository);
            ILog threadlogger = LogManager.GetLogger(logFileName + "Repository", "ThreadLogger");
            i++;
            Task t = Task.Factory.StartNew(() =>
            {
                ILog thdlog = threadlogger;
                while (true)
                {
                    int th = i;
                    Console.WriteLine("In new thread " + Task.CurrentId.ToString());
                    thdlog.Debug("DoWork is working in thread : " + Task.CurrentId.ToString());

                    System.Threading.Thread.Sleep(10000);
                }
            });
      }    
}

0 个答案:

没有答案