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
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 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.
- Files
- Event Viewer Log
- Database
- Network
- Email
- 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 -
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.).
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.