6
votes

Does the Log4net SMTPAppender send email asynchronously? If it doesn't, how can I send logging emails asynchronously?

My log4net.config is:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <appender name="SMTPAppender" type="log4net.Appender.SMTPAppender">
      <authentication value="Basic" />
      <to value="xxx@xx.com" />
      <from value="yyy@xx.com" />
      <username value="yyy@xx.com" />
      <password value="yyy" />
      <subject value="xxx" />
      <smtpHost value="smtp.xx.com" />
      <lossy value="true" />
      <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="WARN" />
      </evaluator>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger %newline %message%newline%newline%newline" />
      </layout>
    </appender>
    <root>
      <level value="INFO"></level>
    </root>
    <logger name="MyLogger">
      <level value="INFO"></level>
      <appender-ref ref="SMTPAppender"></appender-ref>
    </logger>
  </log4net>
</configuration>
3

3 Answers

4
votes

You could just call the logging method asynchronously like this:

Task.Factory.StartNew(() => log.Info("Message I want to email"));

I actually got this suggestion from the following SO article:

How do I create an asynchronous wrapper for log4net?

2
votes

There is a simple workaround before the solid solution is released.

public class SmtpAsyncAppender : SmtpAppender
{
    protected override void SendEmail(string messageBody)
    {
        Task.Run(() => base.SendEmail(messageBody));
    }
}

It presumes that SmtpAppender.SendEmail is thread-safe and reenterable. It is for log4net v1.2.13.0 and there is no reason not to be in the future.

0
votes

Log4net has not built in appender that is asynchronous. If you need that functionality you need to write your own appender. Downloading the log4net source code should get you started...