Skip to main content

How To Implement NLog With WebAPI In Asp.Net(C#).

What is NLog?

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

Which platform support it?
  • .NET Framework 3.5, 4, 4.5, 4.6 & 4.7
  • .NET Framework 4 client profile
  • Xamarin Android
  • Xamarin iOS
  • Windows Phone 8
  • Silver light 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
There are several log levels.
  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 
Where we can log?
  • Console
  • Database
  • Email
  • Event Viewer Log
  • Files
  • Network
Implementation of NLog

Step 1 : Open Visual Studio. Select File > New > Project.


Step 2 : Select Web> ASP.NET Web Application > Give your project name "NLogTestApp", and then click OK.


Step 3 : Select Web API and click OK.


Step 4 : Now, we add NLog in our project. 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.


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



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

Step 5 : Now, add the following code to your config file.

<configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />
        <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />
        <target name="database" type="Database" connectionString="Data Source=SRKSUR5085LT\SQLEXPRESS;initial catalog=NLog;user id=sa;password=OPTICAL;MultipleActiveResultSets=True;">
            <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>
            <parameter name="@TimeStamp" layout="${date}" />
            <parameter name="@Level" layout="${level}" />
            <parameter name="@Logger" layout="${logger}" />
            <parameter name="@Message" layout="${message}" />
            <parameter name="@UserId" layout="${mdc:user_id}" />
            <parameter name="@Exception" layout="${exception}" />
            <parameter name="@StackTrace" layout="${stacktrace}" />
            <dbProvider>System.Data.SqlClient</dbProvider>
        </target>
    </targets>
    <rules>
        <!-- I am adding my 3 logging rules here -->
        <logger name="*" minlevel="Debug" writeTo="database" />
        <logger name="*" minlevel="Trace" writeTo="logfile" />
        <logger name="*" minlevel="Trace" writeTo="eventlog" />
    </rules>
</nlog>  

We will targeting to log into three places.
  1. database
  2. txt file
  3. Event Viewer
Your config look like below.



Step 6 : We need to create our DB Script as shown below

CREATE TABLE [dbo].[exceptionlog]   
  (   
     [id]         [INT] IDENTITY(1, 1) NOT NULL,   
     [timestamp]  [DATETIME] NOT NULL,   
     [level]      [VARCHAR](100) NOT NULL,   
     [logger]     [VARCHAR](1000) NOT NULL,   
     [message]    [VARCHAR](3600) NOT NULL,   
     [userid]     [INT] NULL,   
     [exception]  [VARCHAR](3600) NULL,   
     [stacktrace] [VARCHAR](3600) NULL,   
     CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (   
     pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,   
     allow_row_locks = on, allow_page_locks = on) ON [PRIMARY]   
  )   
ON [PRIMARY]   

Step 7 : Now, go to your home controller and add following code in index method.

using NLog;
using System;
using System.Web.Mvc;

namespace NLogTestApp.Controllers
{    
    public class HomeController : Controller
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            logger.Info("Hello we have visited the Index view" + Environment.NewLine + DateTime.Now);           
            return View();
        }
    }
}

Now, run the application.

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


You can see this in your Event Viewer.


You can see the following in your text file.



When you are working with WEPAPI that time NLog is very useful and easy to apply.

Comments

Post a Comment

Popular posts from this blog

How To See Logs Of Dropped Tables From The Database in MS SQL.

Here, I will explain you how you can see logs of users. Step 1 : First, create a new database with name "test". Step 2 : Create a new table. Step 3 : Now, go and drop the table by running the following command. Step 4 : Now, select your database under Object Explorer and go to Reports >> Standard Reports >> Schema Changes History. Step 5 : You will then see the schema change history. The report will show you who has dropped this table. Finally, you can locate the user activity with the help of log.

How To Deploy .net Core Application On Linux

Here, I can explain steps to deploy .net core application on linux machine. Step 1 - Publish your .net Core application: First, create a .net core application on VS; you can make an MVC project or Web API project and if you already have an existing project, then open it. Right Click on your project Click on publish Now create a new publish profile, and browse the folder where you want to publish your project dll Click on publish so it will create your dll in the folder Step 2 - Install required .net Module on Linux: Now we have our web application dll and now we need to host it on the Linux environment. First, we need to understand how the deployment works in Linux. .Net applications run on Kestrel servers and we run Apache or Nginx server in Linux environments, which acts as a proxy server and handles the traffic from outside the machine and redirects it to the Kestrel server so we will have Apache or Nginx server as the middle layer. In this article, we will use Apache as a proxy ser

List Of Commonly Used Angular Commands

1) To get the npm version,    npm -v 2) To get the node version,    node -v 3) To get the Angular version,    ng v  4) To get the Jasmine version,    jasmine -v  5) To get the Karma version,    karma --version  6) To install Angular CLI,    npm install @angular/cli -g   npm install @angular/cli 7) To install the next version of Angular CLI, v   npm install @angular/cli@next  8) To get help in the terminal,    ng help 9) To create a new project in Angular,    ng new project-name  10) To skip external dependencies while creating a new project,    ng new project-name --skip-install  11) To run the Angular project,   ng serve (or) npm start (or) ng serve --force  12) Dry Run,   ng new project-name --dry-run 13) To create a new component in the Angular Project,   ng generate component component-