The automatic instrumentation provides a base you can build on by adding 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.
To create your custom traces manually, follow these steps:
-
Add the
System.Diagnostics.DiagnosticSource
dependency to your project:<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.0" />
-
Create an
ActivitySource
instance: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
ActivitySource
in OpenTelemetry.AutoInstrumentation by setting theOTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES
environmental variable. You can set the value to eitherExamples.ManualInstrumentations.Registered
or toExamples.ManualInstrumentations.*
, which registers the entire prefix.
You can see a sample console application with manual instrumentation here.
Note that an
Activity
created forNonRegistered.ManualInstrumentations
ActivitySource
is not handled by the OpenTelemetry Automatic Instrumentation.
To create your custom metrics manually, follow these steps:
-
Add the
System.Diagnostics.DiagnosticSource
dependency to your project:<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.0" />
-
Create a
Meter
instance: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
Instrument
value. Optionally, set tags:successCounter.Add(1, new KeyValuePair<string, object?>("tagName", "tagValue"));
-
Register your
Meter
with OpenTelemetry.AutoInstrumentation by setting theOTEL_DOTNET_AUTO_METRICS_ADDITIONAL_SOURCES
environment variable:OTEL_DOTNET_AUTO_METRICS_ADDITIONAL_SOURCES=Examples.Service
You can set the value to either
Examples.Service
or toExamples.*
, which registers the entire prefix.
You can see a sample console application with manual metric instrumentation here.