Make internal telemetrycontext public#3137
Merged
Conversation
…add processors and update docs
…but does in example apps
.publicApi/Microsoft.ApplicationInsights.dll/Stable/PublicAPI.Shipped.txt
Show resolved
Hide resolved
…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.
…nInsightsExtensions
Contributor
There was a problem hiding this comment.
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
TelemetryContextsub-contexts public again (e.g.,CloudContext,ComponentContext,DeviceContext,SessionContext) and re-expose properties likeUser.AccountIdandOperation.SyntheticSource. - Add OpenTelemetry processors to apply
TelemetryClient.Contextto activities and log records (includingILoggeremission 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.Contextand then runs metric examples, but the updated docs in this PR explicitly state metrics are not enriched byTelemetryClient.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.
BASE/src/Microsoft.ApplicationInsights/Processors/TelemetryContextLogProcessor.cs
Show resolved
Hide resolved
...cationInsights.Test/Microsoft.ApplicationInsights.Tests/TelemetryContextLogProcessorTests.cs
Outdated
Show resolved
Hide resolved
BASE/src/Microsoft.ApplicationInsights/Processors/TelemetryContextActivityProcessor.cs
Show resolved
Hide resolved
xiang17
reviewed
Mar 27, 2026
BASE/src/Microsoft.ApplicationInsights/DataContracts/TelemetryContext.cs
Outdated
Show resolved
Hide resolved
Agent-Logs-Url: https://github.com/microsoft/ApplicationInsights-dotnet/sessions/b9572329-ebd7-4426-a448-54a8cc4fd6b9 Co-authored-by: harsimar <19897860+harsimar@users.noreply.github.com>
…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>
…bility Agent-Logs-Url: https://github.com/microsoft/ApplicationInsights-dotnet/sessions/3f259831-d7e7-4b98-8893-d919119e312b Co-authored-by: harsimar <19897860+harsimar@users.noreply.github.com>
This was referenced Apr 3, 2026
Closed
Open
Merged
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Cloud.RoleName,Cloud.RoleInstance, andComponent.Versionsettings fromHomeControllerconstructorBasicConsoleApp/Program.csBASE/README.mdAssert.FailwithAssert.True(false, ...)inTelemetryContextLogProcessorTests.csfor xUnit v2 compatibility⚡ Quickly spin up Copilot coding agent tasks from anywhere on your macOS or Windows machine with Raycast.