我该如何为电子邮件主题指定布局和转换模式?
缓冲区大小需要小于等于1,以确保不发生缓冲。
我该如何为电子邮件主题指定布局和转换模式?
缓冲区大小需要小于等于1,以确保不发生缓冲。
这篇CodeProject文章log4net NonBufferedSmtpAppenderWithSubjectLayout看起来很有前途。
通过继承所需的基本appender(在我的情况下是SmtpPickupDirAppender)并添加一个ILayout属性,可以在Append方法中更改主题。
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属性来覆盖默认主题,从而进行配置。
<appender name="SmtpPickupDirAppender" type="namespace.for.SmtpSubjectLayoutPickupDirAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<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>
public class SmtpAppenderWithSubjectLayout : SmtpAppender
{
public PatternLayout SubjectLayout { get; set; }
protected override void SendBuffer(LoggingEvent[] events)
{
PrepareSubject(events);
base.SendBuffer(events);
}
protected virtual void PrepareSubject(IEnumerable<LoggingEvent> events)
{
var subjects = new List<string>();
foreach (LoggingEvent @event in events)
{
if (Evaluator.IsTriggeringEvent(@event))
{
var subjectWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
SubjectLayout.Format(subjectWriter, @event);
subjects.Add(subjectWriter.ToString());
}
}
Subject = string.Join(", ", subjects.ToArray());
}
}
public ILayout SubjectLayout
需要更改为public PatternLayout SubjectLayout
才能使其正常工作。 - TheCodeKing