.NET Core Web API Logging Using NLog In Event Log

Nlog is a useful tool for logging the errors and such information in the Event Log. In here, let us see the process of using Nlog for error logging in .NET Core Web API.

Let's get started.

  • Open Visual Studio and create a new project.
  • Select ASP.NEt Core Web Application.
  • Select API as a template and click the OK button.
.NET Core Web API Logging Using NLog In Event Log 

Add the Nlog.WindowsEventLog NuGet package.

.NET Core Web API Logging Using NLog In Event Log 

Let's create an interface having each kind of different methods to store the logs like Debug, Warning, Information, Error etc.

  1. namespace CoreNLogEventLog  
  2. {  
  3.     public interface ILog  
  4.     {  
  5.         void Information(string message);  
  6.         void Warning(string message);  
  7.         void Debug(string message);  
  8.         void Error(string message);  
  9.     }  
  10. }  

Implement the above interface in the class and also, get the CurrentClassLogger through LogManager of Nlog, i.e., logger.

Initialize an instance of LogEventInfo with the log level type, loggername, and message.

  1. using NLog;  
  2. using System;  
  3. using System.Collections.Generic;  
  4.    
  5. namespace CoreNLogEventLog  
  6. {  
  7.     public class LogNLog : ILog  
  8.     {  
  9.         private static ILogger logger = LogManager.GetCurrentClassLogger();  
  10.    
  11.         public LogNLog()  
  12.         {  
  13.         }  
  14.    
  15.         public void Debug(string message)  
  16.         {  
  17.             Logger logger = LogManager.GetLogger("EventLogTarget");  
  18.             var logEventInfo = new LogEventInfo(LogLevel.Error, "EventLogMessage", $"{message}, generated at {DateTime.UtcNow}.");  
  19.             logger.Log(logEventInfo);  
  20.             //LogManager.Shutdown();  
  21.         }  
  22.    
  23.         public void Error(string message)  
  24.         {  
  25.             logger.Error(message);  
  26.         }  
  27.    
  28.         public void Information(string message)  
  29.         {  
  30.             logger.Info(message);  
  31.         }  
  32.    
  33.         public void Warning(string message)  
  34.         {  
  35.             logger.Warn(message);  
  36.         }  
  37.     }  
  38. }  

In the startup.cs, load the configuration for Nlog. For now, give the name like nlog.config and give the root path. In the next step, we will add this file and provide the configuration.

Also, we need to add a singleton service of type Ilog with an implementation type LogNLog.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Builder;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using Microsoft.AspNetCore.Mvc;  
  9. using Microsoft.Extensions.Configuration;  
  10. using Microsoft.Extensions.DependencyInjection;  
  11. using Microsoft.Extensions.Logging;  
  12. using Microsoft.Extensions.Options;  
  13. using NLog;  
  14.    
  15. namespace CoreNLogEventLog  
  16. {  
  17.     public class Startup  
  18.     {  
  19.         public Startup(IConfiguration configuration)  
  20.         {  
  21.             LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));  
  22.             Configuration = configuration;  
  23.         }  
  24.    
  25.         public IConfiguration Configuration { get; }  
  26.    
  27.         // This method gets called by the runtime. Use this method to add services to the container.  
  28.         public void ConfigureServices(IServiceCollection services)  
  29.         {  
  30.             services.AddMvc();  
  31.    
  32.             services.AddSingleton<ILog, LogNLog>();  
  33.         }  
  34.    
  35.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  36.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  37.         {  
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.    
  43.             app.UseMvc();  
  44.         }  
  45.     }  
  46. }  

In nlog.config, we need to configure two paths for logging. One is InternalLog and another is actual log which we want to write. So first, provide the internal log file path to the attribute internalLogFile and second, provide the actual path in the target. Add the assembly which we have added through NuGet package under extensions. Also, configure the rule where we are mentioning that Error as a minimum level and write to the EventLog.

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Trace" internalLogFile="D:\AKKI_DEV\RND\CoreNLogEventLog\CoreNLogEventLog\LOG\InnerLog.txt">  
  3.     <extensions>  
  4.         <add assembly="Nlog.WindowsEventLog" />  
  5.   </extensions>      
  6.     <variable name="appName" value="NLogEventLog" />  
  7. <targets>  
  8.   <target xsi:type="EventLog"  
  9.   name="eventlog"  
  10.   source="${appName}"  
  11.   layout="${message}${newline}${exception:format=ToString}" Log="Application" machinename="."/>  
  12. </targets>   
  13.   <rules>  
  14.         <logger name="*" writeTo="eventlog" minlevel="Error" />  
  15.   </rules>  
  16. </nlog>  

When we create a project with Web API, the values controller will be added with the default CRUD operation. So, let's use the GET method of that controller and try to add a log in the same. Here, we have called the debug kind of log methods from the Controller. 

  1. using Microsoft.AspNetCore.Mvc;  
  2. using System.Collections.Generic;  
  3.    
  4. namespace CoreNLogEventLog.Controllers  
  5. {  
  6.     [Route("api/[controller]")]  
  7.     public class ValuesController : Controller  
  8.     {  
  9.    
  10.    private ILog logger;  
  11.         public ValuesController(ILog logger)  
  12.         {  
  13.             this.logger = logger;  
  14.         }  
  15.    
  16.    
  17.         // GET api/values  
  18.         [HttpGet]  
  19.         public IEnumerable<string> Get()  
  20.         {  
  21.             logger.Debug("Get API called of Values Controller");  
  22.    
  23.             return new string[] { "value1""value2" };  
  24.         }  
  25.    
  26.         // GET api/values/5  
  27.         [HttpGet("{id}")]  
  28.         public string Get(int id)  
  29.         {  
  30.             return "value";  
  31.         }  
  32.    
  33.         // POST api/values  
  34.         [HttpPost]  
  35.         public void Post([FromBody]string value)  
  36.         {  
  37.         }  
  38.    
  39.         // PUT api/values/5  
  40.         [HttpPut("{id}")]  
  41.         public void Put(int id, [FromBody]string value)  
  42.         {  
  43.         }  
  44.    
  45.         // DELETE api/values/5  
  46.         [HttpDelete("{id}")]  
  47.         public void Delete(int id)  
  48.         {  
  49.         }  
  50.     }  
  51. }  

Run the application and the GET method of values controller is called. We can see the result of the API.

.NET Core Web API Logging Using NLog In Event Log 

Open the "Run" window and type eventvwr which will open the Event Viewer.

.NET Core Web API Logging Using NLog In Event Log 

Select the application from the left panel and you can see your log highlighted as below.

.NET Core Web API Logging Using NLog In Event Log 

You can download the sample application from here.