Search code examples
c#emaillog4net

Send an Email When an Error Occurs in C# using log4net


Currently my application is using log4net to log errors, the web.config for this is as followed:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="../../logs/gateway_%date{yyyyMMdd}.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppenderOutput" />
    </root>
  </log4net>

However, the client now wants each error to be emailled to them.

What is the easiest way to do this, can you do it within the web.config file?


Solution

  • You should use SmtpAppender

    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
        <to value="[email protected]" />
        <from value="[email protected]" />
        <subject value="test logging message" />
        <smtpHost value="SMTPServer.example.com" />
        <bufferSize value="512" />
        <lossy value="true" />
        <evaluator type="log4net.Core.LevelEvaluator">
            <threshold value="WARN"/>
        </evaluator>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
        </layout>
    </appender>
    
    <logger name="ErrorLogger">
        <level value="Error" />
        <appender-ref ref="FileAppender" />
    </logger>
    <logger name="EmailLogger">
        <level value="Error" />
        <appender-ref ref="SmtpAppender" />
    </logger>
    

    In order to send emails only for an specific error you could do something like this

    try
    {
      // your logic
    }
    catch (MySpecificException ex)
    {
       // I only send emails for exception of type MySpecificException
       LogManager.GetLogger("EmailLogger").Error(ex);
    }
    catch (Exception ex)
    {
       // Just log to a file for the rest
       LogManager.GetLogger("ErrorLogger").Error(ex);
    }