【问题标题】:Log unhandled exceptions in a Windows Service using log4net使用 log4net 在 Windows 服务中记录未处理的异常
【发布时间】:2017-06-20 06:40:10
【问题描述】:

我正在开发 Windows 服务、C#、4.7 .NET Framework 和 log4net。

我想记录未处理的异常,但似乎 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

您知道如何记录未处理的异常吗?

【问题讨论】:

标签: c# windows-services log4net


【解决方案1】:

我目前正在从事一个类似的项目。带有 log4net 的 Windows 服务,需要记录未处理的异常。我注意到的第一件事是,没有设置配置文件。如果这不是故意的,您应该在命名空间上方添加这样的一行:

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

我做的第二件事不同的是不使用UnhandledException 事件处理程序,而是将我的Main() 逻辑包含在try catch 中:

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);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2018-11-02
    • 2013-09-05
    • 2013-12-15
    相关资源
    最近更新 更多