Instrument your .NET application with OpenTelemetry
This walkthrough shows how to add observability to your .NET application using the OpenTelemetry .NET libraries and tools.
Feature | Supported |
---|---|
Automatic Instrumentation | Yes |
Automatic OneAgent Ingestion | Yes |
Prerequisites
- Dynatrace version 1.254+
- For tracing, W3C Trace Context is enabled
- From the Dynatrace menu, go to Settings > Preferences > OneAgent features.
- Turn on Send W3C Trace Context HTTP headers.
Choose how to ingest data into Dynatrace
OneAgent currently only ingests traces automatically. If you are recording metrics or logs, choose the OTLP export route.
Choose how you want to instrument your application
For .NET, OpenTelemetry supports automatic and manual instrumentation (or a combination of both).
It's a good idea to start with automatic instrumentation and add manual instrumentation if the automatic approach doesn't work or doesn't provide enough information.
Automatically instrument your application optional
.NET automatic instrumentation can be configured either during development or later after deployment.
Whether you configure automatic instrumentation during development or after deployment, you also need to configure the export parameters (for example, endpoint and protocol), unless you opt for OneAgent ingestion or configure them manually via manual instrumentation.
Manually instrument your application optional
Setup
-
Add the current version (
[VERSION]
) of the following packages.1<PackageReference Include="Microsoft.Extensions.Logging" Version="[VERSION]" />2<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="[VERSION]" />3<PackageReference Include="OpenTelemetry" Version="[VERSION]" />4<PackageReference Include="OpenTelemetry.Api" Version="[VERSION]" />5<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="[VERSION]" /> -
Add the following
using
statements to the startup class, which bootstraps your application.1using OpenTelemetry;2using OpenTelemetry.Trace;3using OpenTelemetry.Exporter;4using OpenTelemetry.Metrics;5using OpenTelemetry.Logs;6using OpenTelemetry.Resources;7using OpenTelemetry.Context.Propagation;8using System.Diagnostics;9using System.Diagnostics.Metrics;10using Microsoft.Extensions.Logging; -
Add these fields to your startup class, with the first two indicating your Dynatrace URL and access token.
1private static string DT_API_URL = ""; // TODO: Provide your SaaS/Managed URL here2private static string DT_API_TOKEN = ""; // TODO: Provide the OpenTelemetry-scoped access token here34private const string activitySource = "Dynatrace.DotNetApp.Sample"; // TODO: Provide a descriptive name for your application here5public static readonly ActivitySource MyActivitySource = new ActivitySource(activitySource);6private static ILoggerFactory loggerFactoryOT;Value injectionInstead of hardcoding the URL and token, you might also consider reading them from storage specific to your application framework (for example, environment variables or framework secrets).
-
Add the
initOpenTelemetry
method to your startup class and invoke it as early as possible during your application startup. This initializes OpenTelemetry for the Dynatrace backend and creates default tracer and meter providers.1private static void initOpenTelemetry(IServiceCollection services)2{3 List<KeyValuePair<string, object>> dt_metadata = new List<KeyValuePair<string, object>>();4 foreach (string name in new string[] {"dt_metadata_e617c525669e072eebe3d0f08212e8f2.properties", "/var/lib/dynatrace/enrichment/dt_metadata.properties", "/var/lib/dynatrace/enrichment/dt_host_metadata.properties"}) {5 try {6 foreach (string line in System.IO.File.ReadAllLines(name.StartsWith("/var") ? name : System.IO.File.ReadAllText(name))) {7 var keyvalue = line.Split("=");8 dt_metadata.Add( new KeyValuePair<string, object>(keyvalue[0], keyvalue[1]));9 }10 }11 catch { }12 }1314 Action<ResourceBuilder> configureResource = r => r15 .AddService(serviceName: "dotnet-quickstart") //TODO Replace with the name of your application16 .AddAttributes(dt_metadata);1718 services.AddOpenTelemetry()19 .ConfigureResource(configureResource)20 .WithTracing(builder => {21 builder22 .SetSampler(new AlwaysOnSampler())23 .AddSource(MyActivitySource.Name)24 .AddOtlpExporter(options =>25 {26 options.Endpoint = new Uri(Environment.GetEnvironmentVariable("DT_API_URL")+ "/v1/traces");27 options.Protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf;28 options.Headers = $"Authorization=Api-Token {Environment.GetEnvironmentVariable("DT_API_TOKEN")}";29 });30 })31 .WithMetrics(builder => {32 builder33 .AddMeter("my-meter")34 .AddOtlpExporter((OtlpExporterOptions exporterOptions, MetricReaderOptions readerOptions) =>35 {36 exporterOptions.Endpoint = new Uri(Environment.GetEnvironmentVariable("DT_API_URL")+ "/v1/metrics");37 exporterOptions.Headers = $"Authorization=Api-Token {Environment.GetEnvironmentVariable("DT_API_TOKEN")}";38 exporterOptions.Protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf;39 readerOptions.TemporalityPreference = MetricReaderTemporalityPreference.Delta;40 });41 });4243 var resourceBuilder = ResourceBuilder.CreateDefault();44 configureResource!(resourceBuilder);4546 loggerFactoryOT = LoggerFactory.Create(builder => {47 builder48 .AddOpenTelemetry(options => {49 options.SetResourceBuilder(resourceBuilder).AddOtlpExporter(options => {50 options.Endpoint = new Uri(Environment.GetEnvironmentVariable("DT_API_URL")+ "/v1/logs");51 options.Headers = $"Authorization=Api-Token {Environment.GetEnvironmentVariable("DT_API_TOKEN")}";52 options.ExportProcessorType = OpenTelemetry.ExportProcessorType.Batch;53 options.Protocol = OtlpExportProtocol.HttpProtobuf;54 });55 })56 .AddConsole();57 });58 Sdk.CreateTracerProviderBuilder()59 .SetSampler(new AlwaysOnSampler())60 .AddSource(MyActivitySource.Name)61 .ConfigureResource(configureResource);62 // add-logging63}
Add tracing
Using MyActivitySource
from the setup step, we can now start new activities (traces):
1using var activity = Startup.MyActivitySource.StartActivity("Call to /myendpoint", ActivityKind.Consumer, parentContext.ActivityContext);2activity?.SetTag("http.method", "GET");3activity?.SetTag("net.protocol.version", "1.1");
In the above code, we:
Create a new activity (span) and name it "Call to /myendpoint"
- Add two tags (attributes), following the semantic naming convention, specific to the action of this span: information on the HTTP method and version
The activity will be automatically set as the current and active span until the execution flow leaves the current method scope. Subsequent activities will automatically become child spans.
Collect metrics
-
To instantiate new metric instruments, we first need a meter object.
1private static readonly Meter meter = new Meter("my-meter", "1.0.0"); //TODO Replace with the name of your meter -
With
meter
, we can now create individual instruments, such as a counter.1private static readonly Counter<long> counter = meter.CreateCounter<long>("request_counter"); -
We can now invoke the
Add()
method ofcounter
to record new values with our counter and save additional attributes (for example,action.type
).1counter.Add(1, new("ip", "an ip address here"), new("some other key", "some other value"));
Connect logs
With the loggerFactoryOT
variable, we initialized under Setup, we can now create individual logger instances, which will pass logged information straight to the configured OpenTelemetry endpoint at Dynatrace.
1var logger = loggerFactoryOT.CreateLogger<Startup>();2services.AddSingleton<ILoggerFactory>(loggerFactoryOT);3services.AddSingleton(logger);4logger.LogInformation(eventId: 123, "Log line");
Ensure context propagation optional
Context propagation is particularly important when network calls (for example, REST) are involved.
If you are using automatic instrumentation and your networking libraries are covered by automatic instrumentation, this will be automatically taken care of by the instrumentation libraries. Otherwise, your code needs to take this into account.
Extracting the context when receiving a request
In the following example, we assume that we have received a network call via System.Web.HttpRequest
and we define a CompositeTextMapPropagator
instance to fetch the context information from the HTTP headers. We then pass that instance to Extract()
, returning the context object, which allows us to continue the previous trace with our spans.
1private CompositeTextMapPropagator propagator = new CompositeTextMapPropagator(new TextMapPropagator[] {2 new TraceContextPropagator(),3 new BaggagePropagator(),4});5private static readonly Func<HttpRequest, string, IEnumerable<string>> valueGetter = (request, name) => request.Headers[name];678var parentContext = propagator.Extract(default, HttpContext.Request, valueGetter);910using var activity = MyActivitySource.StartActivity("my-span", ActivityKind.Consumer, parentContext.ActivityContext);
Injecting the context when sending requests
In the following example, we send a REST request to another service and provide our existing context as part of the HTTP headers of our request.
To do so, we define a TextMapPropagator
instance, which adds the respective information. Once we have instantiated our REST object, we pass it, along with the context and the setter instance, to Inject()
, which will add the necessary headers to the request.
1private CompositeTextMapPropagator propagator = new CompositeTextMapPropagator(new TextMapPropagator[] {2 new TraceContextPropagator(),3 new BaggagePropagator()4});56private static Action<HttpRequestMessage, string, string> _headerValueSetter => (request, name, value) => {7 request.Headers.Remove(name);8 request.Headers.Add(name, value);9};1011propagator.Inject(new PropagationContext(activity!.Context, Baggage.Current), request, _headerValueSetter);
Configure data capture to meet privacy requirements optional
While Dynatrace automatically captures all OpenTelemetry attributes, only attribute values specified in the allowlist are stored and displayed in the Dynatrace web UI. This prevents accidental storage of personal data, so you can meet your privacy requirements and control the amount of monitoring data stored.
To view your custom attributes, you need to allow them in the Dynatrace web UI first. To learn how to configure attribute storage and masking, see Attribute redaction.
Verify data ingestion into Dynatrace
Once you have finished the instrumentation of your application, perform a couple of test actions to create and send demo traces, metrics, and logs and verify that they were correctly ingested into Dynatrace.
To do that for traces, in the Dynatrace menu, go to Distributed traces and select the Ingested traces tab. If you use OneAgent, select PurePaths instead.
Metrics and logs can be found under their respective entries at Observe and explore.