Add a custom attribute in traces from opentelemetry in .NET core 3.1

584 Views Asked by At

I was looking for adding custom attribute in the traces of opentelemetry.I want to add the session values like unique Id as the custom attribute to track each traces from each user.But in startup I am unable to access the Session.Finally my question is, Why I can't access session in Startup? If not accessible measns What are the way to accomplish my requirements which are mentioned above in bold letters in opentelemetry?

1

There are 1 best solutions below

1
Jalpa Panchal On

In ASP.NET Core, the Startup class configures services and the app's request pipeline. The session is not accessible in Startup because it's not set up at that point. Sessions are typically established once the request pipeline is running, which is well after the Startup configuration is complete.

The session state is established within the context of an HTTP request. During the startup configuration, the application is setting up how it will handle requests, but no request has been made yet.

However, to add custom attributes like a unique user identifier to OpenTelemetry traces, you can follow these steps:

1)Create a custom middleware that runs after the session has been established. In this middleware, you can access the session values and set the custom attributes.

2)Use a telemetry initializer that can access the HttpContext and, by extension, the session state to enrich the telemetry with the session information.

3)If you're using MVC, you could also use an action filter to add the session information to the telemetry. This would be done in the context of an action execution where session data is available.

You could refer this document which will help you understand how to manage session state :

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-7.0