How to log data to the Windows Event Log in C#

Take advantage of the Windows Event Log to store the log data of your .NET Core applications running on Windows

How to log data to the Windows Event Log in C#
Dell technologies

The Windows operating system logs data into the Windows Event Log whenever a problem occurs. You can view this data using the Windows Event Viewer tool. This article discusses how you can programmatically work with the Windows Event Log in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with the Windows event log in the subsequent sections of this article.

Install the EventLog NuGet package

To be able to work with the Windows Event Log in .NET Core applications, you should install the Microsoft.Extensions.Logging.EventLog package from NuGet. You can do this either via the NuGet Package Manager inside the Visual Studio 2019 IDE, or by executing the following command at the NuGet Package Manager Console:

Install-Package Microsoft.Extensions.Logging.EventLog

Create an instance of the EventLog class in C#

To create an instance of the EventLog class and write an entry to the Windows Event Log, you can use the following code:

EventLog eventLog = new EventLog();
eventLog.Source = "MyEventLogTarget";
eventLog.WriteEntry("This is a test message.", EventLogEntryType.Information);

Write to an EventLog instance in C#

If you would like to log data to this EventLog instance from your application, you can use the following code:

string message = "This is a test message.";
using (EventLog eventLog = new EventLog("Application"))
{
    eventLog.Source = "Application";
    eventLog.WriteEntry(message, EventLogEntryType.Information);
}

Clear an EventLog instance in C#

To clear the EventLog instance, you can use the following code:

EventLog eventLog = new EventLog();
eventLog.Source = "MyEventLogSource";
eventLog.Clear();

The following code snippet can be used to delete an event log.

if (EventLog.Exists("MyEventLogTarget"))
{
   EventLog.Delete("MyEventLogTarget");
}

Read EventLog entries in C#

You can read all log entries using the code snippet given below:

EventLog eventLog = new EventLog();
eventLog.Log = "MyEventLogTarget";
foreach (EventLogEntry entry in eventLog.Entries)

   //Write your custom code here
}

Use NLog to write log data to EventLog in C#

Now we’ll take advantage of the NLog.WindowsEventLog package. This package will allow us to use NLog to send log data to EventLog while working from the .NET Core environment.

NLog.WindowsEventLog encapsulates the intricacies of connecting to EventLog and working with EventLog from ASP.NET Core. You just have to call NLog methods as you normally do.

Since we’ll be using NLog to log data to EventLog, add the following package to your project:

Install-Package NLog.WindowsEventLog

Create a logging interface in C#

Create the following interface to store the logs as information, warning, debug, or error.

public interface ILogManager
    {
        void LogInformation(string message);
        void LogWarning(string message);
        void LogDebug(string message);
        void LogError(string message);
    }

Implement an NLogManager class in C#

Next, create a class named NLogManager that extends the ILogManager interface and implements each of its methods.

public class NLogManager : ILogManager
    {
        private static NLog.ILogger logger =
LogManager.GetCurrentClassLogger();
        public void LogDebug(string message)
        {
            throw new NotImplementedException();
        }
        public void LogError(string message)
        {
            logger.Error(message);
        }
        public void LogInformation(string message)
        {
            throw new NotImplementedException();
        }
        public void LogWarning(string message)
        {
            throw new NotImplementedException();
        }
    }

Implement a LogError method in C#

Note that for the sake of simplicity we’ll be using the LogError method in this example and the other methods of the NLogManager class will not be implemented. Let’s now understand how we can use NLog to log data to EventLog. Modify the LogError method of the NLogManager class as shown below:

public void LogError(string message)
    {
        Logger logger = LogManager.GetLogger("EventLogTarget");
        var logEventInfo = new LogEventInfo(LogLevel.Error,
        logger.Name, message);
        logger.Log(logEventInfo);
    }

Note that EventLogTarget is just the name of the log target for EventLog, which needs to be defined in the configuration file nlog.config. The LogEventInfo class is your log event, i.e., it represents the log event. To its constructor you should pass the log level, the name of the logger, and the message to be logged.

Configure NLog to log data to EventLog in C#

To configure NLog programmatically to log data to EventLog, you can use the following code:

var config = new NLog.Config.LoggingConfiguration();
var logEventLog = new NLog.Targets.EventLogTarget("EventLogTarget");
config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Error, logEventLog);
NLog.LogManager.Configuration = config;

Complete NLogManager example in C#

The complete source code of the NLogManager class is given below for your reference:

public class NLogManager : ILogManager
    {
        private static NLog.ILogger logger =
LogManager.GetCurrentClassLogger();
        public void LogDebug(string message)
        {
            logger.Debug(message);
        }
public void LogError(string message)
        {
Logger logger = LogManager.GetLogger("EventLogTarget");
var logEventInfo = new LogEventInfo(LogLevel.Error,
logger.Name, message);
logger.Log(logEventInfo);
        }
        public void LogInformation(string message)
        {
            logger.Info(message);
        }
        public void LogWarning(string message)
        {
            logger.Warn(message);
        }
    }

To leverage the NLogManager instance in the controllers you should add an instance of it in the ConfigureServices method as shown in the code snippet given below.

services.AddSingleton<ILogManager, NLogManager>();

When you launch the Windows Event Viewer, you can see the error message logged there as shown in the screenshot below.

windows event viewer IDG

The Windows Event Log is typically used to record system events, network traffic, and related data such as security, performance, etc. You can take advantage of the Windows Event Log as a log target to store your application’s data. If your application runs only on Windows, the Windows Event Log is a nice option for storing your application’s event log data.

How to do more in C#:

Copyright © 2020 IDG Communications, Inc.

How to choose a low-code development platform