How to log Windows Service custom logs in C#

In this article, learn how to log windows service custom logs in C# using EventLog class of System.Diagnostics namespace. By default, all the windows services applications can interact with the Application event log and write all the relevant log details, including exceptions.


How to log Windows Service custom logs in C#?

In the previous article you have seen how to log the custom event logs. In this article, you will learn how to log custom event logs for any windows service applications.

When you create a windows service project, logging is turned ON by the windows service project template by default. Hence, any windows service you will create can automatically log event messages such as information, warning, and errors into the Application event log.

However, you may also want to create custom event logs to log the internal exceptions raised from your windows service applications. So, if you’re going to develop and write your custom event log other than the Application log, you must set the AutoLog property to false. Here is an example of a Windows Service code that is self-explanatory.

.
/// 
/// Constructor.
/// Initialize the EventLog instance in the constructor.
/// 
public Service1()
{
    // Disable the default application event log.
    this.AutoLog = false;

    // Create an event storuce by specifying the name of the log.
    // Check to Make sure that it is not currently exist.
    if (!EventLog.SourceExists("MySourceName"))
    {
        // Create event source.
        EventLog.CreateEventSource("MySourceName", "MyLog");
    }

    // Configure the event log instalce.
    eventLog.Source = "MySourceName";
    eventLog.Log = "MyLog";

    InitializeComponent();
}

Now, call the EventLog.WriteEntry() function to log the custom event log.

/// 
/// Function to start the service.
/// 
/// 
protected override void OnStart(string[] args)
{
    eventLog.WriteEntry("The OnStart() event called", EventLogEntryType.Information);
    eventLog.WriteEntry("The service is started",EventLogEntryType.Information);

    string firstName = "John";
    string secondName = string.Empty;

    while (serviceFlag)
    {
        try
        {
            if (string.IsNullOrEmpty(secondName))
            {
                eventLog.WriteEntry("Second Name is empty.", EventLogEntryType.Warning);
            }

            //Perform some operations

        }
        catch (Exception ex)
        {
            eventLog.WriteEntry("Service stopped due to exception", EventLogEntryType.Error);
            serviceFlag = false;
        }
    }
    eventLog.WriteEntry("The service is stopped", EventLogEntryType.Information);
}

Complete code:

Here is the sample code template that demonstrate custom event logging for Windows Service applications.

using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

using System.Diagnostics;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        EventLog eventLog = new EventLog();

        bool serviceFlag = true;

        /// 
        /// Constructor.
        /// Initialize the EventLog instance in the constructor.
        /// 
        public Service1()
        {
            // Disable the default application event log.
            this.AutoLog = false;

            // Create an event storuce by specifying the name of the log.
            // Check to Make sure that it is not currently exist.
            if (!EventLog.SourceExists("MySourceName"))
            {
                // Create event source.
                EventLog.CreateEventSource("MySourceName", "MyLog");
            }

            // Configure the event log instalce.
            eventLog.Source = "MySourceName";
            eventLog.Log = "MyLog";

            InitializeComponent();
        }

        /// 
        /// Function to start the service.
        /// 
        /// 
        protected override void OnStart(string[] args)
        {
            eventLog.WriteEntry("The OnStart() event called", EventLogEntryType.Information);
            eventLog.WriteEntry("The service is started",EventLogEntryType.Information);

            string firstName = "John";
            string secondName = string.Empty;

            while (serviceFlag)
            {
                try
                {
                    if (string.IsNullOrEmpty(secondName))
                    {
                        eventLog.WriteEntry("Second Name is empty.", EventLogEntryType.Warning);
                    }

                    //Perform some operations

                }
                catch (Exception ex)
                {
                    eventLog.WriteEntry("Service stopped due to exception", EventLogEntryType.Error);
                    serviceFlag = false;
                }
            }
            eventLog.WriteEntry("The service is stopped", EventLogEntryType.Information);
        }

        /// 
        /// Event to stop the Service.
        /// 
        protected override void OnStop()
        {
            eventLog.WriteEntry("The OnStop() event called", EventLogEntryType.Information);
            serviceFlag = false;
        }
    }
}


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   How to list all the dependent windows services using C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo