Friday 23 November 2018

how to implement NLog in webapi



https://www.c-sharpcorner.com/article/how-to-implement-nlog-in-webapi/

In this topic I will cover the following things
1-    Definition
3-    Log Level
4-    Implementation
After reading this article I hope you will be able to use 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, eventviewer)
Log levels
The log levels, in sliding request, are as per the following:
 S.N Level Use
 1 Fatal Something terrible occurred; application is going down
 2 Error Something fizzled; application might possibly proceed
 3 Warn Something surprising; application will proceed
 4 Info Normal conduct like mail sent, client refreshed profile and so on.
 5 Debug For troubleshooting; executed question, client confirmed, session terminated
 6 Trace  For follow troubleshooting; start technique X, end strategy X


Implementation
Step 1
Click Visual studio> Select File>New>Project
 
Step 2
Select Web> Asp.net Web Application > Give your project name, for me I have given NLogTest then click on Ok
 
Step 3
Select WebApi then click on OK
 
Step 4
Now you have to add NLog to your project.
So follow the steps Right click on your project solution then click on Manage NugGet Packeses
And then install.
 
After click on install you will get following window.
 
Click OK on this pop up windo, after successful installed you will get dll in your project reference
 
Now your half part of configuration is done!
Let go to next level
Step 5
Now add following code in your config file
  1. <configSections>  
  2.   
  3. <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />  
  4.   
  5. </configSections>  
  6.   
  7. <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  8.   
  9. <targets>  
  10.   
  11. <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />  
  12.   
  13. <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />  
  14.   
  15. <target name="database" type="Database" connectionString="Data Source=your sql source;initial catalog=YourDbNameDb;user id=u1;password=p1;MultipleActiveResultSets=True;">  
  16.   
  17. <commandText>  
  18.   
  19. insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message,  
  20.   
  21. case when len(@UserID) = 0 then null  
  22.   
  23. else @UserId  
  24.   
  25. end,  
  26.   
  27. @Exception, @StackTrace);  
  28.   
  29. </commandText>  
  30.   
  31. <parameter name="@TimeStamp" layout="${date}"/>  
  32.   
  33. <parameter name="@Level" layout="${level}"/>  
  34.   
  35. <parameter name="@Logger" layout="${logger}"/>  
  36.   
  37. <parameter name="@Message" layout="${message}"/>  
  38.   
  39. <parameter name="@UserId" layout="${mdc:user_id}"/>  
  40.   
  41. <parameter name="@Exception" layout="${exception}"/>  
  42.   
  43. <parameter name="@StackTrace" layout="${stacktrace}"/>  
  44.   
  45. <dbProvider>System.Data.SqlClient</dbProvider>  
  46.   
  47. </target>  
  48.   
  49. </targets>  
  50.   
  51. <rules>  
  52.   
  53. <!-- add your logging rules here -->  
  54.   
  55. <logger name="*" minlevel="Debug" writeTo="database" />  
  56.   
  57. <logger name="*" minlevel="Trace" writeTo="logfile" />  
  58.   
  59. <logger name="*" minlevel="Trace" writeTo="eventlog" />  
  60.   
  61. </rules>  
  62.   
  63. </nlog>  


Please refer below screen
 
Step 6
Create your db Script
  1. CREATE TABLE [dbo].[ExceptionLog](  
  2.   
  3. [Id] [int] IDENTITY(1,1) NOT NULL,  
  4.   
  5. [TimeStamp] [datetime] NOT NULL,  
  6.   
  7. [Level] [varchar](100) NOT NULL,  
  8.   
  9. [Logger] [varchar](1000) NOT NULL,  
  10.   
  11. [Message] [varchar](3600) NOT NULL,  
  12.   
  13. [UserId] [intNULL,  
  14.   
  15. [Exception] [varchar](3600) NULL,  
  16.   
  17. [StackTrace] [varchar](3600) NULL,  
  18.   
  19. CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED  
  20.   
  21. (  
  22.   
  23. [Id] ASC  
  24.   
  25. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  26.   
  27. ON [PRIMARY]  
Step 7
Go to your home controller
And add following code
  1. using NLog;  
  2.   
  3. using System;  
  4.   
  5. using System.Web.Mvc;  
  6.   
  7. namespace NLogTest.Controllers  
  8.   
  9. {  
  10.   
  11. public class HomeController : Controller  
  12.   
  13. {  
  14.   
  15. private static Logger logger = LogManager.GetCurrentClassLogger();  
  16.   
  17. public ActionResult Index()  
  18.   
  19. {  
  20.   
  21. ViewBag.Title = "Home Page";  
  22.   
  23. logger.Info("Hell You have visited the Index view" + Environment.NewLine + DateTime.Now);  
  24.   
  25. return View();  
  26.   
  27. }  
  28.   
  29. public ActionResult About()  
  30.   
  31. {  
  32.   
  33. ViewBag.Message = "Your app description page.";  
  34.   
  35. logger.Info("hello now You have visited the About view" + Environment.NewLine + DateTime.Now);  
  36.   
  37. return View();  
  38.   
  39. }  
  40.   
  41. }  
  42.   
  43. }  


Now run the application
And open your sql you will see following logs inserted in your dB
 
You can see in your event viewer
 
You can see in your txt file
 
Now your can open your event viewer in 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, enter eventvwr