Skip to content

Conversation

Copy link

Copilot AI commented Feb 3, 2026

When OTEL_SDK_DISABLED=true, WithMetrics() crashes with NullReferenceException. The OpenTelemetryMetricsListener constructor receives a NoopMeterProvider from DI but assumes MeterProviderSdk, leading to null dereference when subscribing to events.

Changes

OpenTelemetryMetricsListener.cs

  • Made meterProviderSdk field nullable (MeterProviderSdk?)
  • Added null guards before event subscription in constructor, Dispose(), and InstrumentPublished()
  • Suppressed CA1508 false positive (static analyzer can't see DI may inject noop provider)

Test coverage

  • Added WithMetricsWhenSdkDisabledTest verifying no crash when SDK disabled
  • Validates NoopMeterProvider returned and meters remain usable

Example

Environment.SetEnvironmentVariable("OTEL_SDK_DISABLED", "true");

var builder = Host.CreateApplicationBuilder();
builder.Services
    .AddOpenTelemetry()
    .WithMetrics(m => m.AddMeter("MyMeter"));  // Previously crashed, now works

var host = builder.Build();  // Success
Original prompt

This section details on the original issue you should resolve

<issue_title>[bug] Null Reference Exception from within WithMetrics when OTEL_SDK_DISABLED is set to true</issue_title>
<issue_description>### Package

OpenTelemetry

Package Version

Package Name Version
OpenTelemetry.Exporter.OpenTelemetryProtocol 1.15.0
OpenTelemetry.Extensions.Hosting 1.15.0
OpenTelemetry.Instrumentation.AspNetCore 1.15.0
OpenTelemetry.Instrumentation.Http 1.15.0
OpenTelemetry.Instrumentation.Runtime 1.15.0

Runtime Version

net10.0

Description

Application crashes on startup within the WithMetrics(x=>{}) Extension method when the Environment variable OTEL_SDK_DISABLED is set to true.

Image

Steps to Reproduce

I have included the contents of a file-based app which I have been able to reproduce the issue

#!/bin/env dotnet
#:package Microsoft.Extensions.Hosting@10.0.2
#:package OpenTelemetry.Exporter.OpenTelemetryProtocol@1.15.0
#:package OpenTelemetry.Extensions.Hosting@1.15.0
#:package OpenTelemetry.Instrumentation.AspNetCore@1.15.0
#:package OpenTelemetry.Instrumentation.Http@1.15.0
#:package OpenTelemetry.Instrumentation.Runtime@1.15.0
#:property PathMap=$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))=./

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

Environment.SetEnvironmentVariable("OTEL_SDK_DISABLED", "true");

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddOpenTelemetry()
    .WithMetrics(metricsProviderBuilder =>
    {
        metricsProviderBuilder
            .AddRuntimeInstrumentation()
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddOtlpExporter();
    })
    .WithTracing(tracingProviderBuilder =>
    {
        tracingProviderBuilder
            .AddSource("Test Application")
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .SetSampler<AlwaysOnSampler>()
            .AddOtlpExporter();
    });

builder.Build().Run();

Expected Result

Application should run with Open Telemetry SDK Disabled

Actual Result

Application exits after Object reference not set to an instance of an object

Additional Context

No response

Tip

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Co-authored-by: cijothomas <5232798+cijothomas@users.noreply.github.com>
@github-actions github-actions bot added pkg:OpenTelemetry Issues related to OpenTelemetry NuGet package pkg:OpenTelemetry.Extensions.Hosting Issues related to OpenTelemetry.Extensions.Hosting NuGet package labels Feb 3, 2026
Co-authored-by: cijothomas <5232798+cijothomas@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix null reference exception in WithMetrics when OTEL_SDK_DISABLED is true Fix NullReferenceException in WithMetrics when OTEL_SDK_DISABLED=true Feb 3, 2026
Copilot AI requested a review from cijothomas February 3, 2026 17:21
@codecov
Copy link

codecov bot commented Feb 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.25%. Comparing base (e7da73e) to head (a9539d6).
✅ All tests successful. No failed tests found.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #6869      +/-   ##
==========================================
- Coverage   87.29%   87.25%   -0.04%     
==========================================
  Files         263      263              
  Lines       12385    12387       +2     
==========================================
- Hits        10811    10808       -3     
- Misses       1574     1579       +5     
Flag Coverage Δ
unittests-Project-Experimental 86.90% <100.00%> (-0.29%) ⬇️
unittests-Project-Stable 87.01% <100.00%> (-0.22%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...s/IMetricsListener/OpenTelemetryMetricsListener.cs 100.00% <100.00%> (+3.44%) ⬆️

... and 7 files with indirect coverage changes

- Refactor to avoid suppressing analyzer warnings.
- Update CHANGELOG.
- Remove use of "crashes" in test.
- Sort items.
- Apply Visual Studio refactoring suggestions.
Add coverage for counters and histograms of different types.
@martincostello martincostello marked this pull request as ready for review February 4, 2026 11:35
@martincostello martincostello requested a review from a team as a code owner February 4, 2026 11:36
Copilot AI review requested due to automatic review settings February 4, 2026 11:36
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a NullReferenceException that occurred when OTEL_SDK_DISABLED=true is set. The issue was that OpenTelemetryMetricsListener assumed it would always receive a MeterProviderSdk instance but received a NoopMeterProvider when the SDK was disabled, causing null dereference on event subscriptions.

Changes:

  • Made OpenTelemetryMetricsListener handle nullable MeterProviderSdk with appropriate null guards
  • Added comprehensive test for SDK disabled scenario
  • Enhanced test coverage for byte, short, int, and float numeric types across metrics tests

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/OpenTelemetry/Metrics/IMetricsListener/OpenTelemetryMetricsListener.cs Made meterProviderSdk nullable and added null guards in constructor, Dispose(), and InstrumentPublished() to handle NoopMeterProvider
test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetryMetricsBuilderExtensionsTests.cs Added test for SDK disabled scenario and expanded test coverage to include byte, short, int, float, and double counter types
test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetry.Extensions.Hosting.Tests.csproj Added reference to EnvironmentVariableScope test helper
test/OpenTelemetry.Tests/Metrics/MetricApiTests.cs Added multithreaded counter and histogram tests for byte, short, int, and float types
test/OpenTelemetry.Exporter.OpenTelemetryProtocol.FuzzTests/Generators.cs Updated fuzzing tests to include counters for all numeric types
src/OpenTelemetry.Extensions.Hosting/CHANGELOG.md Documented the NullReferenceException fix

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Remove redundant local variables.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pkg:OpenTelemetry.Extensions.Hosting Issues related to OpenTelemetry.Extensions.Hosting NuGet package pkg:OpenTelemetry Issues related to OpenTelemetry NuGet package

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Null Reference Exception from within WithMetrics when OTEL_SDK_DISABLED is set to true

4 participants