Create custom traces and metrics
You are viewing the English version of this page because it has not yet been fully translated. Interested in helping out? See Contributing.
The automatic instrumentation configures a TracerProvider and a
MeterProvider so that you can add your own manual instrumentation. By using
both automatic and manual instrumentation, you can better instrument the logic
and functionality of your applications, clients, and frameworks.
Traces
To create your custom traces manually, follow these steps:
Add the
System.Diagnostics.DiagnosticSourcedependency to your project:<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.0" />Create an
ActivitySourceinstance:private static readonly ActivitySource RegisteredActivity = new ActivitySource("Examples.ManualInstrumentations.Registered");Create an
Activity. Optionally, set tags:using (var activity = RegisteredActivity.StartActivity("Main")) { activity?.SetTag("foo", "bar1"); // your logic for Main activity }Register your
ActivitySourcein OpenTelemetry.AutoInstrumentation by setting theOTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCESenvironmental variable. You can set the value to eitherExamples.ManualInstrumentations.Registeredor toExamples.ManualInstrumentations.*, which registers the entire prefix.
An Activity created for
NonRegistered.ManualInstrumentations ActivitySource is not handled by the
OpenTelemetry Automatic Instrumentation.
Metrics
To create your custom metrics manually, follow these steps:
Add the
System.Diagnostics.DiagnosticSourcedependency to your project:<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.0" />Create a
Meterinstance:using var meter = new Meter("Examples.Service", "1.0");Create an
Instrument:var successCounter = meter.CreateCounter<long>("srv.successes.count", description: "Number of successful responses");Update the
Instrumentvalue. Optionally, set tags:successCounter.Add(1, new KeyValuePair<string, object?>("tagName", "tagValue"));Register your
Meterwith OpenTelemetry.AutoInstrumentation by setting theOTEL_DOTNET_AUTO_METRICS_ADDITIONAL_SOURCESenvironment variable:OTEL_DOTNET_AUTO_METRICS_ADDITIONAL_SOURCES=Examples.ServiceYou can set the value to either
Examples.Serviceor toExamples.*, which registers the entire prefix.
Further reading
Feedback
Was this page helpful?
Thank you. Your feedback is appreciated!
Please let us know how we can improve this page. Your feedback is appreciated!