我从Mindscape派生了NLog雷枪,以便在NLog中提供更多的雷枪设置。
创建了一个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的情况。
一切都很好。我们要大摇大摆地进行Healthcheck。我想检查NLog Raygun是否发送成功,但我不知道如何捕捉SendInBackground中的异常,以防API无效。我的意思是,有没有更好的方法来测试这个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();
}它是有效的,但问题是:这是一个很好的方法吗?就我个人而言,我不认为这是因为它根据设置引入了不同的行为或副作用。
发布于 2020-02-14 04:49:28
您可以从AsyncTaskTarget继承,而不是从TargetWithLayout继承
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。
有计划改进InternalLogger 5.0的应用程序接口,这样就可以订阅InternalLogger-Event,还可以获得更多上下文详细信息。如目标名称、目标类型等参见:https://github.com/NLog/NLog/issues/3350
https://stackoverflow.com/questions/60199975
复制相似问题