How To Implement NLog In WebAPI

NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog makes it easy to write to several targets. (database, file, eventviewer).

In this article, I will cover the following.

  1. Definition 
  2. Support
  3. Log Level
  4. Why we need a log 
  5. Where to log 
  6. Implementation
  7. Summary 

After reading this article, I hope you will be able to use the logging feature easily.

Definition

NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog makes it easy to write to several targets (database, file, event viewer).

NLog is an extraordinary open-source logging device that enables the designers to effortlessly and proficiently actualize custom logging. NLog can be arranged to log to various targets.

Support

NLog supports the following platforms,

  • .NET Framework 3.5, 4, 4.5, 4.6 & 4.7
  • .NET Framework 4 client profile
  • Xamarin Android
  • Xamarin iOS
  • Windows Phone 8
  • Silverlight 4 and 5
  • Mono 4
  • ASP.NET 4 (NLog.Web package)
  • ASP.NET Core (NLog.Web.AspNetCore package)
  • .NET Core (NLog.Extensions.Logging package)
  • .NET Standard 1.x - NLog 4.5
  • .NET Standard 2.x - NLog 4.5
  • UWP - NLog 4.5

Log levels

Each log passage has a dimension. What's more, every log is arranged to incorporate or overlook certain dimensions. A typical arrangement is to determine the base dimension where that dimension and larger amounts are incorporated. For instance, in the event that has the base dimension as Info, Info, Warn, Error and Fatal are logged, however, Debug and Trace are disregarded.

The log levels, in sliding request, are as per the following.

 S.N  Level  Use 
 1   Fatal   Something terrible occurred; the application is going down 
 2   Error   Something fizzled; the application might possibly proceed 
 3   Warn   Something surprising; the application will proceed 
 4   Info   Normal conduct like mail sent, client refreshed profile and so on. 
 5   Debug   For troubleshooting; the executed question, the client confirmed, session terminated 
 6   Trace   For follow troubleshooting; start technique X, end strategy X 
 
Why we need a log

Logging is one of the key properties when creating any software application like on Windows and on the web etc. NLog is an incredible open-source logging instrument that enables the software engineers to effectively and proficiently actualize the logging structure.

In this post, I will demonstrate the means expected to arrange and utilize NLog in our application. 
 
Where to log
 
We can use NLog easily within the following places.
  1. Files
  2. Event Viewer Log
  3. Database
  4. Network
  5. Email
  6. Console

Implementation

Step 1

Open Visual Studio. Select File > New > Project.

How To Implement NLog In WebAPI

Step 2

Select Web> ASP.NET Web Application > Give your project a name (I have given NLogTest), and then click OK.

How To Implement NLog In WebAPI

Step 3

Select WebAPI and click OK.

How To Implement NLog In WebAPI

Step 4

Now, you have to add NLog to your project.

So, follow the steps here. Right-click on your project solution, click on "Manage NugGet Packages". Click on the "Browse" link button and in the search box, type nlog. It will show you NLogDll as shown below. Just install this DLL.

How To Implement NLog In WebAPI 

After that, when you click "Install", you will get the following window, i.e., Preview Changes.

How To Implement NLog In WebAPI 

In this popup window, click the OK button. After it is successfully installed, you will get the Nlog DLL in your project reference.

How To Implement NLog In WebAPI 

Now, your half part of the configuration is done! Let us go to the next level. 

Step 5

Now, add the following code to your config file.

  1. <configSections>  
  2.     <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />  
  3. </configSections>  
  4. <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  5.     <targets>  
  6.         <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />  
  7.         <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />  
  8.         <target name="database" type="Database" connectionString="Data Source=your sql source;initial catalog=YourDbNameDb;user id=u1;password=p1;MultipleActiveResultSets=True;">  
  9.             <commandText> insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, case when len(@UserID) = 0 then null else @UserId end, @Exception, @StackTrace); </commandText>  
  10.             <parameter name="@TimeStamp" layout="${date}" />  
  11.             <parameter name="@Level" layout="${level}" />  
  12.             <parameter name="@Logger" layout="${logger}" />  
  13.             <parameter name="@Message" layout="${message}" />  
  14.             <parameter name="@UserId" layout="${mdc:user_id}" />  
  15.             <parameter name="@Exception" layout="${exception}" />  
  16.             <parameter name="@StackTrace" layout="${stacktrace}" />  
  17.             <dbProvider>System.Data.SqlClient</dbProvider>  
  18.         </target>  
  19.     </targets>  
  20.     <rules>  
  21.         <!-- I am adding my 3 logging rules here -->  
  22.         <logger name="*" minlevel="Debug" writeTo="database" />  
  23.         <logger name="*" minlevel="Trace" writeTo="logfile" />  
  24.         <logger name="*" minlevel="Trace" writeTo="eventlog" />  
  25.     </rules>  
  26. </nlog>  
In this config file, I am targeting to log into three places.
  1. database
  2. txt file
  3. Event Viewer,
Please refer to the below screen.
 
How To Implement NLog In WebAPI 

Step 6

Now, in step 5, we need to create our DB Script as shown below.

  1. CREATE TABLE [dbo].[exceptionlog]   
  2.   (   
  3.      [id]         [INT] IDENTITY(1, 1) NOT NULL,   
  4.      [timestamp]  [DATETIME] NOT NULL,   
  5.      [level]      [VARCHAR](100) NOT NULL,   
  6.      [logger]     [VARCHAR](1000) NOT NULL,   
  7.      [message]    [VARCHAR](3600) NOT NULL,   
  8.      [userid]     [INTNULL,   
  9.      [exception]  [VARCHAR](3600) NULL,   
  10.      [stacktrace] [VARCHAR](3600) NULL,   
  11.      CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (   
  12.      pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,   
  13.      allow_row_locks = on, allow_page_locks = onON [PRIMARY]   
  14.   )   
  15. ON [PRIMARY]   

Step 7

Now, go to your home controller and add the namespace nLog just like this -

using NLog;

And, add the following code to this index method. The information will log into target files. 

  1. using NLog;  
  2. using System;  
  3. using System.Web.Mvc;  
  4. namespace NLogTest.Controllers {  
  5.     public class HomeController: Controller {  
  6.         private static Logger logger = LogManager.GetCurrentClassLogger();  
  7.         public ActionResult Index() {  
  8.             ViewBag.Title = "Home Page";  
  9.             logger.Info("Hell You have visited the Index view" + Environment.NewLine + DateTime.Now);  
  10.             return View();  
  11.         }  
  12.         public ActionResult About() {  
  13.             ViewBag.Message = "Your app description page.";  
  14.             logger.Info("hello now You have visited the About view" + Environment.NewLine + DateTime.Now);  
  15.             return View();  
  16.         }  
  17.     }  
  18. }  
How To Implement NLog In WebAPI

Now, run the application.

And open your SQL. You will see the following logs inserted in your database.

How To Implement NLog In WebAPI 
 
You can see this in your Event Viewer.
 
How To Implement NLog In WebAPI 

You can see the following in your text file.

How To Implement NLog In WebAPI 

Now, you can open your Event Viewer in the following ways.

To access the Event Viewer

  1. Right-click on the Start button and select Control Panel > System & Security and double-click Administrative Tools.
  2. Double-click Event Viewer.
  3. Select the type of logs that you wish to review (error, information etc.).

    Or

    Press Windows+R to open the Run dialog, and type "eventvwr".
Summary

With the majority of Web APIs, connecting your custom logging system is simple and smooth. With that close by, you can oversee your following and investigating systems and can use on the ground-breaking highlights of your most loved logging structure - like I utilized nLog for this situation. 
 
I hope you like this post, for any query please write in the comment section.