使用log4net在Windows服务中记录未处理的异常

问题描述:

我正在开发Windows服务,C#,4.7 .NET Framework和log4net。使用log4net在Windows服务中记录未处理的异常

我想记录未处理的异常,但似乎log4net在Program.cs中不起作用。

using System; 
using System.ServiceProcess; 

namespace MyWindowsService 
{ 
    static class Program 
    { 
     private static readonly log4net.ILog log = 
      log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     static void Main() 
     { 
      AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; 

      log4net.Config.XmlConfigurator.Configure(); 

      ServiceBase[] ServicesToRun; 
      ServicesToRun = new ServiceBase[] 
      { 
       new MyService() 
      }; 
      ServiceBase.Run(ServicesToRun); 
     } 

     private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
     { 
      log.ErrorFormat("UnhandledException: {0}", e.ToString()); 
     } 
    } 
} 

我已经修改MyService类扔在OnStart方法例外,但我没有得到任何日志中的日志文件,我不能调试Windows服务的应用程序,以查看是否CurrentDomain_UnhandledException被调用。

你知道我该如何记录未处理的异常吗?

+0

这是[answer](https://*.com/a/5117790)有帮助吗? – kennyzx

我目前正在研究一个类似的项目。带有log4net的Windows服务,需要记录未处理的异常。我首先注意到的是,没有设置configfile。如果这是不是故意的,你应该添加一行这样的命名空间上面:

static void Main() 
     { 
      try 
      { 
       log4net.Config.XmlConfigurator.Configure(); 

       ServiceBase[] ServicesToRun; 
       ServicesToRun = new ServiceBase[] 
       { 
        new MyService() 
       }; 
       ServiceBase.Run(ServicesToRun); 
      } 
      catch(Exception ex) 
      { 
       log.Fatal("Unhandled", ex); 
      } 
     } 

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] 

我做不同的是没有使用UnhandledException事件处理程序,但围在尝试捕捉我Main()逻辑第二件事