Home > Programming > Email Errors with log4net

Email Errors with log4net

On a project I have been working on I was having a terrible time getting errors from the client.  There were a plethora of database errors that I could not get to replicate on my local machine.  Simple features like adding an object to the database or editing that object to the database would error.  What is worse is that the client would not properly transcribe the error message for my debugging purposes.

To alleviate this pain I used log4net to send all errors to an email address.  This way any errors that occur within the system can be sent directly to me, without user interaction, so I might investigate without the need for a middleman.  The configuration was quite simple.

Within app.config:

    <appender name="smtpAppender" type="log4net.Appender.SmtpAppender">
      <to value="[To address]" />
      <from value="[From address]" />
      <subject value="Error" />
      <authentication value="basic" />
      <smtpHost value="[SMTP server]" />
      <username value="[SMTP username]" />
      <password value="[SMTP password]" />
      <port value="[SMTP port]" />
      <bufferSize value="10" />
      <lossy value="true" />
      <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="ERROR"/>
      </evaluator>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
      </layout>
    </appender>

This creates an appender that will send an email to the desired address with the proper smtp settings.  Once the appender is created you need to create a logger that uses the appender.

    <logger name="error-logger" additivity="false">
         <level value="ERROR" />
         <appender-ref ref="smtpAppender" /> 
    </logger>

Then whenever you want to send an error via email you just log the error as an error using the error-logger logger. This will send an email.

Personally I like giving the option to send in case the user knows what went wrong to save on spam but it isn’t a requirement. This set up worked nicely for me.

Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.