Skip to content

Make internal telemetrycontext public#3137

Merged
harsimar merged 21 commits intomainfrom
harskaur/publicContext
Mar 31, 2026
Merged

Make internal telemetrycontext public#3137
harsimar merged 21 commits intomainfrom
harskaur/publicContext

Conversation

@harsimar
Copy link
Copy Markdown
Member

@harsimar harsimar commented Mar 5, 2026

  • Analyze new comments
  • Remove Cloud.RoleName, Cloud.RoleInstance, and Component.Version settings from HomeController constructor
  • Replace hard-coded connection string with dummy placeholder in BasicConsoleApp/Program.cs
  • Remove "Setting Context Properties" section from BASE/README.md
  • Replace Assert.Fail with Assert.True(false, ...) in TelemetryContextLogProcessorTests.cs for xUnit v2 compatibility

⚡ Quickly spin up Copilot coding agent tasks from anywhere on your macOS or Windows machine with Raycast.

rajkumar-rangaraj and others added 4 commits March 20, 2026 13:25
…rocessors

- Introduced unit tests for TelemetryContextLogProcessor to validate attribute application, global properties handling, and snapshot behavior.
- Enhanced TelemetryContextActivityProcessor and TelemetryContextLogProcessor with warmup optimizations, freezing snapshots for improved performance.
- Implemented fast paths for attribute merging to reduce allocations and improve efficiency during logging operations.
- Ensured thread safety and proper handling of existing attributes to prevent overwrites during concurrent processing.
@harsimar harsimar marked this pull request as ready for review March 23, 2026 16:50
Copilot AI review requested due to automatic review settings March 23, 2026 16:50
Copy link
Copy Markdown
Contributor

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 expands the public surface area of TelemetryContext (Cloud/Component/Device/Session and additional properties), and changes how client-level context is propagated by moving enrichment into OpenTelemetry processors for activities and logs.

Changes:

  • Make several TelemetryContext sub-contexts public again (e.g., CloudContext, ComponentContext, DeviceContext, SessionContext) and re-expose properties like User.AccountId and Operation.SyntheticSource.
  • Add OpenTelemetry processors to apply TelemetryClient.Context to activities and log records (including ILogger emission paths).
  • Update docs and tests to reflect new context propagation behavior (including explicit note that metrics are not enriched).

Reviewed changes

Copilot reviewed 28 out of 28 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
examples/BasicConsoleApp/Program.cs Updates sample configuration and sets many TelemetryClient.Context fields to validate propagation.
examples/AspNetCoreWebApp/appsettings.json Clears the sample connection string value.
examples/AspNetCoreWebApp/Controllers/HomeController.cs Adds sample context setters and emits multiple telemetry types in the controller action.
NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs Registers new context processors for tracing/logging in WorkerService DI pipeline.
NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsExtensions.cs Registers new context processors for tracing/logging in AspNetCore DI pipeline.
MigrationGuidance.md Updates guidance for setting context in 3.x and notes metrics aren’t enriched by TelemetryClient.Context.
BreakingChanges.md Revises TelemetryContext breaking changes and lists retained public properties.
BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs Removes ContextTags usage and prepends context processors in non-DI scenarios; adjusts log state construction and activity/property mapping.
BASE/src/Microsoft.ApplicationInsights/Processors/TelemetryContextLogProcessor.cs New log processor enriching LogRecord attributes from client context with skip-if-present semantics and snapshot optimization.
BASE/src/Microsoft.ApplicationInsights/Processors/TelemetryContextActivityProcessor.cs New activity processor enriching Activity tags from client context with skip-if-present semantics and snapshot optimization.
BASE/src/Microsoft.ApplicationInsights/OpenTelemetryBuilderExtensions.cs Reorders tracing/logging builder calls.
BASE/src/Microsoft.ApplicationInsights/Metric.cs Removes automatic client context tag enrichment from Metric.TrackValue paths.
BASE/src/Microsoft.ApplicationInsights/Internal/SemanticConventions.cs Adds new semantic convention keys for session/device/synthetic source/account id.
BASE/src/Microsoft.ApplicationInsights/Extensibility/TelemetryConfiguration.cs Adds internal helper to prepend OpenTelemetry builder configuration.
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/UserContext.cs Makes AccountId public and restores UserAgent property.
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/SessionContext.cs Makes SessionContext public (with IsFirst internal).
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/OperationContext.cs Makes SyntheticSource public.
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/DeviceContext.cs Makes DeviceContext public; swaps Model/OemName visibility (OEM becomes internal).
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/ComponentContext.cs Makes ComponentContext public and sets an env var on Version changes.
BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/CloudContext.cs Makes CloudContext public (already env-var-backed setters).
BASE/src/Microsoft.ApplicationInsights/DataContracts/TelemetryContext.cs Exposes Cloud, Component, Device, Session as public properties.
BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/TelemetryContextLogProcessorTests.cs New unit tests for log processor enrichment, precedence, snapshotting, and concurrency.
BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/TelemetryContextActivityProcessorTests.cs New unit tests for activity processor enrichment, snapshotting, and concurrency.
BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/TelemetryClientTest.cs Updates UserAgent mapping expectations and adds component-version env var test.
BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/TelemetryClientContextTagsTest.cs Reworks tests away from ContextTags and toward processor-driven enrichment behavior.
BASE/README.md Updates docs table for context properties (currently out of sync with new API surface).
.publicApi/Microsoft.ApplicationInsights.dll/Stable/PublicAPI.Unshipped.txt Adds new public API entries for newly public contexts/properties.
.publicApi/Microsoft.ApplicationInsights.dll/Stable/PublicAPI.Shipped.txt Removes UserAgent from shipped surface (now tracked as unshipped addition).
Comments suppressed due to low confidence (1)

examples/BasicConsoleApp/Program.cs:65

  • This sample sets TelemetryClient.Context and then runs metric examples, but the updated docs in this PR explicitly state metrics are not enriched by TelemetryClient.Context. As written, this can mislead readers into thinking these context values should flow to metrics. Consider either removing the metric section from this context-propagation verification, or add an explicit comment clarifying that only trace/log/activity telemetry is enriched.
            // Set all public TelemetryContext properties to verify context tag propagation
            telemetryClient.Context.User.Id = "test-user-123";
            telemetryClient.Context.User.AuthenticatedUserId = "auth-user-456";
            telemetryClient.Context.User.AccountId = "account-789";
            telemetryClient.Context.User.UserAgent = "curl/8.0";
            telemetryClient.Context.Session.Id = "session-abc";
            telemetryClient.Context.Device.Id = "device-xyz";
            telemetryClient.Context.Device.Model = "Surface Pro";
            telemetryClient.Context.Device.Type = "PC";
            telemetryClient.Context.Device.OperatingSystem = "Windows 11";
            telemetryClient.Context.Operation.Name = "TestOperation";
            telemetryClient.Context.Operation.SyntheticSource = "test-bot";
            telemetryClient.Context.Location.Ip = "10.0.0.1";
            telemetryClient.Context.Cloud.RoleName = "TestRole";
            telemetryClient.Context.Cloud.RoleInstance = "TestInstance";
            telemetryClient.Context.Component.Version = "2.0.0";
            telemetryClient.Context.GlobalProperties["GlobalKey"] = "GlobalValue";

            // **The following lines are examples of tracking different telemetry types.**

            telemetryClient.TrackEvent("SampleEvent");
            telemetryClient.TrackEvent(new EventTelemetry("SampleEventObject"));
            telemetryClient.TrackTrace("A trace message");
            telemetryClient.TrackTrace("A warning", SeverityLevel.Warning);
            telemetryClient.TrackTrace("A debug trace", SeverityLevel.Verbose);
            telemetryClient.TrackTrace("A trace with properties", new System.Collections.Generic.Dictionary<string, string> { { "Key", "Value" } });
            telemetryClient.TrackTrace("A trace with severity and properties", SeverityLevel.Error, new System.Collections.Generic.Dictionary<string, string> { { "Key", "Value" } });
            telemetryClient.TrackTrace(new TraceTelemetry("TraceTelemetry object", SeverityLevel.Information));

            // **Metrics Examples**
            telemetryClient.TrackMetric("SampleMetric", 42.0);
            telemetryClient.TrackMetric("SampleMetricWithProperties", 99.5, new System.Collections.Generic.Dictionary<string, string> { { "Environment", "Production" } });
            telemetryClient.TrackMetric(new MetricTelemetry("SampleMetricObject", 42.0));


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

…xt Properties section from README

Agent-Logs-Url: https://github.com/microsoft/ApplicationInsights-dotnet/sessions/f704c8d6-9288-49bd-a0f4-8c6a7b4cbbd9

Co-authored-by: harsimar <19897860+harsimar@users.noreply.github.com>
This was referenced Apr 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants