Skip to content

How to implement logging in database table and log file using NLog in C#

NLog is a .Net Library which is very useful for logging program information. It delivers various features of logging error free.
NLog allows users to write the logs to various outputs some of most helpful are:

  • a File
  • text console
  • email message
  • database
  • event log
  • and many more

And the log levels in NLog are classified into:

Trace – Very detailed log messages, potentially of a high frequency and volume
Debug -Less detailed and/or less frequent debugging messages
Info – Informational messages
Warn – Warnings which don’t appear to the user of the application
Error – Error messages
Fatal – Fatal error messages. After a fatal error, the application usually terminates.

This posts only tries to focus on logging in the text file, console application and database.
To do so follow the following steps:

  1. To implement NLog into your .net application you have to first install NLog in your application via Nuget Package.  Install NLog and NLog configuration in your required .net application.

Nlog2. After install is successful open your Nlog.config file for configuring how you want your logger to perform in your application.

First Set The rules in your nlog: (What levels of outputs you want to use in your application log- In my case i am using trace for all)

rulesConfig

Then Set the Target for your nlog logger: ( what types of outputs you want to use – In my case i am writing outputs in console, file and database )

target

(For detailed logging rule go to: https://github.com/nlog/nlog/wiki/Configuration-file)

– In my first target i have setup console with colored outputs — the logger logs to the console with different color messages
– Second target is File: where i have given the path of the file and up to what level the messages should be logged.
– Third is the Database – which consists of insert statement and connection strings for the database .. log table must be created manually in your database before you start using nlog

3. In your application

Import N Log :

using NLog;

Declare NLog:

static readonly Logger Log = LogManager.GetCurrentClassLogger();

Now you are ready to start logging:

Log.Warn(“Processing Warnings…..”);
Log.Info(“Processing Info”);
Log.Error(srException, “Error message…”);

 

Enjoy coding…  please comment to appreciate if you find this post helpful or your useful feedbacks are mostly welcome…

feel free to share

Reference: Introduction to NLog - Code Project
Leave a Reply

Your email address will not be published. Required fields are marked *