open-telemetry / opentelemetry-dotnet

The OpenTelemetry .NET Client
https://opentelemetry.io
Apache License 2.0
3.27k stars 769 forks source link

VB.NET Integrate Authorization token in Header #5738

Open Keerthii-r opened 4 months ago

Keerthii-r commented 4 months ago

Feature Request

Are you requesting automatic instrumentation for a framework or library? Please describe. We are using OpenTelemetry SDK

Describe the solution you'd like We followed everything as per the git link https://github.com/open-telemetry/opentelemetry-dotnet-contrib/tree/main/src/OpenTelemetry.Instrumentation.AspNet

We managed to get telemetry data through Console output, however we can't able to send data to Grafana as Token needs to be pass in header.

Code we did so far in Global.asax.vb file

Imports OpenTelemetry Imports OpenTelemetry.Exporter Imports OpenTelemetry.Metrics Imports OpenTelemetry.Resources Imports OpenTelemetry.Trace

Public Class Global_asax Inherits HttpApplication

Private _TracerProvider As TracerProvider
Private _MeterProvider As MeterProvider

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

    Dim otlpEndpoint As String = ConfigurationManager.AppSettings("OtlpEndpoint")
    Dim otlpToken As String = ConfigurationManager.AppSettings("OtlpToken")

    ' Create custom resource attributes
    Dim resourceBuilder As ResourceBuilder = ResourceBuilder.CreateDefault().
                                          AddAttributes(New Dictionary(Of String, Object) From {
                                            {"deployment.environment", "dev"},
                                            {"version", "4.1"}
                                          })

    ' Create a dictionary to hold the headers
    Dim headers As New Dictionary(Of String, String)()
    headers.Add("Authorization ", "Basic " & otlpToken)

    ' Convert the dictionary to a format acceptable by the Headers property
    Dim headersString As String = String.Join(",", headers.Select(Function(kvp) kvp.Key & "=" & kvp.Value))

    Try
        _TracerProvider = Sdk.CreateTracerProviderBuilder().
           AddAspNetInstrumentation().
           AddHttpClientInstrumentation().
           AddOtlpExporter(Function(otlpOptions)
                               otlpOptions.Endpoint = New Uri(otlpEndpoint)
                               otlpOptions.Protocol = OtlpExportProtocol.Grpc
                               otlpOptions.Headers = headersString
                           End Function).
           AddConsoleExporter(Function(options)
                                  options.Targets = ConsoleExporterOutputTargets.Debug
                              End Function).
           SetResourceBuilder(resourceBuilder).
           Build()

        _MeterProvider = Sdk.CreateMeterProviderBuilder().
           AddAspNetInstrumentation().
           AddHttpClientInstrumentation().
           AddOtlpExporter(Function(otlpOptions)
                               otlpOptions.Endpoint = New Uri(otlpEndpoint)
                               otlpOptions.Protocol = OtlpExportProtocol.Grpc
                               otlpOptions.Headers = headersString
                           End Function).
           AddConsoleExporter(Function(options)
                                  options.Targets = ConsoleExporterOutputTargets.Debug
                              End Function).
           SetResourceBuilder(resourceBuilder).
           Build()

    Catch ex As Exception
        Console.WriteLine(ex.Message)

    End Try
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    _TracerProvider?.Dispose()
    _MeterProvider?.Dispose()
End Sub

End Class

Extra Notes: We need to add and remove some of the predefined attributes. And also the output of the telemetry data should be in different formats (Ex. JSON, CSV, ..)

pellared commented 4 months ago

Have you tried adding using OTEL_EXPORTER_OTLP_HEADERS env var? More:

Keerthii-r commented 4 months ago

Yes we did that too but no luck. Is there any example project available with the web.config files included.

Kielek commented 4 months ago

@matt-hensley, could you please advice?

Keerthii-r commented 4 months ago

Hi @pellared / @Kielek

I managed to fix it. Its sending my logs, metrices and traces to Grafana while testing. How ever when I published my code to IIS its not sending any. I think it may be some GRPC protocol issue. Let me know if you faces this issue before. I will post my code here so that it may be helpful for someone.

Imports OpenTelemetry Imports OpenTelemetry.Logs Imports OpenTelemetry.Exporter Imports OpenTelemetry.Metrics Imports OpenTelemetry.Resources Imports OpenTelemetry.Trace

Public Class Global_asax Inherits HttpApplication

Private _TracerProvider As TracerProvider
Private _MeterProvider As MeterProvider

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    log4net.Config.XmlConfigurator.Configure()

    Dim otlpEndpoint As String = ConfigurationManager.AppSettings("OtlpEndpoint")
    Dim otlpToken As String = ConfigurationManager.AppSettings("OtlpToken")

    ' Create custom resource attributes
    Dim resourceBuilder As ResourceBuilder = ResourceBuilder.CreateDefault().
                                          AddService(serviceName:="Your Service Name", serviceVersion:="V1.0").
                                          AddAttributes(New Dictionary(Of String, Object) From {
                                            {"deployment.environment", "dev"},
                                            {"system_name", "..."},
                                            {"team", "..."},
                                            {"version", "1.0"}
                                          })

    ' Create a dictionary to hold the headers
    Dim headers As New Dictionary(Of String, String)()
    headers.Add("Authorization ", "Basic " & otlpToken)

    ' Convert the dictionary to a format acceptable by the Headers property
    Dim headersString As String = String.Join(",", headers.Select(Function(kvp) kvp.Key & "=" & kvp.Value))

    Dim _LoggerFactory = LoggerFactory.Create(Function(builder)
                                              builder.AddOpenTelemetry(Function(logging)
                                                                           logging.AddOtlpExporter(Function(otlpOptions)
                                                                                                       otlpOptions.Endpoint = New Uri(otlpEndpoint)
                                                                                                       otlpOptions.Protocol = OtlpExportProtocol.Grpc
                                                                                                       otlpOptions.Headers = headersString
                                                                                                   End Function)
                                                                           logging.SetResourceBuilder(resourceBuilder)
                                                                       End Function)
                                          End Function)

    Dim OTELlogger = _LoggerFactory.CreateLogger(Of Logger)()
    OTELlogger.LogInformation("Information..")

    _TracerProvider = Sdk.CreateTracerProviderBuilder().
           AddAspNetInstrumentation().
           AddHttpClientInstrumentation().
           AddOtlpExporter(Function(otlpOptions)
                               otlpOptions.Endpoint = New Uri(otlpEndpoint)
                               otlpOptions.Protocol = OtlpExportProtocol.Grpc
                               otlpOptions.Headers = headersString
                           End Function).
           SetResourceBuilder(resourceBuilder).
           Build()

    _MeterProvider = Sdk.CreateMeterProviderBuilder().
           AddAspNetInstrumentation().
           AddHttpClientInstrumentation().
           AddOtlpExporter(Function(otlpOptions)
                               otlpOptions.Endpoint = New Uri(otlpEndpoint)
                               otlpOptions.Protocol = OtlpExportProtocol.Grpc
                               otlpOptions.Headers = headersString
                           End Function).
           SetResourceBuilder(resourceBuilder).
           Build()

End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    ResourceProviderConfig.Current.ResourceProvider = New APIResourceProvider()
End Sub

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    If (ConfigurationManager.AppSettings("EnableErrorPage").ToUpper = "TRUE") Then
        Server.Transfer("/ErrorPage.aspx")
    End If
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    _TracerProvider?.Dispose()
    _MeterProvider?.Dispose()
End Sub

End Class


Web.config File

vascoveigams commented 1 month ago

Is there a way to provide the header per Grpc call? What if the Auth token expires and a new token needs to be provided?

Keerthhii commented 3 weeks ago

Is there a way to provide the header per Grpc call? What if the Auth token expires and a new token needs to be provided?

Hi all the headers will be included per call. We store the token in web.config file and can be changed without need to republish the code.