Logging Data to Windows Event Log in C#

By FoxLearn 1/6/2025 6:53:21 AM   109
Use the Windows Event Log to store log data for your .NET Core applications on Windows, where the OS logs issues that can be viewed with the Windows Event Viewer tool.

To work with the Windows Event Log in .NET Core applications, install the Microsoft.Extensions.Logging.EventLog package from NuGet.

This can be done either through the NuGet Package Manager in Visual Studio 2019 or by running the following command in the NuGet Package Manager Console:

Install-Package Microsoft.Extensions.Logging.EventLog

Creating an EventLog in C#

To create an EventLog instance and write an entry to the Windows Event Log.

EventLog eventLog = new EventLog();
eventLog.Source = "MyApp";
eventLog.WriteEntry("Application started successfully.", EventLogEntryType.Information);

Writing to an EventLog in C#

To log data to an EventLog instance from your application.

string message = "System initialized successfully.";
using (EventLog eventLog = new EventLog("System"))
{
    eventLog.Source = "MyApp";
    eventLog.WriteEntry(message, EventLogEntryType.Warning);
}

Clearing an EventLog in C#

To clear an EventLog instance, use the following code

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

To delete an event log, you can use this code:

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

Reading EventLog Entries in C#

To read all log entries, use the following code

EventLog eventLog = new EventLog();
eventLog.Log = "Application";
foreach (EventLogEntry entry in eventLog.Entries)
{
    // Process each entry
}

Using NLog to Write to EventLog in C#

Use the NLog.WindowsEventLog package to log data to EventLog in .NET Core. This package simplifies connecting to EventLog, allowing you to use NLog methods as usual.

To get started, add the package with the command: Install-Package NLog.WindowsEventLog.

Creating a logging interface in C#

Create an interface to log messages 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#

Create a class called NLogManager that implements the ILogManager interface and 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#

To log data to EventLog using NLog, modify the LogError method as follows:

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

In this example, 'EventLogTarget' is the name of the EventLog log target, which must be defined in the nlog.config file. The LogEventInfo class represents the log event, and its constructor requires the log level, logger name, and the message to be logged."

Configure NLog to log data to EventLog in C#

To configure NLog programmatically for logging data to EventLog, 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;

To use the NLogManager instance in controllers, add it in the ConfigureServices method as shown below.

services.AddSingleton<ILogManager, NLogManager>();

When you open the Windows Event Viewer, you can view the logged error message.

The Windows Event Log is commonly used to record system events, network traffic, and other data like security and performance. It serves as a useful log target for storing application data, especially for applications running exclusively on Windows.