Search code examples
c#log4netlog4net-configurationlog4net-appendersmtpappender

extend log4net SmtpAppender for dynamic To email address


Ok. I have created custom SmtpAppender to use dynamic To email address.

Using sample project given with Log4net - I have managed to use dynamic email address as below

log4net.ThreadContext.Properties["ToProperty"] =  "swapneel@stackoverlfow.com";

and in my custom SMTPAppender

        string mailMessageTo;
        if (ToProperty == null)
        {
            mailMessageTo = "DoNotReply@StaockOverlfow.com"            }
        else
        {
            var subjectWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
            ToProperty.Format(subjectWriter, loggingEvent);
            mailMessageTo = subjectWriter.ToString();
        }

this code is working in sample application but when I am trying to use it in our "Project" not working for some reason.

I have 2 appenders in Log4net.config. EventLog is working as expected but CustomSmtpAppender is not sending any emails. Any direction to resolve this issue.

1] <appender name ="EmailLogAppender1" type ="MY.Company.ProjectName.Appenders.CustomSmtpAppender, 
    TRS">


2] <appender name ="EventLogAppender" type="log4net.Appender.EventLogAppender" >

Solution

  • I enabled log4net internal debugging and could see what was causing problem.

    Add this to your Web.Config:
    
     <appSettings>
      <add key="log4net.Internal.Debug" value="true" />
     </appSettings>
     <system.diagnostics>
      <trace autoflush="true">
       <listeners>
        <add
         name="textWriterTraceListener"
         type="System.Diagnostics.TextWriterTraceListener"
         initializeData="c:\\log4net.txt" />
       </listeners>
      </trace>
     </system.diagnostics>