Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Activity.Current null in isolated Azure Function v4 in .NET 6 #914

Closed
debasish-das-it opened this issue May 27, 2022 · 21 comments
Closed

Activity.Current null in isolated Azure Function v4 in .NET 6 #914

debasish-das-it opened this issue May 27, 2022 · 21 comments
Labels
enhancement New feature or request logging

Comments

@debasish-das-it
Copy link

debasish-das-it commented May 27, 2022

Activity.Current appears null in isolated Azure Function v4 in .NET 6. can some one help me to fix this issue.

Following my project .csproj content.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <AzureFunctionsVersion>v4</AzureFunctionsVersion> <OutputType>Exe</OutputType> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Remove="Clients\**" /> <EmbeddedResource Remove="Clients\**" /> <None Remove="Clients\**" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.3.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" /> <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" /> <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi" Version="1.3.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> </ItemGroup> <ItemGroup> <None Update="host.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="local.settings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>Never</CopyToPublishDirectory> </None> <None Update="swagger.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" /> </ItemGroup> </Project>

@ghost ghost assigned kashimiz May 27, 2022
@debasish-das-it
Copy link
Author

Any one faced this issue?

@Ved2806 Ved2806 self-assigned this May 31, 2022
@Ved2806
Copy link

Ved2806 commented May 31, 2022

Hi @debasish-das-it Thank you for the feedback, we will discuss this issue internally and let you know about the findings soon!

@debasish-das-it
Copy link
Author

Thanks @Ved2806

@kshyju
Copy link
Member

kshyju commented May 31, 2022

@debasish-das-it Could you share the relevant part of the code where you are getting this issue?

@debasish-das-it
Copy link
Author

debasish-das-it commented May 31, 2022

@debasish-das-it Could you share the relevant part of the code where you are getting this issue?

hello @kshyju I am facing issue in the line with var correlation_id = Activity.Current.RootId; of the code. i get null for Activity.Current.
public class CommandProcessor
{
private readonly ILogger _logger;
private readonly IEndpointProcessor endpointProcessor;

    public CommandProcessor(ILogger<CommandProcessor> logger, 
        IEndpointProcessor endpointProcessor)
    {
        _logger = logger;
        this.endpointProcessor = endpointProcessor;
    }

    [Function("commands")]
    [OpenApiOperation(operationId: "commands")]
    [OpenApiResponseWithBody(statusCode: HttpStatusCode.Accepted, contentType: "text/plain", bodyType: typeof(string), Description = "OK response")]
    public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
    {
        try
        {
            var x =  context.GetLogger("commands");
            var correlation_id = Activity.Current.RootId;
            _logger.LogInformation("C# HTTP trigger function processed a request. test logged");

            string? jsonPayload = req.ReadAsStringAsync().Result;
            if (string.IsNullOrEmpty(jsonPayload))
            {
                _logger.LogError("Command Not Valid!");
                throw new Exception();
            }
            var payload = new object(); // payload for processing.
            await endpointProcessor.Execute(payload, req.Url);

            _logger.LogInformation("Command processed successfully!");
        }            
        catch(Exception ex)
        {
            _logger.LogError("", ex);
        }
    }

}

@kshyju kshyju transferred this issue from Azure/azure-functions-host May 31, 2022
@fabiocav fabiocav added enhancement New feature or request and removed Needs: Triage (Functions) labels Jun 1, 2022
@fabiocav
Copy link
Member

fabiocav commented Jun 1, 2022

This should be addressed.

Notes for the logic:

  • If the trace context passed into the worker is populated with a parent ID, we should reuse that ID for the activity.
  • Otherwise; an activity should be created using the invocation ID.

@debasish-das-it
Copy link
Author

@fabiocav Not sure how to achieve that.

@debasish-das-it
Copy link
Author

Any Update on this?

@getsetcode
Copy link

We have the same problem here. CosmosDbTrigger and trying to write telemetry using TelemetryClient. By default any custom events or exceptions we're writing don't have operation context, and we can't add explicitly because in the code Activity.Current is null. Currently exploring work-around by wrapping the function code in a new System.Diagnostics.Activity, but it'd be good to know the correct approach.

@RohitRanjanMS
Copy link
Member

RohitRanjanMS commented Jun 10, 2022

@debasish-das-it you can start an activity by using the traceparent form the context.

string traceparent = "get the traceparent from TraceContext.Attributes";
Activity activity = activitySource.StartActivity("your activity", ActivityKind.Internal, traceparent);

@debasish-das-it
Copy link
Author

@getsetcode. can you please share the working approach code.

@sahayaarockiamary
Copy link

@debasish-das-it I am also facing this issue. Did you find any solution to resolve this?

@jviau
Copy link
Contributor

jviau commented Aug 15, 2022

General advice, whether this is a bug or not, always check for null on Activity.Current. As an optimization, activities are only created if someone is actively listening to them. In the case an activity source has 0 listeners, Activity.Current can be null.

See here

@lufthavn
Copy link

I'm also experiencing this with a ServiceBusTrigger on a brand new .NET isolated v4 function.

Our basic setup setup is API -> topic -> function #1 -> queue -> function 2. In application insights, I get telemetry up to and including function #1. The subsequent telemetry in the entire operation is not correlated. I tried debugging function #1 and can see that Activity.Current is null, which is a bit confusing since the telemetry from function #1 is correlated.
But since I can't access the Correlation ID on the current activity in function #1, I can't fetch it to set it on the message that goes to function #2.

Maybe switching to using an output binding, instead of using the Service Bus SDK will fix this? But it would be nice to be able to access the correlation ID for other purposes.

@sahayaarockiamary
Copy link

@fabiocav Any update on when the development will be complete and we can refer Activity.Current in Azure Functions?

@jviau jviau added the logging label Jan 25, 2023
@jviau
Copy link
Contributor

jviau commented Jan 25, 2023

We don't have any update for this at the moment, but we are evaluating the observability experience in Functions and will get back to this soon.

@Qualizorg
Copy link

Any news?

@jviau
Copy link
Contributor

jviau commented Apr 19, 2023

Can you try the latest AppInsights preview package? https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.ApplicationInsights/1.0.0-preview4

@Qualizorg
Copy link

Qualizorg commented May 19, 2023

Can you try the latest AppInsights preview package? https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.ApplicationInsights/1.0.0-preview4

@jviau yes, activity is created. Would be good to know if there is any roadmap for a stable version.

@jviau
Copy link
Contributor

jviau commented May 22, 2023

@Qualizorg - this would be directly related to that: Azure/azure-functions-host#9273. This is a proposal to align Functions telemetry with OpenTelemetry, and this package would fall under that work.

@jviau
Copy link
Contributor

jviau commented May 22, 2023

Closing this as it is addressed by the preview package.

@jviau jviau closed this as completed May 22, 2023
@ghost ghost locked as resolved and limited conversation to collaborators Jun 22, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request logging
Projects
None yet
Development

No branches or pull requests