Search code examples
c#windows-servicesevent-logsystem.diagnostics

Can C# window service automatically log into custom eventsource/log


I have a C# window service where I am creating custom event source and log name in ProjectInstaller.Designer.cs file,

private void InitializeComponent()
    {
        this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
        this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
        // 
        // serviceProcessInstaller1
        // 
        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
        this.serviceProcessInstaller1.Password = null;
        this.serviceProcessInstaller1.Username = null;
        // 
        // serviceInstaller1
        // 
        this.serviceInstaller1.ServiceName = "DemoService";
        this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

        var eventLog1 = new System.Diagnostics.EventLog();
        if (!System.Diagnostics.EventLog.SourceExists("MySource"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";

        // 
        // ProjectInstaller
        // 
        this.Installers.AddRange(new System.Configuration.Install.Installer[] {
        this.serviceProcessInstaller1,
        this.serviceInstaller1});

    }

and When I'm installing the window service the log name appears under Applications and Service Logs,

enter image description here

Now, will it possible that all unhanded exception from the service will log under MyNewLog with source 'MySource`?

protected override void OnStart(string[] args)
    {
        throw new NotImplementedException();
    }

Currently it's logs under Application with source as 'Service1`


Solution

  • Well, Config EventLog in class constructor:

    void InitiateEventLog(EventLog eventLog)
    {
        if (!EventLog.SourceExists("MySource"))
        {
           EventLog.CreateEventSource("MySource", "MyNewLog");
        }
        eventLog.Source = "MySource";
        eventLog.Log = "MyNewLog";
    }
    

    Your constructor should be like:

    public Service1()
    {
        InitiateEventLog(EventLog);
        InitializeComponent();
    }
    

    Then, you can catch unhandled exceptions in OnStart method and then write CUSTOM Log:

        protected override void OnStart(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
    
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            EventLog.WriteEntry($"Unhundeled Exception occurred: {(e.ExceptionObject as Exception).Message}");
        }