How to Configure NLog to Log to File, Database, and Send Email
Table of Contents
Introduction
This blog shows an example of how to configure NLog to log to a file, a database, and call a class.
Example requirements for logging:
- Debug, Info, Warning, Error, and Fatal level logs to a file
- Info, Warning, Error, and Fatal logs to a database
- Fatal logs send an email
Install NLog via NuGet
Type the following in the Visual Studio Package Manager Console window:
Install-Package NLog
Add NLog.config File
<?xml version="1.0" encoding="utf-8" ?>
<!--
See http://nlog-project.org/wiki/Configuration_file
for information on customizing logging rules and outputs.
-->
Data Source=databaseservername;Initial Catalog=databasename;User Id=username;Password=password;
insert into YourTableForLogging(date,level,message,machine_name, user_name, call_site,thread, exception, stacktrace) values(@time_stamp, @level, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace);
<!-- add your logging rules here -->
Using NLog in Code
At this point, the NLog configuration is ready, and you should be able to use NLog in your code.
For how to call NLog, you can reference the following article to write code in .NET. NLog will automatically handle the logging, and if you log at the Fatal level, it will call the specified class to perform the action.
How to call NLog
Conclusion
NLog is a flexible logging framework for .NET that supports multiple targets including files, databases, and email. By configuring the NLog.config file, you can easily route different log levels to different destinations.