NLOG Library in .NET

NLog is a .Net Library that enables you to add high-quality logs for your application.

NLog can also be downloaded using Nugget in Visual Studio.

Targets

  • Targets are used to display, store or pass log messages to another destination.
  • There are the following two kind of targets:

          Those that receive and handle the message.
          and the other that buffers or routes the message to another target.
  • So the targets can be:

          File
          Console
          DataBase
          EmailMessage
          EventLog

And many more and in this article we will see how to write the logs to a database and a file.

Layout

  • Layout is the one of the attributes of most of the targets.
  • If we don't specify a layout then there is a default layout.

    ${longdate}|${level:uppercase=true}|${logger}|${message}
  • The rules that we specify in the layout are pieces of additional information that will be sent to the target along with the log.
  • The additional information can include:

          Current date and time in various formats
          Log level
          Source Name
          Information about exceptions and much more.

Log Level

  • Each Tracing message is associated with a Log Level.

The following are the allowed log levels (in descending order).

  1. Off.
  2. Fatal.
  3. Error.
  4. Warn.
  5. Info.
  6. Debug.
  7. Trace.

So let's go ahead and create a Sample application to use NLOG.

  • We will use NLOG along with a MVC 4 application and SQL Server database.

Creating the Database to Log Errors

The following shows how to create the database to log errors:

  1. CREATE TABLE [dbo].[NLog_Error](  
  2. [Id] [int] IDENTITY(1, 1) NOT NULL,  
  3. [TimeStamp][DateTime2] NOT NULL,  
  4. [Level] [nvarchar](50) NOT NULL,  
  5. [Host] [nvarchar](maxNOT NULL,  
  6. [Type] [nvarchar](50) NOT NULL,  
  7. [Logger] [nvarchar](50) NOT NULL,  
  8. [Message] [nvarchar](maxNOT NULL,  
  9. [stacktrace] [nvarchar](maxNOT NULL,  
  10. CONSTRAINT [PK_NLogError] PRIMARY KEY CLUSTERED ([Id] ASCWITH (  
  11. PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
  12. IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
  13. ALLOW_PAGE_LOCKS = ON  
  14. ON [PRIMARY]  
  15. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
Creating a MVC 4 Application 
  • Creating an MVC application .

Solution

  • Create the configuration file for NLog as shown (NLog.config).

NLog.config

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <nlog  
  3.     xmlns="http://www.nlog-project.org/schemas/NLog.xsd"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5. autoReload="true" throwExceptions="false"  
  6. internalLogFile="C:\NLogErrors\log.txt" >  
  7.     <extensions>  
  8.         <!-- load NLog.Extended to enable ASP.NET-specific functionality -->  
  9.         <add assembly="NLog.Extended" />  
  10.     </extensions>  
  11.     <!--Define Various Log Targets-->  
  12.     <targets >  
  13.         <target name="console" xsi:type="ColoredConsole"  
  14. layout="${message}" />  
  15.         <!--Write logs to File-->  
  16.         <target name="file" xsi:type="File" fileName="C:\NLogErrors\ErrorLogFile.log"  
  17. layout="  
  18. --------------------- ${level}(${longdate})${machinename}-------------------- ${newline}  
  19. ${newline}  
  20. Exception Type:${exception:format=Type}${newline}  
  21. Exception Message:${exception:format=Message}${newline}  
  22. Stack Trace:${exception:format=Stack Trace}${newline}  
  23. Additional Info:${message}${newline}  
  24. ></target>  
  25.         <!--Write Logs to Database-->  
  26.         <target xsi:type="Database" name="db-Details">  
  27.             <!-- SQL command to be executed for each entry -->  
  28.             <commandText>INSERT INTO [NLog_Error](TimeStamp,Level,Host,Type,Logger,Message,stackTrace)  
  29. VALUES(getutcdate(),@level,@host,@type,@logger,@message,@stacktrace)</commandText>  
  30.             <!-- parameters for the command -->  
  31.             <parameter name="@level" layout="${level}" />  
  32.             <parameter name="@host" layout="${machinename}" />  
  33.             <parameter name="@type" layout="${exception:format=type}" />  
  34.             <parameter name="@logger" layout="${logger}" />  
  35.             <parameter name="@message" layout="${message}" />  
  36.             <parameter name="@stacktrace" layout="${exception:stacktrace}" />  
  37.             <!-- connection string -->  
  38.             <dbProvider>System.Data.SqlClient</dbProvider>  
  39.             <connectionString>Data Source=MachineName;Initial Catalog=MyDataBase;Integrated Security=True;</connectionString>  
  40.         </target>  
  41.     </targets>  
  42.     <!--End Targets-->  
  43.     <rules>  
  44.         <logger name="*" minlevel="trace" writeTo="file" />  
  45.         <logger name="*" minlevel="trace" writeTo="db-Details" />  
  46.     </rules>  
  47. </nlog>
LoginController 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Mvc_Security.Security;  
  7. using Mvc_Security.Models;  
  8. using System.Web.Script.Serialization;  
  9. using System.Web.Security;  
  10. using Newtonsoft.Json;  
  11. using NLog;  
  12. using System.Threading;  
  13. namespace Mvc_Security.Controllers   
  14. {  
  15.     public class LoginController: Controller   
  16.     {  
  17.         Logger loggerx = LogManager.GetCurrentClassLogger();  
  18.         // GET: /Login/  
  19.         public ActionResult Index()   
  20.         {   return View();  }  
  21.         public ActionResult Login()  
  22.         {  return View();  }  
  23.         [HttpPost]  
  24.         public ActionResult Login(User model, String returnUrl)  
  25.         {  
  26.             try   
  27.             {  
  28.                 int x = 0;  
  29.                 int y = 5;  
  30.                 int z = y / x;  
  31.             }   
  32.             catch (Exception ex)   
  33.             {  
  34.                 loggerx.ErrorException("Error occured in Login controller", ex);  
  35.                 //logger.Error(ex);  
  36.             }  
  37.         }
The following is a screenshot of the database:



The following is a screenshot of the LogFile:

Up Next
    Ebook Download
    View all
    Learn
    View all