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.
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.
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="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>
Here is another example of SmtpAppender with custom subjects.
You can download it from Nuget
Source code and example
Because the previous answeres that suggests to use NuGet version of SmtpAppenderWithSubjectLayout needs log4net version > 1.2.1, I've used the NuGet source code but modified to use the 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());
}
}