Take advantage of the Windows Event Log to store the log data of your .NET Core applications running on Windows Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. 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. 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#: How to use ArrayPool and MemoryPool in C# How to use the Buffer class in C# How to use HashSet in C# How to use named and optional parameters in C# How to benchmark C# code using BenchmarkDotNet How to use fluent interfaces and method chaining in C# How to unit test static methods in C# How to refactor God objects in C# How to use ValueTask in C# How to use immutability in C How to use const, readonly, and static in C# How to use data annotations in C# How to work with GUIDs in C# 8 When to use an abstract class vs. interface in C# How to work with AutoMapper in C# How to use lambda expressions in C# How to work with Action, Func, and Predicate delegates in C# How to work with delegates in C# How to implement a simple logger in C# How to work with attributes in C# How to work with log4net in C# How to implement the repository design pattern in C# How to work with reflection in C# How to work with filesystemwatcher in C# How to perform lazy initialization in C# How to work with MSMQ in C# How to work with extension methods in C# How to us lambda expressions in C# When to use the volatile keyword in C# How to use the yield keyword in C# How to implement polymorphism in C# How to build your own task scheduler in C# How to work with RabbitMQ in C# How to work with a tuple in C# Exploring virtual and abstract methods in C# How to use the Dapper ORM in C# How to use the flyweight design pattern in C# Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos