.NET Core Web API Logging Using NLog In Text File

Logging errors is an important part of every web application. In here, we will see how to use Nlog to list some information or error in a text file in a .NET Core Web API.

Open Visual Studio and create a new project. Select ASP.NET Core Web Application.

Select API as the template and click the OK button.

.NET Core Web API Logging Using NLog In Text File 

Add Nlog.Extensions.Logging NuGet package.

.NET Core Web API Logging Using NLog In Text File 

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

  1. namespace CoreNLogText  
  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 CurrentClassLogger through LogManager of Nlog, i.e., logger.

Call each method through logger and pass the message as a parameter.

  1. using NLog;  
  2. namespace CoreNLogText  
  3. {  
  4.     public class LogNLog : ILog  
  5.     {  
  6.         private static ILogger logger = LogManager.GetCurrentClassLogger();  
  7.    
  8.         public LogNLog()  
  9.         {  
  10.         }  
  11.    
  12.         public void Information(string message)  
  13.         {  
  14.             logger.Info(message);  
  15.         }  
  16.    
  17.         public void Warning(string message)  
  18.         {  
  19.             logger.Warn(message);  
  20.         }  
  21.    
  22.         public void Debug(string message)  
  23.         {  
  24.             logger.Debug(message);  
  25.         }  
  26.    
  27.         public void Error(string message)  
  28.         {  
  29.             logger.Error(message);  
  30.         }  
  31.     }  
  32. }  

In the startup.cs file, load the configuration for Nlog. For now, give a 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 Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using System.IO;  
  6. using NLog;  
  7.    
  8. namespace CoreNLogText  
  9. {  
  10.     public class Startup  
  11.     {  
  12.         public Startup(IConfiguration configuration)  
  13.         {  
  14.             LogManager.LoadConfiguration(System.String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));  
  15.             Configuration = configuration;  
  16.         }  
  17.    
  18.         public IConfiguration Configuration { get; }  
  19.    
  20.         public void ConfigureServices(IServiceCollection services)  
  21.         {  
  22.             services.AddMvc();  
  23.    
  24.             services.AddSingleton<ILog, LogNLog>();  
  25.         }  
  26.    
  27.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  28.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  29.         {  
  30.             if (env.IsDevelopment())  
  31.             {  
  32.                 app.UseDeveloperExceptionPage();  
  33.             }  
  34.    
  35.             app.UseMvc();  
  36.         }  
  37.     }  
  38. }  

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 under extensions. Also, configure the rule where we are mentioning to debug at minimum level and write to log file.

nlog.config

  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\CoreNLogText\CoreNLogText\LOG\InnerLog.txt">  
  3.     <extensions>  
  4.         <add assembly="NLog.Extended" />  
  5.     </extensions>  
  6.      
  7.     <targets>  
  8.         <target name="logfile" xsi:type="File" fileName="D:/AKKI_DEV/RND/CoreNLogText/CoreNLogText/LOG/${shortdate}_log.txt" layout="${longdate} ${level:uppercase=true} ${message}"/>  
  9.     </targets>  
  10.      
  11.     <rules>  
  12.         <logger name="*" minlevel="Debug" writeTo="logfile" />  
  13.     </rules>  
  14. </nlog>  

When we create a project with Web API, the values controller is added with 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 all kinds of log methods from the Controller. 

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

Run the application. The Get method of values controller is called. We can see the result of the API in the browser, as shown below.

.NET Core Web API Logging Using NLog In Text File 

Now, go to the configured path in nlog.config and open the text file. You can find the log which was written by the API.

Log

2019-01-18 23:08:04.4985 INFO Information is logged
2019-01-18 23:08:04.5623 WARN Warning is logged
2019-01-18 23:08:04.5623 DEBUG Debug log is logged
2019-01-18 23:08:04.5623 ERROR Error is logged

That's it guys. I hope you enjoyed it. You can download the sample application from here.


Similar Articles