How do I email errors logged with NLog?

Keith Beard picture Keith Beard · Jan 7, 2012 · Viewed 22k times · Source

I am using NLog for the first time, i figured out how to write to a text file, but now i want to send an email to myself. am making the assumption that when you supply SMTP credentials to NLog. The assembly calls the System.Net.Mail namespace and handles sending an email. If this is wrong please tell me. And if you have done this before i would appreciate any information on what it took you to accomplish send emails.

Below is my configuration.

    <?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" >
  <targets>
    <!--<target name="logfile" xsi:type="File" fileName="C:\Users\keithb\Desktop\TestLog.txt" />-->
    <target name="Mail" xsi:type="Mail" html="true" subject="Error Received" body="${message}"         
         to="[email protected]"
         from="[email protected]"
         Encoding="UTF8"
         smtpUsername="[email protected]"
         enableSsl="False"
         smtpPassword="pa$$word"
         smtpAuthentication="Basic"
         smtpServer="mail.someemail.com"
         smtpPort="25" />
  </targets>
  <rules>
    <!--<logger name="*" minlevel="Debug" writeTo="logfile" />-->
    <logger name="*" level="Error" writeTo="Mail" />
    <logger name="*" level="Fatal" writeTo="Mail" />
  </rules>
</nlog>

I call the error like so

Imports NLog

Public Class HandleGetRouteInfo
    Private Shared logger As Logger = LogManager.GetCurrentClassLogger()

    Public Shared Function GetRouteInfo(ByVal routeInfo As RequestGetRouteInfo) As GetRouteInfoResponse
        'TODO: Check route ID, username, password
        logger.Fatal("User" & routeInfo.UserName & "has entered the GetRouteInfo Method.")
        logger.Error("User" & routeInfo.UserName & "has entered the GetRouteInfo Method.")
        Dim str As String = logger.Name
End Function
End Class

I am trying to get it to send the error, containing message, and the things it normally logs to a file, to my email. I know how to catch exceptions and email it to myself, but i thought NLog had the capabilities to do this. Any tutorials with dead simple examples of using email functionality would work. I found a lot of things but cant get it to work. If you have done this, some sample code or explanation of what else i need to do would help. I cant figure out what it is i am doing wrong. Anyone have any ideas?

Answer

Richard picture Richard · Jan 7, 2012

Change your encoding from UTF8 to UTF-8.

Assuming there are no other errors in your SMTP settings (which is usually the cause of messages not being sent), it should work.