How to config NLog to log to file, database and send email

Posted in C#, NLog, on 5/2/2015

This blog will show a example of how to config NLog so able to log to file, database and call class.

Example requirement for Logging : 

  • Debug, Info, Warning, Error, Fatal level log to file
  • Info, Warning, Error, Fatal log to database
  • Fata log send email.

1. Install NLog via Nuget

Type following at visual studio Package Manager Console window. Install-Package NLog

2. Add NLog.config file

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="" xmlns:xsi="">

  for information on customizing logging rules and outputs.
  <variable name="logDir" value="${specialfolder:folder=ApplicationData}/Log/"></variable>
  <variable name="logFormat" value="${longdate} ${callsite} ${level} ${stacktrace} ${message}"></variable>
    <target xsi:type="File" name="file" fileName="${logDir}/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=tostring}" maxArchiveFiles="1" archiveAboveSize="1000000"/>
    <target name="database" type="Database"> 
        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); 
      <parameter name="@time_stamp" layout="${longdate}"/> 
      <parameter name="@level" layout="${level}"/> 
      <parameter name="@message" layout="${message}"/> 
      <parameter name="@machinename" layout="${machinename}"/> 
      <parameter name="@user_name" layout="${windows-identity:domain=true}"/> 
      <parameter name="@call_site" layout="${callsite:filename=true}"/>
      <parameter name="@threadid" layout="${threadid}"/> 
      <parameter name="@log_exception" layout="${exception}"/> 
      <parameter name="@stacktrace" layout="${exception:stacktrace}"/>
	 <target name="sendEmail" xsi:type="MethodCall" className="yourClassForSendingEmalNamespace, thisClassAssemblyName" methodName="MethodToSendEmail">
		<parameter layout="${level}" />
		 <parameter layout="${message}" />
		 <parameter layout="${machinename}" />
		 <parameter layout="${exception}" />
		 <parameter name="stacktrace" layout="${exception:format=tostring}" />

    <!-- add your logging rules here -->
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Info" appendTo="database"/> 
<logger name="*" minlevel="Fatal" writeTo="sendEmail" />


At this point, NLog config setting is ready you should be able to use NLog at code.

For how to call NLog, you could either reference following article to write code to the .NET and, NLog should be automatically, if you're log as Fatal level, will call specific class to do thing.

How to call NLog