如何为生成的电子邮件主题指定布局和conversionPattern?
BufferSize需要小于或等于1,因此不会发生缓冲。
答案 0 :(得分:15)
CodeProject文章log4net NonBufferedSmtpAppenderWithSubjectLayout看起来很有希望。
通过继承所需的基本appender(在我的情况下为SmtpPickupDirAppender)并添加ILayout属性,可以在Append方法中更改Subject。
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>
答案 1 :(得分:1)
Here is另一个带自定义主题的SmtpAppender示例。
答案 2 :(得分:1)
您可以从Nuget
下载答案 3 :(得分:0)
因为之前的回答建议使用NuGet版本的SmtpAppenderWithSubjectLayout需要log4net版本&gt; 1.2.1,我使用了NuGet源代码,但修改后使用了log4net 1.2.1
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());
}
}