Search code examples
azure-functionsaopazure-application-insights

Aspect in Azure Function for Application Insight Correlation


I have written many Azure functions (Http, ServiceBus, EventHub and CosmosDB trigger). For application logging, I have implemented my own Logger class, which create TelemetryClient object to sink log in Application Insight.

I can see all my trace, exception and Exception log in Application Insight but I can't correlate without OperationName and OperationId

Now I'm manually calling TelemetryClient StartOperation and StopOperation to create OperationId.

AzureFunction

[FunctionName("AlertEventStoreFunction")]
    public static async Task Run([EventHubTrigger("%AlertEventHub%", Connection = "AlertEventHubConnection", ConsumerGroup = "cg1")]EventData eventMessage,
        [Inject]IEventService eventService, [Inject]ILog log)
    {
        log.StartOperation("AlertEventStoreFunction");
        try
        {                
            log.Info($"Event PartitionKey {eventMessage.PartitionKey}, Offset {eventMessage.Offset} and SequenceNumber {eventMessage.SequenceNumber}");
            string message = Encoding.UTF8.GetString(eventMessage.GetBytes());
            log.Verbose(message);
            await eventService.SaveAlertEventAsync(message);
        }
        catch (Exception ex)
        {
            log.Error(ex.Message, ex);
        }
        finally
        {
            log.StopOperation();
        }
    }

Logger Class

public class Log : ILog
{
    private static TelemetryClient telemetryClient = new TelemetryClient() { InstrumentationKey = ConfigurationManager.AppSettings["InstrumentationKey"] };
    private IOperationHolder<RequestTelemetry> operation;
    private bool status = true;

    public TelemetryClient TelemetryClient
    {
        get
        {
            return telemetryClient;
        }
    }

    /// <summary>
    /// This method will start new session for particular request, we can correlate each log by Operation_Id
    /// </summary>
    /// <param name="functionName">function name</param>
    public void StartOperation(string functionName)
    {
        RequestTelemetry requestTelemetry = new RequestTelemetry { Name = functionName };
        this.operation = telemetryClient.StartOperation(requestTelemetry);
        telemetryClient.TrackTrace($"{functionName} trigger");
    }

    /// <summary>
    /// this method will close session
    /// </summary>
    public void StopOperation()
    {
        telemetryClient.StopOperation(this.operation);
        this.operation.Telemetry.Success = status;
    }

    public void Error(string message, Exception ex = null)
    {
        telemetryClient.TrackTrace(message, SeverityLevel.Error);
        if (ex != null)
            telemetryClient.TrackException(ex);
        status = false;
    }

    public void Info(string message)
    {
        telemetryClient.TrackTrace(message, SeverityLevel.Information);
    }

    public void Verbose(string message)
    {
        telemetryClient.TrackTrace(message, SeverityLevel.Verbose);
    }

    public void Warning(string message)
    {
        telemetryClient.TrackTrace(message, SeverityLevel.Warning);
    }
}

I don't want to put try-catch block in every function so I Created Aspect (AOP) using postsharp, it was working as expected but free version allows only on 10 functions.

I don't see any other good replacement of postsharp (tried sprint.net, Cauldron.Interception etc.)

Instead of this code, what I can do to create correlation (OperationId)?


Solution

  • I got Postsharp alternate "MrAdvice", New version doesn't have any dependency

    public class LoggerAspect : Attribute, IMethodAdvice
    {
        private ILog log;
        private IOperationHolder<RequestTelemetry> operation;
    
        public void Advise(MethodAdviceContext context)
        {
            try
            {
                log = LogManager.GetLogger();
                RequestTelemetry requestTelemetry = new RequestTelemetry { Name = context.TargetType.Name };
                operation = log.TelemetryClient.StartOperation(requestTelemetry);
                operation.Telemetry.Success = true;
    
                context.Proceed(); // this calls the original method
            }
            catch (Exception ex)
            {
                operation.Telemetry.Success = false;
                log.Error(ex.Message, ex);
            }
            finally
            {
                log.TelemetryClient.StopOperation(operation);
            }
        }
    }
    

    Still open for better suggestions.