简体   繁体   中英

Azure Functions: Have a CorrelationId between Http Trigger and Blob Trigger to follow a request

I want to have a CorrelationId to be able to follow a request from Http Trigger to Blob Trigger in Application insights.

I am creating a CorrelationId in Http Trigger function and want to track same in the blob trigger.

Here is my Http Trigger function:

[FunctionName(nameof(ReceiveEvent))]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Inject] ILoggingService loggingService,
            [Inject] IProvideCorrelationIds correlationIds,
            [Inject] IEventMapper eventMapper,
            [Inject] IEventValidator eventValidator,
            [Inject] IEventHandler<ResultDto, Messages.Events.Event> eventHandler)
        {
            var logger = new Logger(loggingService);

            try
            {
                IActionResult actionResult = null;

                correlationIds.CorrelationId = Guid.NewGuid().ToString();

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

                logger.Info($"Event request received");

                var @event = eventMapper.Map(requestBody);

                if (eventValidator.Validate(req, @event, logger, ref actionResult))
                {
                    var response = await eventHandler.HandleAsync(@event, logger);
                    actionResult = new OkObjectResult(response);
                }
                return actionResult;
            }
            catch (Exception ex)
            {
                logger.Error($"Exception while processing {nameof(ReceiveEvent)}", ex,
                  nameof(ReceiveEvent));

                throw;
            }
        }

CorrelationId Provider:

public class CorrelationIdProvider: IProvideCorrelationIds
    {
        private static readonly AsyncLocal<string> AsyncLocalCorrelationId = new AsyncLocal<string>();

        public string CorrelationId
        {
            get => AsyncLocalCorrelationId.Value;
            set => AsyncLocalCorrelationId.Value = value;
        }
    }

Blob Trigger Function:

[FunctionName(nameof(ProcessEvent))]
        public static async Task Run([BlobTrigger(BlobStorageContainer.Name + "/{name}",
            Connection = "AzureWebJobsStorage")]
            Stream eventBlob, string name,
            [Inject] ILoggingService loggingService,
            [Inject] IEventProcessorService eventProcessor,
            [Inject] IBlobClient blobClient)
        {
            var logger = new Logger(loggingService);
            try
            {
                logger.Info($"Starting blob job tracker for file name {name}",
                    nameof(ProcessEvent));

                //correlationIds.CorrelationId = correlationId;

                var eventContent = eventBlob.ReadAsString();

                var result = await eventProcessor.HandleProcessor(eventContent, logger);

                if (result)
                {
                    await blobClient.DeleteBlobAsync(BlobStorageContainer.Name, name);
                    logger.Info($"Blob deleted successfully file name: {name}");
                }
                else
                {
                    logger.Warning($"Unable to process blob job for file with name: {name}");
                }
            }
            catch (Exception ex)
            {
                logger.Error($"Unable to process blob job for file with name: {name}", ex,
                    nameof(ProcessEvent));
            }
        }

What are the changes I need to do to get CorrelationId in Blob Trigger?

You can put the two trigger in the same class, use below code you can get id from http trigger:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp86
{
    public class CorrelationIdProvider
    {
        public string id;
        public string CorrelationId
        {
            get { return id; }
            set { id = value; }
        }
    }

    public static class Function1
    {
        public static string id;
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run1(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            CorrelationIdProvider cp = new CorrelationIdProvider();
            cp.CorrelationId = Guid.NewGuid().ToString();
            log.LogInformation(cp.CorrelationId);
            id = cp.CorrelationId;

            return new OkObjectResult(cp.CorrelationId);
        }
        [FunctionName("Function2")]
        public static async Task<IActionResult> Run2(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            CorrelationIdProvider cp = new CorrelationIdProvider();
            cp.CorrelationId = id;
            log.LogInformation(cp.CorrelationId);

            return new OkObjectResult(cp.CorrelationId);
        }
    }
}

My second trigger is http trigger, you can change it to blob trigger.:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM