我知道我参加聚会迟到了,但我遇到了类似的问题,需要我以编程方式解决它,而不是直接将它们硬编码到app.config
文件中。
当您不想通过配置文件公开您的电子邮件凭据时,这是您想要使用的方法。如果您出于任何原因想要覆盖 SmtpAppender,它也很有用。
这是 log4net appender 的设置app.config
:
<appender name="SmtpAppender" type="MyNameSpace.SmtpAppenderHelper">
<to value="sendto@company.com" />
<cc value="sendccto@company.com" />
<subject value="An Error Occured" />
<bufferSize value="1" />
<EnableSsl value="true" />
<lossy value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %date - %message%newline" />
</layout>
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>
</appender>
我的助手类:
namespace MyNameSpace
{
public class SmtpAppenderHelper : SmtpAppender
{
protected override void SendBuffer(LoggingEvent[] events)
{
// overriding the SmtpAppender so that I can add some sensitive information
this.Username = "myemailaddress@gmail.com";
this.Password = "NotSafePassword";
this.SmtpHost = "smtp.gmail.com";
this.Port = 587;
this.Authentication = SmtpAuthentication.Basic;
this.From = "myemailaddress@gmail.com";
base.SendBuffer(events);
}
}
}
您还可以创建一个SmtpAppenderHelper
类方法来帮助您修改电子邮件主题并在base.SendBuffer(events)
修改主题的方法之前触发它,如下所示:
protected virtual void prepareSubject(ICollection<LoggingEvent> events)
{
Subject = null;
foreach (LoggingEvent _event in events)
{
if (Evaluator.IsTriggeringEvent(_event))
{
string msg = _event.ExceptionObject == null ? _event.RenderedMessage : _event.ExceptionObject.Message;
Subject = string.Format("[{0}] {1}", _event.Level, msg);
break;
}
}
}
另一个关于覆盖的示例Appenders