【发布时间】:2017-05-23 04:08:22
【问题描述】:
当前在 Azure 中,当 WebJob 引发异常时,异常会被JobHost(不知何故)捕获和处理,然后将异常记录到仪表板,该仪表板可通过托管 Web 作业的 Web 应用的刀片提供.有什么方法可以拦截错误处理或覆盖它,以便我可以插入我的 Application Insights 实例?
【问题讨论】:
标签: c# azure azure-webjobs azure-application-insights
当前在 Azure 中,当 WebJob 引发异常时,异常会被JobHost(不知何故)捕获和处理,然后将异常记录到仪表板,该仪表板可通过托管 Web 作业的 Web 应用的刀片提供.有什么方法可以拦截错误处理或覆盖它,以便我可以插入我的 Application Insights 实例?
【问题讨论】:
标签: c# azure azure-webjobs azure-application-insights
您可以使用Azure WebJobs SDK Extensions:有一个ErrorTrigger,以便您可以使用拦截未处理的异常:
public class UnhandledErrorTrigger : IDisposable
{
private readonly TelemetryClient _telemetryClient;
public UnhandledErrorTrigger(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
public void UnHandledException([ErrorTrigger("0:01:00", 1)] TraceFilter filter, TextWriter log)
{
foreach (var traceEvent in filter.Events)
{
_telemetryClient.TrackException(traceEvent.Exception);
}
// log the last detailed errors to the Dashboard
log.WriteLine(filter.GetDetailedMessage(1));
}
public void Dispose()
{
_telemetryClient.Flush();
}
}
要注册错误扩展,请在您的启动代码中调用config.UseCore():
private static void Main()
{
var config = new JobHostConfiguration();
config.UseCore();
...
new JobHost(config).RunAndBlock();
}
因此,如果您使用的是 IoC 容器,则可以轻松注入 TelemetryClient。要为网络作业配置作业激活器,您可以查看这篇文章:
【讨论】:
查看一些 azure 文档 here。您可以将处理程序附加到 AppDomain 处理未知异常(取自上面的链接):
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// ...
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
ExceptionTelemetry excTelemetry = new ExceptionTelemetry((Exception)e.ExceptionObject);
excTelemetry.SeverityLevel = SeverityLevel.Critical;
excTelemetry.HandledAt = ExceptionHandledAt.Unhandled;
telemetryClient.TrackException(excTelemetry);
telemetryClient.Flush();
}
【讨论】: