Azure Functions的全局异常处理程序

时间:2019-05-09 01:46:01

标签: azure-functions

是否可以为Azure Functions .Net C#项目提供全局异常处理程序?

我们希望有一个集中的位置将异常记录到Rollbar。

2 个答案:

答案 0 :(得分:1)

此功能暂时不可用,您可以转到feedback page对该功能进行投票以表明您的请求。

不过,您仍然可以将Azure Function与Application Insights结合使用,有关详细信息,请参考以下文档:Monitor Azure Functions

答案 1 :(得分:0)

我也在等待测试功能,但是现在,我已经写了我的方面(AOP)用于日志记录/异常处理。我有很多功能,但没有编写单个try-catch进行异常处理。

我将MrAdvice用于AOP

尊重

public class LoggerAspectAttribute : Attribute, IMethodAsyncAdvice
{
    public async Task Advise(MethodAsyncAdviceContext context)
    {
        ILog log = LogManager.GetLogger();
        RequestTelemetry requestTelemetry = new RequestTelemetry { Name = context.TargetType.Name };
        IOperationHolder<RequestTelemetry> operation = log.TelemetryClient.StartOperation(requestTelemetry);
        operation.Telemetry.Success = true;
        log.Info($"{context.TargetType.Name} trigger");

        try
        {
            await context.ProceedAsync(); // this calls the original method
        }
        catch (Exception ex)
        {
            operation.Telemetry.Success = false;
            log.Error(ex.Message, ex);
            throw;
        }
        finally
        {
            log.Info($"{context.TargetType.Name} completed.");
            log.TelemetryClient.StopOperation(operation);
        }
    }
}

功能

public static class AlertFunction
{
    [LoggerAspect]
    [FunctionName("AlertFunction")]
    public static async Task Run([EventHubTrigger("%AlertEventHub%", Connection = "AlertEventHubConnection", ConsumerGroup = "%AlertEventHubConsumerGroup%")]EventData eventMessage,
        [Inject]IEventService eventService, [Inject]ILog log)
    {
        log.Verbose($"Event PartitionKey {eventMessage.PartitionKey}, Offset {eventMessage.Offset} and SequenceNumber {eventMessage.SequenceNumber}");
        string message = Encoding.UTF8.GetString(eventMessage.GetBytes());
        log.Verbose(message);
        await eventService.FilterAlertEventAsync(message);
    }
}

希望它会给您一些想法!