In this article, I will cover the following.
- Definition
- Support
- Log Level
- Why we need a log
- Where to log
- Implementation
- 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 requests, 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 | To follow troubleshooting; start technique X, end strategy X |
Why we need a log
Where to log
- Files
- Event Viewer Log
- Database
- Network
- Console
Implementation
Step 1
Open Visual Studio. Select File > New > Project.

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

Step 3
Select WebAPI and click OK.

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.
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.
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.
- <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=your sql source;initial catalog=YourDbNameDb;user id=u1;password=p1;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>
In this config file, I am targeting to log into three places.
- database
- txt file
- Event Viewer,
Please refer to the below screen.
Step 6
Now, in step 5, 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 the namespace nLog just like this -
- using NLog;
And, add the following code to this index method. The information will log into target files.
- using NLog;
- using System;
- using System.Web.Mvc;
- namespace NLogTest.Controllers {
- public class HomeController: Controller {
- private static Logger logger = LogManager.GetCurrentClassLogger();
- public ActionResult Index() {
- ViewBag.Title = "Home Page";
- logger.Info("Hell You have visited the Index view" + Environment.NewLine + DateTime.Now);
- return View();
- }
- public ActionResult About() {
- ViewBag.Message = "Your app description page.";
- logger.Info("hello now You have visited the About 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.
Now, you can open your Event Viewer in the following ways.
To access the Event Viewer
- Right-click on the Start button and select Control Panel > System & Security and double-click Administrative Tools.
- Double-click Event Viewer.
- Select the type of logs that you wish to review (error, information, etc.).
OrPress Windows+R to open the Run dialog, and type "eventvwr".
Summary
I hope you like this post, for any query please write in the comment section.

sai jamesPosted Aug 11, 2023, 1:07 AM
Hi Hamid, how are you able to insert the data in the database for all the fields??
bhuwanPosted Feb 8, 2021, 11:06 AM
Well explained.
mostafa fallahPosted Oct 2, 2020, 3:46 PM
It was very good sample. Can you set me how can i set database configs for Postgre ?
Amir NavedPosted Sep 1, 2019, 3:33 AM
Great Job Hamid Khan Keep Going man
Zain AsgharPosted Apr 22, 2019, 1:23 AM
How we can send userId to the database while logging?
VASUDEVA THIRUMALAR MUNAGALAPosted Mar 19, 2019, 4:52 AM
Thanks for sharing .
Rushi MehtaPosted Dec 6, 2018, 5:40 AM
Nice Article
Jignesh KumarPosted Dec 6, 2018, 3:56 AM
Nice Article. Thanks for sharing