Implementing LNog in .NET with a database and a file as the storage medium

We all know about logging mechanism, if you don’t know about what is exactly logging, I would like recommend you to study on it. It’s very important for every developer. There is a lot of api available for .net environment for logging, but recently I used NLog. I think it’s something very easy to use.

It supports –

And many more..

Recently I work with Database. It store log in database.

So before proceed, you need to download Nlog.

You can download it from NuGet package: http://nuget.org/List/Packages/NLog

Or you can download installer from codeplex: http://nlog.codeplex.com/releases/view/32639

It seems easier to use installer. So install it first.

click on next button.

read the license agreements and click on next buttons.

Select any, I chose complete.

If everything is fine, it will be installed.

Now open visual studio and create a console application to test it. Now right click on your project from the solution explorer and select for New Item. Select empty nlog configuration file.

This part is very important. You have to write configuration for nlog. Im using to both database and file to trace log. Here Im going to share my configuration, you can just copy and paste it in your application.


<?xml version="1.0" encoding="utf-8" ?>
 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 autoReload="true"
 internalLogLevel="Trace"
 throwExceptions="true"
 internalLogFile="${basedir}/internalLog.txt"
 internalLogToConsole="true">

<!-- define various log targets -->
 <targets>
 <!-- write logs to file -->
 <target name="file" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt" layout="${longdate} ${callsite} ${level}: ${message} ${exception:format=Message,StackTrace} ${stacktrace}" />

<!-- write log message to database -->
 <target xsi:type="Database" name="Logger" keepConnection="true"
 useTransactions="true"
 dbDatabase="Logger"
 commandText="INSERT INTO LogTable (CreateDate, Origin, LogLevel, Message, Exception, StackTrace) values (@createDate, @origin, @logLevel, @message, @exception, @stackTrace)"
 connectionString="Server=.\SQLEXPRESS;Initial Catalog=Logger;Integrated Security=True; User Id=sa;Password=sa1234">

<parameter name="@createDate" layout="${date}"/>
 <parameter name="@origin" layout="${callsite}"/>
 <parameter name="@logLevel" layout="${level}"/>
 <parameter name="@message" layout="${message}"/>
 <parameter name="@exception" layout="${exception:format=Message,StackTrace}"/>
 <parameter name="@stackTrace" layout="${stacktrace}"/>
 </target>
 </targets>
 <rules>
 <logger name="*" minlevel="Trace" writeTo="file" />
 <logger name="*" minlevel="Trace" writeTo="Logger" />
 </rules>
 </nlog>

Now you need to create database for nLog. Here is database table schema.


CREATE TABLE [dbo].[LogTable](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[CreateDate] [datetime] NULL,
[Origin] [nvarchar](50) NULL,
[LogLevel] [text] NULL,
[Message] [text] NULL,
[Exception] [text] NULL,
[StackTrace] [text] NULL,
 CONSTRAINT [PK_LogTable] 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] TEXTIMAGE_ON [PRIMARY]
GO

Now change the connectionString.

Everything is just fine. Now write a simple program and try to trace an error.


using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using NLog;

namespace NLogDemo
 {
 class Program
 {
 private static Logger logger = LogManager.GetCurrentClassLogger();

static void Main(string[] args)
 {
 logger.Debug("Dude! its all about test loggin");
 logger.Trace("Hello world");

Object obj = null;
 try
 {
 Console.WriteLine(obj.ToString());
 }
 catch (NullReferenceException e)
 {
 logger.TraceException("Exception", e);
 }

Console.ReadKey();
 }
 }
 }
 

If you run the program, everything will go fine, you will find error trace in your database table and a file placed in your solution folder>bin>debug>logs.

That’s pretty cool, huh?

Advertisements

2 Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s