Skip to main content

arolariu.Backend.Common.Telemetry.Tracing

arolariu.Backend.Common

arolariu.Backend.Common.Telemetry.Tracing Namespace

Classes

ActivityEnrichingProcessor Class

A custom span processor that enriches all activities with consistent baseline attributes for improved filtering and correlation in Azure Application Insights.

public sealed class ActivityEnrichingProcessor : OpenTelemetry.BaseProcessor<System.Diagnostics.Activity>

Inheritance System.Object 🡒 OpenTelemetry.BaseProcessor<System.Diagnostics.Activity> 🡒 ActivityEnrichingProcessor

Example

// Registration in TracingExtensions.cs
tracingOptions.AddProcessor(new ActivityEnrichingProcessor());

Remarks

This processor is invoked for every span (activity) started in the application and adds:

  • Correlation IDs for cross-service tracing
  • Environment context for multi-environment filtering
  • Timestamp metadata for precise timing analysis
  • Request context extraction from Activity baggage

The processor runs before spans are exported to Azure Monitor, ensuring all telemetry contains the enrichment data needed for effective distributed trace analysis.

Constructors

ActivityEnrichingProcessor() Constructor

Initializes a new instance of the ActivityEnrichingProcessor class.

public ActivityEnrichingProcessor();

Methods

ActivityEnrichingProcessor.CalculateSpanDepth(Activity) Method

Calculates the depth of the current span in the trace hierarchy.

private static int CalculateSpanDepth(System.Diagnostics.Activity? activity);

Parameters

activity System.Diagnostics.Activity

The activity to calculate depth for.

Returns

System.Int32
The depth level (0 = root, 1 = first child, etc.).

ActivityEnrichingProcessor.OnEnd(Activity) Method

Called when an activity is stopped. Can add final enrichment based on activity results.

public override void OnEnd(System.Diagnostics.Activity activity);

Parameters

activity System.Diagnostics.Activity

The activity that was stopped.

Remarks

OnEnd is called synchronously on the thread that stops the activity. This is the last chance to add attributes before the span is exported.

ActivityEnrichingProcessor.OnStart(Activity) Method

Called when an activity is started. Enriches the activity with baseline context.

public override void OnStart(System.Diagnostics.Activity activity);

Parameters

activity System.Diagnostics.Activity

The activity that was started.

Remarks

OnStart is called synchronously on the thread that starts the activity. Keep processing minimal to avoid impacting application performance.

ActivityExtensions Class

Provides extension methods for enriching System.Diagnostics.Activity instances with semantic attributes following OpenTelemetry conventions for improved distributed tracing visibility in Azure Application Insights.

public static class ActivityExtensions

Inheritance System.Object 🡒 ActivityExtensions

Example

using var activity = InvoicePackageTracing.StartActivity("ReadInvoice", ActivityKind.Internal);
activity?
.SetInvoiceContext(invoiceId, userId)
.SetLayerContext("Foundation", "InvoiceStorageFoundationService")
.RecordSuccess();

Remarks

These extensions enable structured, consistent span enrichment across all application layers:

  • Endpoints (Server spans with HTTP context)
  • Services (Internal spans with business context)
  • Brokers (Client spans with database semantic conventions)

Following OpenTelemetry semantic conventions ensures proper correlation and visualization in Azure Application Insights Transaction Search and End-to-End Transaction views.

Methods

ActivityExtensions.AddCustomEvent(this Activity, string, IEnumerable<KeyValuePair<string,object>>) Method

Records a custom event on the activity timeline.

public static System.Diagnostics.Activity? AddCustomEvent(this System.Diagnostics.Activity? activity, string eventName, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,object?>>? attributes=null);

Parameters

activity System.Diagnostics.Activity

The activity to add the event to.

eventName System.String

The name of the event.

attributes System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.Object>>

Optional attributes to attach to the event.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

Events are useful for marking significant points in an operation's lifecycle, such as "validation.started", "external.service.called", or "cache.miss".

ActivityExtensions.RecordException(this Activity, Exception, bool) Method

Records that the operation failed with an error status and exception details.

public static System.Diagnostics.Activity? RecordException(this System.Diagnostics.Activity? activity, System.Exception exception, bool escaped=true);

Parameters

activity System.Diagnostics.Activity

The activity to mark as failed.

exception System.Exception

The exception that caused the failure.

escaped System.Boolean

Whether the exception escaped the span (default: true).

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

This method: 1. Sets the activity status to Error 2. Records the exception as an activity event (per OpenTelemetry spec) 3. Sets semantic exception attributes for filtering 4. Marks the span with the error flag for Application Insights

ActivityExtensions.RecordSuccess(this Activity, string) Method

Records that the operation completed successfully with an OK status.

public static System.Diagnostics.Activity? RecordSuccess(this System.Diagnostics.Activity? activity, string? description=null);

Parameters

activity System.Diagnostics.Activity

The activity to mark as successful.

description System.String

Optional description of the successful completion.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

ActivityExtensions.SetCosmosDbContext(this Activity, string, string, string, string) Method

Sets Azure Cosmos DB specific context following OpenTelemetry database semantic conventions.

public static System.Diagnostics.Activity? SetCosmosDbContext(this System.Diagnostics.Activity? activity, string database, string container, string operation, string? partitionKey=null);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

database System.String

The Cosmos DB database name.

container System.String

The Cosmos DB container name.

operation System.String

The database operation type (e.g., "create", "read", "upsert", "delete", "query").

partitionKey System.String

Optional partition key value used for the operation.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

Following OpenTelemetry semantic conventions ensures proper dependency tracking and enables Application Insights to correctly categorize and display database operations. See: https://opentelemetry\.io/docs/specs/semconv/database/cosmosdb/

ActivityExtensions.SetCosmosDbRequestCharge(this Activity, double) Method

Records the Cosmos DB request charge (RUs consumed) for cost analysis.

public static System.Diagnostics.Activity? SetCosmosDbRequestCharge(this System.Diagnostics.Activity? activity, double requestCharge);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

requestCharge System.Double

The request charge in Request Units (RU).

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

Tracking RU consumption per operation enables cost optimization analysis and identification of expensive database operations.

ActivityExtensions.SetDbStatement(this Activity, string) Method

Sets a sanitized database query statement for debugging purposes.

public static System.Diagnostics.Activity? SetDbStatement(this System.Diagnostics.Activity? activity, string statement);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

statement System.String

The query statement (should be parameterized, no sensitive data).

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

Only include parameterized queries without sensitive data values. This aids in debugging slow or problematic queries.

ActivityExtensions.SetInvoiceContext(this Activity, Guid, Nullable<Guid>) Method

Sets invoice-specific context for the activity, enabling invoice-based filtering and correlation.

public static System.Diagnostics.Activity? SetInvoiceContext(this System.Diagnostics.Activity? activity, System.Guid invoiceId, System.Nullable<System.Guid> userId=null);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

invoiceId System.Guid

The unique identifier of the invoice being processed.

userId System.Nullable<System.Guid>

Optional user identifier associated with the invoice.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

Remarks

Invoice context enables searching for all operations related to a specific invoice in Application Insights using custom dimension filters.

ActivityExtensions.SetInvoiceDetails(this Activity, Guid, Guid, Nullable<Guid>, Nullable<int>, Nullable<decimal>, string) Method

Sets detailed invoice information for comprehensive trace enrichment.

public static System.Diagnostics.Activity? SetInvoiceDetails(this System.Diagnostics.Activity? activity, System.Guid invoiceId, System.Guid userId, System.Nullable<System.Guid> merchantId=null, System.Nullable<int> itemCount=null, System.Nullable<decimal> totalAmount=null, string? currency=null);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

invoiceId System.Guid

The invoice identifier.

userId System.Guid

The user identifier.

merchantId System.Nullable<System.Guid>

The merchant identifier.

itemCount System.Nullable<System.Int32>

The number of items in the invoice.

totalAmount System.Nullable<System.Decimal>

The total amount of the invoice.

currency System.String

The currency code (e.g., "USD", "EUR", "RON").

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

ActivityExtensions.SetLayerContext(this Activity, string, string) Method

Sets the architectural layer context for the activity, enabling hierarchical trace visualization.

public static System.Diagnostics.Activity? SetLayerContext(this System.Diagnostics.Activity? activity, string layer, string component);

Parameters

activity System.Diagnostics.Activity

The activity to enrich. If null, no operation is performed.

layer System.String

The architectural layer name (e.g., "Endpoint", "Processing", "Orchestration", "Foundation", "Broker").

component System.String

The component or service name within the layer.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining, or null if input was null.

Remarks

Layer information enables filtering and grouping spans by architectural tier in Application Insights. This is particularly useful for identifying bottlenecks at specific layers of the application.

ActivityExtensions.SetMerchantContext(this Activity, Guid, string) Method

Sets merchant-specific context for the activity.

public static System.Diagnostics.Activity? SetMerchantContext(this System.Diagnostics.Activity? activity, System.Guid merchantId, string? merchantName=null);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

merchantId System.Guid

The merchant identifier.

merchantName System.String

Optional merchant name for display purposes.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

ActivityExtensions.SetOperationType(this Activity, string) Method

Sets the operation type for the activity, categorizing the kind of work being performed.

public static System.Diagnostics.Activity? SetOperationType(this System.Diagnostics.Activity? activity, string operationType);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

operationType System.String

The operation type (e.g., "CRUD.Create", "CRUD.Read", "Analysis", "Validation").

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

ActivityExtensions.SetUserContext(this Activity, Guid) Method

Sets user context for the activity, enabling user-based trace filtering.

public static System.Diagnostics.Activity? SetUserContext(this System.Diagnostics.Activity? activity, System.Guid userId);

Parameters

activity System.Diagnostics.Activity

The activity to enrich.

userId System.Guid

The user identifier.

Returns

System.Diagnostics.Activity
The enriched activity for method chaining.

ActivityExtensions.StartActivityWithLink(this ActivitySource, string, ActivityContext, ActivityKind) Method

Creates a new activity with a link to a parent trace context, useful for async/batch operations.

public static System.Diagnostics.Activity? StartActivityWithLink(this System.Diagnostics.ActivitySource source, string name, System.Diagnostics.ActivityContext linkedContext, System.Diagnostics.ActivityKind kind=System.Diagnostics.ActivityKind.Internal);

Parameters

source System.Diagnostics.ActivitySource

The activity source to create the activity from.

name System.String

The name of the new activity.

linkedContext System.Diagnostics.ActivityContext

The activity context to link to.

kind System.Diagnostics.ActivityKind

The kind of activity (default: Internal).

Returns

System.Diagnostics.Activity
A new activity with the specified link.

Remarks

Links are useful when an operation is triggered by multiple parent operations or when processing batched items that originated from different traces.

ActivityGenerators Class

Provides centralized activity sources for distributed tracing across application components. This class defines ActivitySource instances that enable OpenTelemetry tracing throughout the system.

public static class ActivityGenerators

Inheritance System.Object 🡒 ActivityGenerators

Example

// Creating a custom activity
using var activity = ActivityGenerators.CommonPackageTracing.StartActivity("ConfigurationLoad");
activity?.SetTag("config.source", "KeyVault");
// Perform configuration loading
activity?.SetStatus(ActivityStatusCode.Ok);

Remarks

Activity sources are used to create spans and traces for: - Cross-service request correlation - Performance monitoring and bottleneck identification - Distributed system debugging and troubleshooting - Service dependency mapping and analysis

Fields

ActivityGenerators.AuthPackageTracing Field

Activity source for the Authentication package operations. Used to trace authentication, authorization, and security-related operations.

public static readonly ActivitySource AuthPackageTracing;

Field Value

System.Diagnostics.ActivitySource

Remarks

This activity source covers: - User authentication and token validation - Authorization policy evaluation - JWT token generation and verification - Security-related middleware operations

ActivityGenerators.CommonPackageTracing Field

Activity source for the Common package operations. Used to trace shared infrastructure components including configuration, validation, and Key Vault operations.

public static readonly ActivitySource CommonPackageTracing;

Field Value

System.Diagnostics.ActivitySource

Remarks

This activity source covers: - Configuration loading and management - Key Vault secret retrieval operations - Validation and utility operations - Shared service interactions

ActivityGenerators.CorePackageTracing Field

Activity source for the Core package operations. Used to trace application startup, middleware pipeline, and general API operations.

public static readonly ActivitySource CorePackageTracing;

Field Value

System.Diagnostics.ActivitySource

Remarks

This activity source covers: - Application startup and configuration - HTTP request processing and middleware operations - Swagger documentation generation - General API infrastructure operations

ActivityGenerators.InvoicePackageTracing Field

Activity source for the Invoices domain package operations. Used to trace business operations related to invoice processing and management.

public static readonly ActivitySource InvoicePackageTracing;

Field Value

System.Diagnostics.ActivitySource

Remarks

This activity source covers: - Invoice creation, processing, and management - Business rule validation and enforcement - Data persistence and retrieval operations - Domain-specific service interactions

TracingExtensions Class

Provides extension methods for configuring OpenTelemetry distributed tracing with Azure Monitor integration. This class sets up comprehensive request tracing across application layers and external dependencies.

public static class TracingExtensions

Inheritance System.Object 🡒 TracingExtensions

Example

// Usage in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.AddOTelTracing();

Remarks

This extension configures: - ASP.NET Core instrumentation for HTTP request tracing - HTTP client instrumentation for outbound dependency tracking - Entity Framework Core instrumentation for database operation tracing - Azure Monitor exporter for distributed trace visualization

Methods

TracingExtensions.AddOTelTracing(this WebApplicationBuilder) Method

Configures OpenTelemetry distributed tracing with comprehensive instrumentation and Azure Monitor export. This method enables end-to-end request tracing across all application layers and external dependencies.

public static void AddOTelTracing(this Microsoft.AspNetCore.Builder.WebApplicationBuilder builder);

Parameters

builder Microsoft.AspNetCore.Builder.WebApplicationBuilder

The Microsoft.AspNetCore.Builder.WebApplicationBuilder to configure with OpenTelemetry tracing.

Exceptions

System.ArgumentNullException
Thrown when builder is null.

Remarks

This method configures tracing instrumentation for: - ASP.NET Core: HTTP request spans with timing, status codes, and routing information - HTTP Client: Outbound request tracing for dependency monitoring and performance analysis - Entity Framework Core: Database query tracing with SQL execution times and connection details - Console export during debugging for immediate trace visibility - Azure Monitor export for production distributed tracing and correlation - Managed Identity authentication for secure Azure integration

// was this page useful?