Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure or extend log4net SmtpAppender with custom subjects

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.

like image 287
Daniel Ballinger Avatar asked Oct 10 '10 20:10

Daniel Ballinger


3 Answers

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>
like image 177
Daniel Ballinger Avatar answered Oct 20 '22 04:10

Daniel Ballinger


Here is another example of SmtpAppender with custom subjects.

like image 23
VladV Avatar answered Oct 20 '22 05:10

VladV


You can download it from Nuget

Source code and example

like image 21
Alexander Byndyu Avatar answered Oct 20 '22 03:10

Alexander Byndyu