0

I'm developing a Windows Service, C#, 4.7 .NET Framework and log4net.

I want to log unhandled exceptions but it seems that log4net doesn't work in 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());
        }
    }
}

I have modified MyService class to throw an exception on OnStart method, but I don't get any log in log file and I can't debug a Windows Service app to see if CurrentDomain_UnhandledException is called.

Do you know how can I log unhandled exceptions?

VansFannel
  • 45,055
  • 107
  • 359
  • 626

1 Answers1

-2

I'm currently working on a similar project. Windows Service with log4net, that needs to log unhandled exceptions. First thing I noticed is, that no configfile is set. If that is not on purpose you should add a line like this above the namespace:

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

Second thing I did different is not using the UnhandledException event handler but enclose my Main() logic in a 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);
            }
        }
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55