[英]Configure NLog programmatically, web.config
我的web.config中有以下Nlog配置部分(已修改为仅显示相关信息)
<nlog>
<targets async="true">
<target name="mail" type="Mail"
body="${date:format=yyyy-MM-dd HH\:mm\:ss} - ${level} [${logger}] - ${message} ${newline}${newline}${event-context:item=OtherInfo}${newline}${newline}${exception:maxInnerExceptionLevel=2:format=ToString}${newline}${newline}"
subject="[${machinename}] ${logger}"
to="mail@domain.com" encoding="UTF-8" from="anotheremail@domain.com" smtpServer="" enableSsl="true" smtpAuthentication="Basic"
/>
</targets>
<targets>
<target name="mailsync" type="Mail" body="${date:format=yyyy-MM-dd HH\:mm\:ss} - ${level} [${logger}] - ${message} ${newline}${newline}${event-context:item=OtherInfo}${newline}${newline}${exception:maxInnerExceptionLevel=2:format=ToString}${newline}${newline}" subject="[${machinename}] ${logger}"
to="mail@domain.com" encoding="UTF-8" from="anotheremail@domain.com" smtpServer="" enableSsl="true" smtpAuthentication="Basic"
/>
</targets>
<rules>
<logger name="*" level="Error" writeTo="mail" />
</rules>
</nlog>
我正在通过Application_Start中的代码更新配置,
var config = LogManager.Configuration;
const string targetName = "mail";
var wrapper = (AsyncTargetWrapper) config.FindTargetByName(targetName);
wrapper.WrappedTarget.SmtpServer = "hostname";
wrapper.WrappedTarget.SmtpUserName = "username";
wrapper.WrappedTarget.SmtpPassword = "password";
config.RemoveTarget(targetName);
config.AddTarget(targetName, wrapper);
LogManager.Configuration = config;
但是,当我记录任何错误时,不会发送电子邮件。 我还有一个其他文件目标(代码片段中未显示),其中包含错误消息。 那告诉我错误正在被记录,但是不知何故没有通过电子邮件发送。
如果不是通过代码更新配置,而是通过硬编码web.config中的值,则将发送电子邮件。 我已验证通过代码使用的smtp值有效。
我确实在SO上搜索了许多类似的问题,但是我还没有找到提到适合我的解决方案的问题。
编辑:
根据Xharze的回答,我启用了异常,内部日志记录,并且在进行更改后也输出了目标的值。 内部日志显示有关MailAdrress
格式错误的异常。 因此,我检查了接受电子邮件地址的所有目标值,然后发现了问题。 目标的from
属性接受一个电子邮件地址,而我为其提供了显示名称!
您可以尝试启用抛出异常和内部日志并将其发布吗? 它可能会提供更多信息。 参见github.com/NLog/NLog/wiki/Logging-troubleshooting。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.