OpenTracing Instrumentation for C#

This article describes how to automatically extract traces from your C#-based application with OpenTracing instrumentation.

OpenTracing and Jaeger

OpenTracing is an API standard of instrumentation for distributed tracing. Jaeger is one implementation of that standard and our most recommended practice for C#. It has a set of libraries and tools to provide open source implementation for distributed tracing

Requirements

Add the following packages to your solution:

  • OpenTracing.Contrib.NetCore
  • OpenTracing
  • Jaeger

Examples

To see an actual example, head to our examples repository.

Auto instrument your C# code

To auto instrument your C# application, add the code snippet below to your Startup.cs file.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddOpenTracing();

            services.AddSingleton<ITracer>(serviceProvider =>
            {
                string serviceName = serviceProvider.GetRequiredService<IWebHostEnvironment>().ApplicationName;
                string hostName = <<JAEGER_AGENT_HOST>>;
                var tracer =
                    new Tracer.Builder(serviceName)
                        .WithSampler(new ConstSampler(true))
                        .WithReporter(new RemoteReporter.Builder().WithSender(
                            new UdpSender(hostName, 6831, 0)).Build())
                        .Build();
                    GlobalTracer.Register(tracer);

                    return tracer;
                }
            );

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseStaticFiles();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }

Within the snippet:

  • Replace <<JAEGER_AGENT_HOST>> with the host address of your Jaeger agent: Use localhost if it’s on the same machine.
  • For a Kubernetes deployment, use Environment.GetEnvironmentVariable(Jaeger.Configuration. JaegerAgentHost) and make sure your application deployment contains the environment variables as shown in the Kubernetes reference, below.
Kubernetes Reference

If you are deploying your application on Kubernetes, first deploy Jaeger/OpenTelemetry collector and agents. Then add the following environment variables to your application containers:

 env:
 - name: JAEGER_AGENT_HOST
   valueFrom:
     fieldRef:
       fieldPath: status.hostIP
 - name: JAEGER_AGENT_PORT
   value: "6831"