.NET Core Web API Logging Using NLog In RabbitMQ

In this article, we will see how we can log information or errors in Event Log using Nlog in RabbitMQ.

In my previous article, we saw how we can log information or errors in Event Log using Nlog in NET Core Web API. Here, let us use NLog for information logging while using RabbitMQ.

Let's start the step-by-step process now.

Create a project.
  • 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 RabbitMQ 
 
Add Nlog.RabbitMQ.Target NuGet package to your project.
 
.NET Core Web API Logging Using NLog In RabbitMQ
 
Let's create an interface having each kind of different method to store the logs, like Debug, Warning, Information, Error etc. 
  1. namespace CoreNLogRabbitMQ  
  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.

Initialize an instance of LogEventInfo with log level type, a loggername, and a message.
  1. using NLog;  
  2. using System;  
  3. using System.Collections.Generic;  
  4.    
  5. namespace CoreNLogRabbitMQ  
  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("RmqTarget");  
  18.             var logEventInfo = new LogEventInfo(LogLevel.Debug, "RmqLogMessage", $"{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 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 as LogNLog.

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

In nlog.config, we need to configure RabbitMQ. As we are going to use local RabbitMQ, set "localhost" as the Host, "guest" as username and password, and provide the exchange name which will be created in RabbitMQ if it's not there already.

Add the assembly which we have added through NuGet Package under Extensions. Also, configure the rule where we are mentioning "Trace as minimum level" and write to logstash.
  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\CoreNLogRabbitMQ\CoreNLogRabbitMQ\LOG\InnerLog.txt">  
  3.     <extensions>  
  4.         <add assembly="Nlog.RabbitMQ.Target" />  
  5.   </extensions>       
  6.     <variable name="rmqHost" value="localhost" />  
  7.     <variable name="rmqUser" value="guest" />  
  8.     <variable name="rmqPassword" value="guest" />  
  9.     <variable name="rmqvHost" value="/" />  
  10.     <targets async="true">  
  11.       <target name="logstash"  
  12.       xsi:type="RabbitMQ"  
  13.       username="${rmqUser}"  
  14.       password="${rmqPassword}"  
  15.       hostname="${rmqHost}"  
  16.       exchange="rmq.target.demo"  
  17.       port="5672"  
  18.       vhost="${rmqvHost}"  
  19.       useJSON ="true"  
  20.       >  
  21.         <field key="fieldFromConfig" name="Field From Config" layout="${machinename}"/>  
  22.         <field key="EmployeeName" name="Employee Name" layout="Overriden From Config"/>  
  23.         <field key="EmployeeID" name="" layout="Overriden From Config"/>  
  24.       </target>  
  25.     </targets>  
  26.    
  27.      
  28.     <rules>  
  29.         <logger name="*" minlevel="Trace" writeTo="logstash" />  
  30.   </rules>  
  31. </nlog>  

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6.    
  7. namespace CoreNLogRabbitMQ.Controllers  
  8. {  
  9.     [Route("api/[controller]")]  
  10.     public class ValuesController : Controller  
  11.     {  
  12. private ILog logger;  
  13.         public ValuesController(ILog logger)  
  14.         {  
  15.             this.logger = logger;  
  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.         // POST api/values  
  33.         [HttpPost]  
  34.         public void Post([FromBody]string value)  
  35.         {  
  36.         }  
  37.         // PUT api/values/5  
  38.         [HttpPut("{id}")]  
  39.         public void Put(int id, [FromBody]string value)  
  40.         {  
  41.         }  
  42.         // DELETE api/values/5  
  43.         [HttpDelete("{id}")]  
  44.         public void Delete(int id)  
  45.         {  
  46.         }  
  47.     }  
  48. }  

Before we run our application, RabbitMQ should be configured. So, let's do that.

Install Erlang which is required in order to configure RabbitMQ. You can download and install Erlang from the below link.

https://www.erlang.org/downloads

Install RabbitMQ Server from the below link.

https://www.rabbitmq.com/download.html

In order to configure RabbitMQ management portal, go to the following path.

C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.10\sbin

Execute this command now.

rabbitmq-plugins enable rabbitmq_management

.NET Core Web API Logging Using NLog In RabbitMQ 

Browse the below URL from the browser and you can check that the RabbitMQ Management portal is configured with default username and password.

http://localhost:15672/

Username: guest

Password: guest

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

.NET Core Web API Logging Using NLog In RabbitMQ 

In the RabbitMQ Management portal, we can see that the new exchange is created and the graph shows that our log message is pushed.

.NET Core Web API Logging Using NLog In RabbitMQ 

That's it. We have successfully implemented NLog with Rabbit MQ. I hope you will find it useful. You can download the sample application from here