NLog Raygun - 如何在调用 SendInBackground 时捕获异常



我从Mindscape中分叉了NLog Raygun,以在NLog中提供更多Raygun设置。

创建一个 RaygunTarget 并需要覆盖Write方法,如下 NLog 文档 (https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target(。

要向 Raygun 发送异常,请按照以下代码操作

protected override void Write(LogEventInfo logEvent)
{
_raygunClient ??= (_raygunClient = CreateRaygunClient());
...
_raygunClient.SendInBackground(exception, tags, userCustomData);
}

SendInBackground返回一个任务,我们无法将其Write方法标记为async void,因为这不是使用async void的情况。

一切正常。我们大摇大摆地进行健康检查。我想检查 NLog Raygun 是否成功发送,但我不知道如何在 API 密钥无效的情况下SendInBackground捕获异常。我的意思是有没有更好的方法来测试这个RaygunTarget是否可以成功向Raygun发送消息?

如果我提供一个名为 ThrowOnError 的设置,并且Write方法像这样更新

protected override void Write(LogEventInfo logEvent)
{
_raygunClient ??= (_raygunClient = CreateRaygunClient());
...
var task = _raygunClient.SendInBackground(exception, tags, userCustomData);
if (_setting.ThrowOnError) task.Wait();
}

它有效,但问题是:这是这样做的好方法吗?就个人而言,我认为这不是因为它引入了基于设置的不同行为或副作用。

不是从TargetWithLayout继承,而是可以从AsyncTaskTarget继承:

protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
{
_raygunClient ??= (_raygunClient = CreateRaygunClient());
...
var userCustomData = base.GetAllProperties(logEvent);
return _raygunClient.SendInBackground(exception, tags, userCustomData);
} 

另请参阅:https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target

然后你可以使用InternalLogger.LogWriter挂接到 NLog InternalLogger,并转发到 healthcheck-api。

有计划改进NLog 5.0的API,以便可以订阅InternalLogger-Event,也可以获得更多上下文详细信息。如目标名称,目标类型等。另请参阅:https://github.com/NLog/NLog/issues/3350

最新更新