【发布时间】:2019-10-27 20:42:19
【问题描述】:
我想知道是否有办法在带有 NLog 的 .net core web api 中使用带有未处理异常的事件属性?
这是我的代码示例
API 控制器操作
[HttpGet("ThrowError")]
public void ThrowError()
{
throw new Exception("My Test Exception");
}
Nlog.config 目标
<target xsi:type="Mail"
name="mailserver1"
html="true"
replaceNewlineWithBrTagInHtml="true"
encoding="UTF-8"
subject="Attention Error!!!"
body="MyValue: ${event-properties:item=MyValue} ${newline} <strong>Date:</strong> ${date} ${newline} <strong>Message:</strong> ${message} ${newline} <strong>Exception:</strong> ${exception:tostring}"
to=""
from=""
smtpServer=""
smtpUsername=""
smtpPort=""
enableSsl=""
smtpAuthentication=""
smtpPassword=""/>
正如您在电子邮件正文属性中看到的,我的事件属性称为 MyValue。我可以使用以下代码轻松设置我的值以处理异常
LogEventInfo theEvent = new LogEventInfo(NLog.LogLevel.Error, "", "Pass my custom value");
theEvent.Properties["MyValue"] = "My custom string";
logger.Log(theEvent);
但是,对于意外/未处理的错误(例如,在上述示例代码中调用 ThrowError API 操作),NLog 会自动发送电子邮件,而我没有设置事件属性值。
我尝试了如下中间件代码,但在调用中间件代码之前记录了异常
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = errorFeature.Error;
var serviceProvider = app.ApplicationServices;
var logger = LogManager.GetCurrentClassLogger();
LogEventInfo theEvent = new LogEventInfo(NLog.LogLevel.Error, "", exception.StackTrace);
theEvent.Properties["MyValue"] = "My custom string";
logger.Log(theEvent);
});
});
不胜感激。谢谢。
【问题讨论】:
标签: c# .net-core asp.net-core-webapi nlog