-
Notifications
You must be signed in to change notification settings - Fork 102
Add OpenTelemetry Package #1172
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1fca144
otel: add OpenTelemetry package
mtmk 807a4d8
Merge branch 'release/3.0' into nats-otel-pkg
mtmk 176e367
otel: add options configure overload
mtmk eb45395
otel: add subject-pattern trace filter helper
mtmk a252d58
Merge remote-tracking branch 'origin/release/3.0' into nats-otel-pkg
mtmk 72ee48e
Merge remote-tracking branch 'origin/release/3.0' into nats-otel-pkg
mtmk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
src/NATS.Client.OpenTelemetry/NATS.Client.OpenTelemetry.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <!-- NuGet Packaging --> | ||
| <PackageTags>opentelemetry;tracing;metrics;observability;nats</PackageTags> | ||
| <Description>OpenTelemetry instrumentation for NATS .NET. Adds the ActivitySource and Meter for the client to a TracerProviderBuilder or MeterProviderBuilder.</Description> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="OpenTelemetry.Api" Version="1.15.3" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\NATS.Client.Core\NATS.Client.Core.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
38 changes: 38 additions & 0 deletions
38
src/NATS.Client.OpenTelemetry/NatsInstrumentationExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| using System; | ||
| using NATS.Client.Core; | ||
| using OpenTelemetry.Metrics; | ||
| using OpenTelemetry.Trace; | ||
|
|
||
| namespace NATS.Client.OpenTelemetry; | ||
|
|
||
| public static class NatsInstrumentationExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds the NATS .NET client <see cref="System.Diagnostics.ActivitySource"/> to the tracer provider, | ||
| /// enabling distributed tracing for publish, subscribe, and request/reply operations. | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="TracerProviderBuilder"/> to add the source to.</param> | ||
| /// <returns>The supplied <paramref name="builder"/> for chaining.</returns> | ||
| public static TracerProviderBuilder AddNatsClientInstrumentation(this TracerProviderBuilder builder) => | ||
| builder.AddSource(NatsTelemetry.SourceName); | ||
|
|
||
| /// <summary> | ||
| /// Adds the NATS .NET client <see cref="System.Diagnostics.ActivitySource"/> to the tracer provider and | ||
| /// configures the shared <see cref="NatsInstrumentationOptions"/> (filter and enrich callbacks). | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="TracerProviderBuilder"/> to add the source to.</param> | ||
| /// <param name="configure">Action that mutates the process-wide <see cref="NatsInstrumentationOptions.Default"/>.</param> | ||
| /// <returns>The supplied <paramref name="builder"/> for chaining.</returns> | ||
| public static TracerProviderBuilder AddNatsClientInstrumentation(this TracerProviderBuilder builder, Action<NatsInstrumentationOptions> configure) | ||
| { | ||
| configure?.Invoke(NatsInstrumentationOptions.Default); | ||
| return builder.AddSource(NatsTelemetry.SourceName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds the NATS .NET client <see cref="System.Diagnostics.Metrics.Meter"/> to the meter provider, | ||
| /// enabling messaging metrics (published/consumed counters, operation duration, and more). | ||
| /// </summary> | ||
| public static MeterProviderBuilder AddNatsClientInstrumentation(this MeterProviderBuilder builder) => | ||
| builder.AddMeter(NatsTelemetry.SourceName); | ||
| } | ||
108 changes: 108 additions & 0 deletions
108
src/NATS.Client.OpenTelemetry/NatsInstrumentationOptionsExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| using System; | ||
| using NATS.Client.Core; | ||
|
|
||
| namespace NATS.Client.OpenTelemetry; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for <see cref="NatsInstrumentationOptions"/>. | ||
| /// </summary> | ||
| public static class NatsInstrumentationOptionsExtensions | ||
| { | ||
| /// <summary> | ||
| /// Restricts tracing to operations whose subject matches the given NATS subject patterns. | ||
| /// </summary> | ||
| /// <param name="options">The options to configure.</param> | ||
| /// <param name="include"> | ||
| /// Subject patterns to trace. An operation is traced only if its subject matches at least one | ||
| /// pattern. When <c>null</c> or empty, every subject is eligible (still subject to <paramref name="exclude"/>). | ||
| /// </param> | ||
| /// <param name="exclude"> | ||
| /// Subject patterns to skip. An operation matching any of these is not traced, even when it also | ||
| /// matches an include pattern. A common use is dropping inbox traffic with <c>_INBOX.></c>. | ||
| /// </param> | ||
| /// <returns>The same <paramref name="options"/> instance for chaining.</returns> | ||
| /// <remarks> | ||
| /// Patterns use NATS subject wildcards: <c>*</c> matches a single token and <c>></c> matches one or | ||
| /// more trailing tokens. The resulting predicate is combined (logical AND) with any existing | ||
| /// <see cref="NatsInstrumentationOptions.Filter"/>, so a previously configured filter still applies. | ||
| /// </remarks> | ||
| public static NatsInstrumentationOptions FilterSubjects( | ||
| this NatsInstrumentationOptions options, | ||
| string[]? include = null, | ||
| string[]? exclude = null) | ||
| { | ||
| if (options is null) | ||
| throw new ArgumentNullException(nameof(options)); | ||
|
|
||
| var includeTokens = Tokenize(include); | ||
| var excludeTokens = Tokenize(exclude); | ||
|
|
||
| // Nothing to filter on; leave any existing filter untouched. | ||
| if (includeTokens is null && excludeTokens is null) | ||
| return options; | ||
|
|
||
| var previous = options.Filter; | ||
| options.Filter = context => | ||
| { | ||
| if (previous is not null && !previous(context)) | ||
| return false; | ||
|
|
||
| var subject = context.Subject; | ||
|
|
||
| if (excludeTokens is not null) | ||
| { | ||
| foreach (var pattern in excludeTokens) | ||
| { | ||
| if (Matches(subject, pattern)) | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| if (includeTokens is not null) | ||
| { | ||
| foreach (var pattern in includeTokens) | ||
| { | ||
| if (Matches(subject, pattern)) | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| }; | ||
|
|
||
| return options; | ||
| } | ||
|
|
||
| private static string[][]? Tokenize(string[]? patterns) | ||
| { | ||
| if (patterns is null || patterns.Length == 0) | ||
| return null; | ||
|
|
||
| var result = new string[patterns.Length][]; | ||
| for (var i = 0; i < patterns.Length; i++) | ||
| result[i] = patterns[i].Split('.'); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| // NATS subject match: '*' matches exactly one token, '>' matches one or more trailing tokens. | ||
| private static bool Matches(string subject, string[] pattern) | ||
| { | ||
| var tokens = subject.Split('.'); | ||
| for (var i = 0; i < pattern.Length; i++) | ||
| { | ||
| if (pattern[i] == ">") | ||
| return tokens.Length > i; | ||
|
|
||
| if (i >= tokens.Length) | ||
| return false; | ||
|
|
||
| if (pattern[i] != "*" && !string.Equals(pattern[i], tokens[i], StringComparison.Ordinal)) | ||
| return false; | ||
| } | ||
|
|
||
| return tokens.Length == pattern.Length; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
tests/NATS.Net.OpenTelemetry.Tests/NatsInstrumentationExtensionsTest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| using NATS.Client.OpenTelemetry; | ||
| using OpenTelemetry; | ||
| using OpenTelemetry.Metrics; | ||
| using OpenTelemetry.Trace; | ||
|
|
||
| namespace NATS.Client.Core.Tests; | ||
|
|
||
| public class NatsInstrumentationExtensionsTest | ||
| { | ||
| [Fact] | ||
| public void AddNatsClientInstrumentation_builds_tracer_provider() | ||
| { | ||
| using var provider = Sdk.CreateTracerProviderBuilder() | ||
| .AddNatsClientInstrumentation() | ||
| .Build(); | ||
|
|
||
| provider.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AddNatsClientInstrumentation_builds_meter_provider() | ||
| { | ||
| using var provider = Sdk.CreateMeterProviderBuilder() | ||
| .AddNatsClientInstrumentation() | ||
| .Build(); | ||
|
|
||
| provider.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AddNatsClientInstrumentation_with_configure_sets_options() | ||
| { | ||
| var configured = false; | ||
| try | ||
| { | ||
| using var provider = Sdk.CreateTracerProviderBuilder() | ||
| .AddNatsClientInstrumentation(options => | ||
| { | ||
| configured = true; | ||
| options.Filter = _ => true; | ||
| options.Enrich = (_, _) => { }; | ||
| }) | ||
| .Build(); | ||
|
|
||
| configured.Should().BeTrue(); | ||
| NatsInstrumentationOptions.Default.Filter.Should().NotBeNull(); | ||
| NatsInstrumentationOptions.Default.Enrich.Should().NotBeNull(); | ||
| } | ||
| finally | ||
| { | ||
| NatsInstrumentationOptions.Default.Filter = null; | ||
| NatsInstrumentationOptions.Default.Enrich = null; | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void SourceName_is_NATS_Net() | ||
| { | ||
| NatsTelemetry.SourceName.Should().Be("NATS.Net"); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("orders.new", true)] | ||
| [InlineData("orders.new.eu", true)] | ||
| [InlineData("orders", false)] // '>' needs at least one trailing token | ||
| [InlineData("payments.new", false)] | ||
| public void FilterSubjects_include_matches_only_listed(string subject, bool expected) | ||
| { | ||
| var options = new NatsInstrumentationOptions().FilterSubjects(include: ["orders.>"]); | ||
|
|
||
| options.Filter!(Context(subject)).Should().Be(expected); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("_INBOX.abc.def", false)] | ||
| [InlineData("foo.bar", true)] | ||
| public void FilterSubjects_exclude_drops_listed(string subject, bool expected) | ||
| { | ||
| var options = new NatsInstrumentationOptions().FilterSubjects(exclude: ["_INBOX.>"]); | ||
|
|
||
| options.Filter!(Context(subject)).Should().Be(expected); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("foo.bar", true)] | ||
| [InlineData("foo.bar.baz", false)] // '*' matches a single token only | ||
| [InlineData("foo", false)] | ||
| public void FilterSubjects_single_token_wildcard(string subject, bool expected) | ||
| { | ||
| var options = new NatsInstrumentationOptions().FilterSubjects(include: ["foo.*"]); | ||
|
|
||
| options.Filter!(Context(subject)).Should().Be(expected); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void FilterSubjects_exclude_wins_over_include() | ||
| { | ||
| var options = new NatsInstrumentationOptions().FilterSubjects(include: ["orders.>"], exclude: ["orders.internal.>"]); | ||
|
|
||
| options.Filter!(Context("orders.new")).Should().BeTrue(); | ||
| options.Filter!(Context("orders.internal.audit")).Should().BeFalse(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void FilterSubjects_composes_with_existing_filter() | ||
| { | ||
| var options = new NatsInstrumentationOptions { Filter = ctx => ctx.Subject.StartsWith("orders.", StringComparison.Ordinal) }; | ||
| options.FilterSubjects(exclude: ["orders.internal.>"]); | ||
|
|
||
| options.Filter!(Context("orders.new")).Should().BeTrue(); | ||
| options.Filter!(Context("orders.internal.audit")).Should().BeFalse(); // dropped by subject exclude | ||
| options.Filter!(Context("payments.new")).Should().BeFalse(); // dropped by the pre-existing filter | ||
| } | ||
|
|
||
| [Fact] | ||
| public void FilterSubjects_without_patterns_leaves_filter_unset() | ||
| { | ||
| var options = new NatsInstrumentationOptions().FilterSubjects(); | ||
|
|
||
| options.Filter.Should().BeNull(); | ||
| } | ||
|
|
||
| private static NatsInstrumentationContext Context(string subject) => | ||
| new(subject, Headers: null, ReplyTo: null, QueueGroup: null, BodySize: null, Size: null, Connection: null, ParentContext: default); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.