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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos