本文介绍了使用自定义主题配置或扩展log4net SmtpAppender的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为生成的电子邮件主题指定布局和conversionPattern?

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

BufferSize必须小于或等于1,这样就不会发生缓冲.

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

推荐答案

CodeProject文章 log4net NonBufferedSmtpAppenderWithSubjectLayout 看起来很有希望.

The CodeProject article log4net NonBufferedSmtpAppenderWithSubjectLayout looks promising.

通过继承所需的基本附加程序(在我的情况下为SmtpPickupDirAppender)并添加ILayout属性,可以在Append方法中更改Subject.

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);
    }
}

然后可以通过指定subjectLayout属性以覆盖默认主题来对其进行配置.

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>

这篇关于使用自定义主题配置或扩展log4net SmtpAppender的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:36