Configure or extend log4net SmtpAppender with custom subjects

Daniel Ballinger picture Daniel Ballinger · Oct 10, 2010 · Viewed 8.2k times · Source

How can I specify a layout and conversionPattern for the resulting emails subject?

The BufferSize will need to be less than or equal to 1 so no buffering will occur.

Answer

Daniel Ballinger picture Daniel Ballinger · Oct 10, 2010

The CodeProject article log4net NonBufferedSmtpAppenderWithSubjectLayout looks promising.


By inheriting from the required base appender (SmtpPickupDirAppender in my case) and adding a ILayout property it is possible to change the Subject in the Append method.

public class SmtpSubjectLayoutPickupDirAppender : log4net.Appender.SmtpPickupDirAppender
{
    public SmtpSubjectLayoutPickupDirAppender()
        : base()
    {

    }

    public ILayout SubjectLayout
    {
        get;
        set;
    }

    protected override void Append(log4net.Core.LoggingEvent loggingEvent)
    {
        if (this.BufferSize <= 1 && this.SubjectLayout != null)
        {
            StringWriter subjectWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
            this.SubjectLayout.Format(subjectWriter, loggingEvent);
            this.Subject = subjectWriter.ToString();
        }

        base.Append(loggingEvent);
    }
}

This can then be configured by specifying a subjectLayout property to override the default subject.

<appender name="SmtpPickupDirAppender" type="namespace.for.SmtpSubjectLayoutPickupDirAppender">
    <to value="[email protected]" />
    <from value="[email protected]" />
    <subject value="test logging message" />

    <subjectLayout type="log4net.Layout.PatternLayout, log4net">
        <conversionPattern value="Logging message - %message"/>
    </subjectLayout>

    <pickupDir value="C:\SmtpPickup" />
    <bufferSize value="1" />
    <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>