Skip to content

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

NLog is a .Net Library that is very useful for logging program information. It delivers various features of logging error-free.
NLog allows users to write logs to various outputs some of the 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 – These are very detailed log messages. They are potentially of a high frequency and volume.
Debug – These are less detailed debugging messages. They will be less frequent.
Info – These are informational messages.
Warn – These warnings don’t are not displayed 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 next 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.
Nlog

2. After install is successful open your Nlog.config file for configuring how you want your logger to act 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 set up a console with colored outputs. The logger logs to the console with different color messages.
– Second target is File. I have given the path of the file. I also specified 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 *