目前我的应用程序使用log4net来记录错误,web.config的目的如下:
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="../../logs/gateway_%date{yyyyMMdd}.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppenderOutput" />
</root>
</log4net>
但是,客户现在希望将每个错误都通过电子邮件发送给他们。
最简单的方法是什么,你可以在web.config文件中做到吗?
答案 0 :(得分:49)
您应该使用SmtpAppender
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<smtpHost value="SMTPServer.domain.com" />
<bufferSize value="512" />
<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>
<logger name="ErrorLogger">
<level value="Error" />
<appender-ref ref="FileAppender" />
</logger>
<logger name="EmailLogger">
<level value="Error" />
<appender-ref ref="SmtpAppender" />
</logger>
为了仅针对特定错误发送电子邮件,您可以执行类似
的操作try
{
// your logic
}
catch (MySpecificException ex)
{
// I only send emails for exception of type MySpecificException
LogManager.GetLogger("EmailLogger").Error(ex);
}
catch (Exception ex)
{
// Just log to a file for the rest
LogManager.GetLogger("ErrorLogger").Error(ex);
}