Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only send one email with all the errors using NLog with Console Application using C#

Tags:

c#

nlog

I want to send only one email with all the errors I get from my C# Console Application.

I have the Targets:

<target xsi:type="File" name="HeelpAdsImport_log" fileName="${basedir}/logs/HeelpAdsImport-${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true} ${message}" />  <target name="HeelpAdsImport_patrick_email" xsi:type="Mail"         smtpServer="XXXXX"         smtpPort="25"         smtpAuthentication="Basic"         smtpUserName="YYYYYY"         smtpPassword="*ZZZZZZ"         enableSsl="false"         from="DDDDDDDDDD"         to="EEEEEEEEEEE"         layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true} ${message}"       /> 

I have an Info rule and an Error rule:

<logger name="*" minlevel="Info" writeTo="HeelpAdsImport_log" />  <logger name="*" minlevel="Error" writeTo="HeelpAdsImport_patrick_email" /> 

I have several calls in the code for each other:

logger.Log(LogLevel.Info, " ----- New Ad Success! - auto.id: " + auto.id + " | auto.plate: " + auto.plate);  logger.Log(LogLevel.Error, "| continue error #4 - auto.id: " + auto.id); 
like image 397
Patrick Avatar asked Mar 27 '14 12:03

Patrick


1 Answers

You can use a BufferingWrapper for your email target to batch multiple log entries into one email. It supports batching for a specified span of time (set flushTimeout in milliseconds) and/or for a specified number of log entries (set bufferSize to the number of entries).

Edit: Wrap your current target inside a <target type="BufferingWrapper"> like so:

<target xsi:type="BufferingWrapper"           name="MailBuffer"           slidingTimeout="false"           bufferSize="100"           flushTimeout="-1">     <target name="HeelpAdsImport_patrick_email" xsi:type="Mail"             smtpServer="XXXXX"             smtpPort="25"             smtpAuthentication="Basic"             smtpUserName="YYYYYY"             smtpPassword="*ZZZZZZ"             enableSsl="false"             from="DDDDDDDDDD"             to="EEEEEEEEEEE"             layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true} ${message}${newline}"           /> </target> 

Edit 2: Do you call LogManager.Flush() before exiting your program?

Edit 3: The ${newline} layout renderer should produce a line break in your email (at the end of the layout attribute above).

like image 96
andyp Avatar answered Sep 21 '22 08:09

andyp