diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/CHANGELOG.md b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/CHANGELOG.md index 07fdcd147da9..274a896b2a13 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/CHANGELOG.md +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/CHANGELOG.md @@ -4,7 +4,10 @@ ### Features Added -### Breaking Changes +- Added multi-tenant support for traces, off by default and enabled with the `Azure.Monitor.OpenTelemetry.EnableMultiTenantExport` AppContext switch. When enabled, an Activity carrying the `microsoft.instrumentation_key` and `microsoft.ingestion_endpoint` attributes is sent to that endpoint instead of the exporter's own; Activities without both attributes are dropped. Live Metrics is disabled while the switch is on, and sampling defaults to fixed-rate rather than rate-limited because a per-process rate limit would be shared across every tenant the process carries. The switch cannot be combined with Microsoft Entra ID authentication, because the credential is scoped to the exporter's own audience and would be sent to endpoints supplied by telemetry. + ([#62707](https://github.com/Azure/azure-sdk-for-net/pull/62707)) + +- Extended multi-tenant export to logs, off by default and enabled with the same `Azure.Monitor.OpenTelemetry.EnableMultiTenantExport` AppContext switch used for traces. When enabled, a `LogRecord` carrying the `microsoft.instrumentation_key` and `microsoft.ingestion_endpoint` attributes is sent to that endpoint instead of the exporter's own; log records without both attributes are dropped. The two routing attributes are consumed for routing and are not emitted as custom properties. Routing reads only `LogRecord.Attributes`, not logging scopes. Live Metrics disablement and the Microsoft Entra ID restriction that apply to multi-tenant traces apply to logs as well, since both are enforced on the shared transmitter. ### Bugs Fixed @@ -16,9 +19,6 @@ - Add support for project id attributes propagation ([#62052](https://github.com/Azure/azure-sdk-for-net/pull/62052)) -- Added multi-tenant support for traces, off by default and enabled with the `Azure.Monitor.OpenTelemetry.EnableMultiTenantExport` AppContext switch. When enabled, an Activity carrying the `microsoft.instrumentation_key` and `microsoft.ingestion_endpoint` attributes is sent to that endpoint instead of the exporter's own; Activities without both attributes are dropped. Live Metrics is disabled while the switch is on, and sampling defaults to fixed-rate rather than rate-limited because a per-process rate limit would be shared across every tenant the process carries. The switch cannot be combined with Microsoft Entra ID authentication, because the credential is scoped to the exporter's own audience and would be sent to endpoints supplied by telemetry. - ([#62707](https://github.com/Azure/azure-sdk-for-net/pull/62707)) - - Shutting down a provider (including `Dispose()`) now writes pending telemetry to offline storage and uploads it in the background instead of blocking on ingestion. Short-lived applications such as CLI tools previously lost this telemetry, because they exit before a transmission completes; the telemetry is now durable before exit, and delivery is completed by a background drain in this or a subsequent run. `ForceFlush` is unchanged by default and can be opted in with the `Azure.Monitor.OpenTelemetry.Exporter.PersistOnForceFlush` AppContext switch, which applies to traces and logs only: a metric reader cannot distinguish a caller's flush from its periodic collection, so metric `ForceFlush` always transmits. The previous behavior can be restored with the `Azure.Monitor.OpenTelemetry.Exporter.DisablePersistOnShutdown` AppContext switch. ([#61818](https://github.com/Azure/azure-sdk-for-net/pull/61818)) diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/AzureMonitorLogExporter.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/AzureMonitorLogExporter.cs index 09c2d1d526d9..7b8423f11af9 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/AzureMonitorLogExporter.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/AzureMonitorLogExporter.cs @@ -6,6 +6,7 @@ using Azure.Core.Pipeline; using Azure.Monitor.OpenTelemetry.Exporter.Internals; using Azure.Monitor.OpenTelemetry.Exporter.Internals.Diagnostics; +using Azure.Monitor.OpenTelemetry.Exporter.Internals.MultiTenant; using OpenTelemetry; using OpenTelemetry.Logs; @@ -17,8 +18,11 @@ namespace Azure.Monitor.OpenTelemetry.Exporter public sealed class AzureMonitorLogExporter : BaseExporter { private readonly ITransmitter _transmitter; + private readonly IMultiTenantTransmitter? _multiTenantTransmitter; private readonly string _instrumentationKey; + private readonly bool _multiTenantEnabled; private AzureMonitorResource? _resource; + private EndpointRouteBatch? _routeBatch; private bool _disposed; /// @@ -30,9 +34,35 @@ public AzureMonitorLogExporter(AzureMonitorExporterOptions options) : this(Trans } internal AzureMonitorLogExporter(ITransmitter transmitter) + : this(transmitter, MultiTenantConfig.Enabled) + { + } + + /// + /// The gate is a constructor parameter so a test can exercise either path without mutating + /// process-wide state that other tests observe. + /// + internal AzureMonitorLogExporter(ITransmitter transmitter, bool multiTenantEnabled) { _transmitter = transmitter; _instrumentationKey = transmitter.InstrumentationKey; + _multiTenantEnabled = multiTenantEnabled; + + if (_multiTenantEnabled) + { + if (transmitter is not IMultiTenantTransmitter multiTenantTransmitter) + { + // The caller already took a reference on the shared transmitter, which owns + // storage timers and statsbeat, so it has to be released before unwinding. + transmitter.Dispose(); + + throw new NotSupportedException($"Multi-tenant export requires a transmitter implementing {nameof(IMultiTenantTransmitter)}."); + } + + _multiTenantTransmitter = multiTenantTransmitter; + + AzureMonitorExporterEventSource.Log.MultiTenantExportEnabled(); + } } internal AzureMonitorResource? LogResource => _resource ??= ParentProvider?.GetResource().CreateAzureMonitorResource(_instrumentationKey); @@ -45,6 +75,11 @@ public override ExportResult Export(in Batch batch) // Prevent Azure Monitor's HTTP operations from being instrumented. using var scope = SuppressInstrumentationScope.Begin(); + if (_multiTenantEnabled) + { + return ExportMultiTenant(batch); + } + ExportResult exportResult = ExportResult.Failure; try @@ -63,6 +98,39 @@ public override ExportResult Export(in Batch batch) return exportResult; } + private ExportResult ExportMultiTenant(in Batch batch) + { + // A concurrent Export takes a fresh batch rather than sharing the cached one. + var routeBatch = Interlocked.Exchange(ref _routeBatch, null) ?? new EndpointRouteBatch(); + + try + { + LogsHelper.OtelToAzureMonitorLogsMultiTenant(batch, LogResource, routeBatch); + + if (routeBatch.Count == 0) + { + // Routing attributes are stamped upstream only on records meant to be routed; + // a batch where nothing carried them is not addressed to any tenant, so report + // success rather than treating an empty routed batch as a failed export. + return ExportResult.Success; + } + + // Blocks until every group has been sent, so Reset cannot run under a consumer that + // still holds a group's item list. + return _multiTenantTransmitter!.Track(routeBatch, TelemetryItemOrigin.AzureMonitorLogExporter, CancellationToken.None); + } + catch (Exception ex) + { + AzureMonitorExporterEventSource.Log.FailedToExport(nameof(AzureMonitorLogExporter), _instrumentationKey, ex); + return ExportResult.Failure; + } + finally + { + routeBatch.Reset(); + Interlocked.Exchange(ref _routeBatch, routeBatch); + } + } + /// protected override void Dispose(bool disposing) { diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/Diagnostics/AzureMonitorExporterEventSource.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/Diagnostics/AzureMonitorExporterEventSource.cs index a4cd39bf6c18..01fb95892294 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/Diagnostics/AzureMonitorExporterEventSource.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/Diagnostics/AzureMonitorExporterEventSource.cs @@ -558,7 +558,7 @@ public void FailedToPersistOnShutdown(string instrumentationKey, Exception ex) [Event(60, Message = "Ingestion rejected a batch of {0} stored payloads with status code {1}. Retrying them individually to isolate the rejected payload.", Level = EventLevel.Warning)] public void CoalescedBatchRejected(int batchSize, int statusCode) => WriteEvent(60, batchSize, statusCode); - [Event(61, Message = "Multi-tenant export is enabled. Activities are routed by their microsoft.instrumentation_key and microsoft.ingestion_endpoint tags.", Level = EventLevel.Informational)] + [Event(61, Message = "Multi-tenant export is enabled. Telemetry is routed by its microsoft.instrumentation_key and microsoft.ingestion_endpoint tags.", Level = EventLevel.Informational)] public void MultiTenantExportEnabled() => WriteEvent(61); [Event(62, Message = "Live Metrics was disabled because multi-tenant export is enabled. Live Metrics streams to the endpoint from the exporter's own connection string and cannot serve routed tenants.", Level = EventLevel.Warning)] diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs index 37048ae50bf9..5f83acf802c9 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/LogsHelper.cs @@ -4,11 +4,13 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using Azure.Monitor.OpenTelemetry.Exporter.Internals.CustomerSdkStats; using Azure.Monitor.OpenTelemetry.Exporter.Internals.Diagnostics; +using Azure.Monitor.OpenTelemetry.Exporter.Internals.MultiTenant; using Azure.Monitor.OpenTelemetry.Exporter.Models; using Microsoft.Extensions.Logging; @@ -21,6 +23,8 @@ namespace Azure.Monitor.OpenTelemetry.Exporter.Internals internal static class LogsHelper { private const string CustomEventAttributeName = "microsoft.custom_event.name"; + private const string InstrumentationKeyAttributeName = SemanticConventions.AttributeMicrosoftInstrumentationKey; + private const string IngestionEndpointAttributeName = SemanticConventions.AttributeMicrosoftIngestionEndpoint; private const string ClientIpAttributeName = "microsoft.client.ip"; private const string EndUserPseudoIdAttributeName = "enduser.pseudo.id"; private const string EndUserIdAttributeName = "enduser.id"; @@ -76,85 +80,176 @@ internal static (List TelemetryItems, TelemetrySchemaTypeCounter { List telemetryItems = new List(capacity: (int)batchLogRecord.Count); var telemetrySchemaTypeCounter = new TelemetrySchemaTypeCounter(); - TelemetryItem telemetryItem; foreach (var logRecord in batchLogRecord) { try { - var properties = new ChangeTrackingDictionary(); - ProcessLogRecordProperties(logRecord, properties, out string? message, out string? eventName, out LogContextInfo logContext, out AvailabilityInfo? availabilityInfo); + telemetryItems.Add(BuildLogTelemetryItem(logRecord, resource, instrumentationKey, telemetrySchemaTypeCounter, recognizeRoutingTags: false)); + } + catch (Exception ex) + { + AzureMonitorExporterEventSource.Log.FailedToConvertLogRecord(instrumentationKey, ex); + } + } + + return (telemetryItems, telemetrySchemaTypeCounter); + } - if (logRecord.Exception is not null) + /// + /// Converts a batch into envelopes grouped by the ingestion endpoint each + /// was stamped with. A record whose routing attributes are missing or invalid is dropped rather + /// than sent under the exporter's own connection string. + /// + internal static void OtelToAzureMonitorLogsMultiTenant(Batch batchLogRecord, AzureMonitorResource? resource, EndpointRouteBatch routeBatch) + { + foreach (var logRecord in batchLogRecord) + { + try + { + if (!TryGetLogRoute(logRecord, out var instrumentationKey, out var ingestionEndpoint)) { - telemetryItem = new TelemetryItem("Exception", logRecord, resource, instrumentationKey, logContext) - { - Data = new MonitorBase - { - BaseType = "ExceptionData", - BaseData = new TelemetryExceptionData(Version, logRecord, message, properties), - } - }; - telemetrySchemaTypeCounter._exceptionCount++; + // Routing attributes are stamped upstream only on records meant to be routed; + // a record without them is not addressed to any tenant, so drop it quietly + // instead of misrouting it to the exporter's own connection string. This is a + // normal, expected outcome rather than a failed conversion. + continue; } - else if (eventName is not null) + + var group = routeBatch.GetOrAdd(ingestionEndpoint); + + // No schema counter on the routed path: IMultiTenantTransmitter.Track carries none, + // matching the trace multi-tenant conversion. + group.TelemetryItems.Add(BuildLogTelemetryItem(logRecord, resource, instrumentationKey, telemetrySchemaTypeCounter: null, recognizeRoutingTags: true)); + } + catch (Exception ex) + { + AzureMonitorExporterEventSource.Log.FailedToConvertLogRecord(instrumentationKey: string.Empty, ex); + } + } + } + + /// + /// Reads the two routing attributes off a . Only + /// LogRecord.Attributes are consulted - logging scopes are not a routing source - and + /// only string values are accepted (first occurrence of each key wins), matching how trace + /// routing reads an . + /// + internal static bool TryGetLogRoute( + LogRecord logRecord, + [NotNullWhen(true)] out string? instrumentationKey, + [NotNullWhen(true)] out string? ingestionEndpoint) + { + object? rawKey = null; + object? rawEndpoint = null; + bool keySeen = false; + bool endpointSeen = false; + + foreach (KeyValuePair item in logRecord.Attributes ?? Enumerable.Empty>()) + { + if (!keySeen && item.Key == InstrumentationKeyAttributeName) + { + rawKey = item.Value; + keySeen = true; + } + else if (!endpointSeen && item.Key == IngestionEndpointAttributeName) + { + rawEndpoint = item.Value; + endpointSeen = true; + } + + if (keySeen && endpointSeen) + { + break; + } + } + + // A non-string value stringifies unpredictably (e.g. "System.String[]" for an array), so + // 'as string' drops it and routing fails, exactly as the trace path does. + return TenantRouting.TryGetRoute(rawKey as string, rawEndpoint as string, out instrumentationKey, out ingestionEndpoint); + } + + private static TelemetryItem BuildLogTelemetryItem(LogRecord logRecord, AzureMonitorResource? resource, string instrumentationKey, TelemetrySchemaTypeCounter? telemetrySchemaTypeCounter, bool recognizeRoutingTags) + { + var properties = new ChangeTrackingDictionary(); + ProcessLogRecordProperties(logRecord, properties, out string? message, out string? eventName, out LogContextInfo logContext, out AvailabilityInfo? availabilityInfo, recognizeRoutingTags); + + TelemetryItem telemetryItem; + + if (logRecord.Exception is not null) + { + telemetryItem = new TelemetryItem("Exception", logRecord, resource, instrumentationKey, logContext) + { + Data = new MonitorBase { - telemetryItem = new TelemetryItem("Event", logRecord, resource, instrumentationKey, logContext) - { - Data = new MonitorBase - { - BaseType = "EventData", - BaseData = new TelemetryEventData(Version, eventName, properties, message, logRecord), - } - }; - telemetrySchemaTypeCounter._eventCount++; + BaseType = "ExceptionData", + BaseData = new TelemetryExceptionData(Version, logRecord, message, properties), } - else if (availabilityInfo is not null) + }; + if (telemetrySchemaTypeCounter is not null) + { + telemetrySchemaTypeCounter._exceptionCount++; + } + } + else if (eventName is not null) + { + telemetryItem = new TelemetryItem("Event", logRecord, resource, instrumentationKey, logContext) + { + Data = new MonitorBase { - DateTimeOffset envelopeTime = availabilityInfo.Value.TestTimestamp != null - && DateTimeOffset.TryParse( - availabilityInfo.Value.TestTimestamp, - CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.RoundtripKind, - out var parsedTs) - ? parsedTs.ToUniversalTime() - : TelemetryItem.FormatUtcTimestamp(logRecord.Timestamp); - - telemetryItem = new TelemetryItem("Availability", envelopeTime, logRecord, resource, instrumentationKey, logContext) - { - Data = new MonitorBase - { - BaseType = "AvailabilityData", - BaseData = new AvailabilityData(Version, availabilityInfo.Value, properties, logRecord), - } - }; - telemetrySchemaTypeCounter._availabilityCount++; + BaseType = "EventData", + BaseData = new TelemetryEventData(Version, eventName, properties, message, logRecord), } - else + }; + if (telemetrySchemaTypeCounter is not null) + { + telemetrySchemaTypeCounter._eventCount++; + } + } + else if (availabilityInfo is not null) + { + DateTimeOffset envelopeTime = availabilityInfo.Value.TestTimestamp != null + && DateTimeOffset.TryParse( + availabilityInfo.Value.TestTimestamp, + CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.RoundtripKind, + out var parsedTs) + ? parsedTs.ToUniversalTime() + : TelemetryItem.FormatUtcTimestamp(logRecord.Timestamp); + + telemetryItem = new TelemetryItem("Availability", envelopeTime, logRecord, resource, instrumentationKey, logContext) + { + Data = new MonitorBase { - telemetryItem = new TelemetryItem("Message", logRecord, resource, instrumentationKey, logContext) - { - Data = new MonitorBase - { - BaseType = "MessageData", - BaseData = new MessageData(Version, logRecord, message, properties), - } - }; - telemetrySchemaTypeCounter._traceCount++; + BaseType = "AvailabilityData", + BaseData = new AvailabilityData(Version, availabilityInfo.Value, properties, logRecord), } - - telemetryItems.Add(telemetryItem); + }; + if (telemetrySchemaTypeCounter is not null) + { + telemetrySchemaTypeCounter._availabilityCount++; } - catch (Exception ex) + } + else + { + telemetryItem = new TelemetryItem("Message", logRecord, resource, instrumentationKey, logContext) { - AzureMonitorExporterEventSource.Log.FailedToConvertLogRecord(instrumentationKey, ex); + Data = new MonitorBase + { + BaseType = "MessageData", + BaseData = new MessageData(Version, logRecord, message, properties), + } + }; + if (telemetrySchemaTypeCounter is not null) + { + telemetrySchemaTypeCounter._traceCount++; } } - return (telemetryItems, telemetrySchemaTypeCounter); + return telemetryItem; } - internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary properties, out string? message, out string? eventName, out LogContextInfo logContext, out AvailabilityInfo? availabilityInfo) + internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary properties, out string? message, out string? eventName, out LogContextInfo logContext, out AvailabilityInfo? availabilityInfo, bool recognizeRoutingTags = false) { eventName = null; availabilityInfo = null; @@ -166,6 +261,18 @@ internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary { switch (item.Key) { + // On the multi-tenant path these two attributes are consumed for routing, so drop + // them here rather than leak them into custom dimensions. On the single-tenant + // path (recognizeRoutingTags false) they fall through to default and become + // ordinary properties exactly as before. + case InstrumentationKeyAttributeName: + case IngestionEndpointAttributeName: + if (!recognizeRoutingTags) + { + goto default; + } + + break; case CustomEventAttributeName: eventName = item.Value?.ToString(); break; @@ -255,7 +362,7 @@ internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary // If we detected availability data, do a second pass to extract all availability attributes if (hasAvailabilityData) { - availabilityInfo = ExtractAvailabilityInfo(logRecord, properties, message, out logContext); + availabilityInfo = ExtractAvailabilityInfo(logRecord, properties, message, out logContext, recognizeRoutingTags); } logRecord.ForEachScope(s_processScope, properties); @@ -283,7 +390,7 @@ internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary } } - private static AvailabilityInfo? ExtractAvailabilityInfo(LogRecord logRecord, IDictionary properties, string? message, out LogContextInfo logContext) + private static AvailabilityInfo? ExtractAvailabilityInfo(LogRecord logRecord, IDictionary properties, string? message, out LogContextInfo logContext, bool recognizeRoutingTags = false) { string? availabilityId = null; string? availabilityName = null; @@ -298,6 +405,16 @@ internal static void ProcessLogRecordProperties(LogRecord logRecord, IDictionary { switch (item.Key) { + // Consumed for routing on the multi-tenant path; otherwise treated as an ordinary + // availability property, matching single-tenant behavior. + case InstrumentationKeyAttributeName: + case IngestionEndpointAttributeName: + if (!recognizeRoutingTags) + { + goto default; + } + + break; case AvailabilityIdAttributeName: availabilityId = item.Value?.ToString(); break; diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/MultiTenant/TenantRouting.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/MultiTenant/TenantRouting.cs index 83624308c496..73365a6afccc 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/MultiTenant/TenantRouting.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/src/Internals/MultiTenant/TenantRouting.cs @@ -42,12 +42,35 @@ internal static bool TryGetRoute( [NotNullWhen(true)] out string? instrumentationKey, [NotNullWhen(true)] out string? ingestionEndpoint) { - ingestionEndpoint = null; - // Only a string is accepted: ToString() on an array-valued tag yields "System.String[]", // which would become a tenant of its own. - var rawKey = mappedTags[SemanticSlot.MicrosoftInstrumentationKey] as string; - var trimmedKey = rawKey != null && rawKey.Length <= MaxInstrumentationKeyLength ? rawKey.Trim() : null; + return TryGetRoute( + mappedTags[SemanticSlot.MicrosoftInstrumentationKey] as string, + mappedTags[SemanticSlot.MicrosoftIngestionEndpoint] as string, + out instrumentationKey, + out ingestionEndpoint); + } + + /// + /// Validates raw routing values and reduces them to the canonical instrumentation key and + /// ingestion endpoint used to group telemetry. Signal-neutral: traces resolve the raw values + /// from an , logs from -free + /// LogRecord.Attributes, but both share this validation core. + /// + /// + /// A non-string value is rejected by the caller passing : an + /// array-valued attribute stringified to "System.String[]" would otherwise become a tenant + /// of its own. + /// + internal static bool TryGetRoute( + string? rawInstrumentationKey, + string? rawIngestionEndpoint, + [NotNullWhen(true)] out string? instrumentationKey, + [NotNullWhen(true)] out string? ingestionEndpoint) + { + ingestionEndpoint = null; + + var trimmedKey = rawInstrumentationKey != null && rawInstrumentationKey.Length <= MaxInstrumentationKeyLength ? rawInstrumentationKey.Trim() : null; if (trimmedKey == null || trimmedKey.Length == 0) { instrumentationKey = null; @@ -56,8 +79,7 @@ internal static bool TryGetRoute( instrumentationKey = trimmedKey; - var rawEndpoint = mappedTags[SemanticSlot.MicrosoftIngestionEndpoint] as string; - if (rawEndpoint == null || (ingestionEndpoint = NormalizeEndpoint(rawEndpoint)) == null) + if (rawIngestionEndpoint == null || (ingestionEndpoint = NormalizeEndpoint(rawIngestionEndpoint)) == null) { instrumentationKey = null; return false; diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Logs/MultiTenantLogDemo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Logs/MultiTenantLogDemo.cs new file mode 100644 index 000000000000..f9ff5b210961 --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Logs/MultiTenantLogDemo.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Threading; + +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.Monitor.OpenTelemetry.Exporter.Demo.Traces; + +using Microsoft.Extensions.Logging; + +using OpenTelemetry; +using OpenTelemetry.Logs; +using OpenTelemetry.Resources; + +namespace Azure.Monitor.OpenTelemetry.Exporter.Demo.Logs +{ + /// + /// Generates log traffic for several Application Insights components from a single exporter, to + /// exercise multi-tenant log routing end to end. Mirrors but + /// for s. + /// + /// + /// The switch this depends on is read once into a static, so + /// has to run before any exporter type + /// is touched. + /// + internal sealed class MultiTenantLogDemo : IDisposable + { + private readonly ILoggerFactory _loggerFactory; + private readonly TenantRoutingLogProcessor _routingProcessor; + + public MultiTenantLogDemo(string exporterConnectionString, IReadOnlyList routes, string runId, bool faultTenantEndpoints = false) + { + _routingProcessor = new TenantRoutingLogProcessor(routes, runId); + + var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(new Dictionary + { + { "service.name", "multi-tenant-demo" }, + { "service.version", "1.0.0-demo" }, + }); + + _loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.SetResourceBuilder(resourceBuilder); + + // Availability/event bodies are surfaced from the formatted message, so it has to + // be captured rather than dropped. + options.IncludeFormattedMessage = true; + + // Stamp the routing tags onto every LogRecord before the exporter's own + // processor sees it, the same way the trace demo stamps Activity tags. + options.AddProcessor(_routingProcessor); + + options.AddAzureMonitorLogExporter(o => + { + o.ConnectionString = exporterConnectionString; + + if (faultTenantEndpoints) + { + o.AddPolicy(new MultiTenantTraceDemo.FaultInjectionPolicy(routes), HttpPipelinePosition.PerRetry); + } + + o.AddPolicy(new MultiTenantTraceDemo.IngestionLoggingPolicy(), HttpPipelinePosition.PerCall); + }); + }); + }); + } + + // Attribute keys the exporter recognizes to classify a LogRecord into a specific Application + // Insights telemetry type. Kept in sync with LogsHelper's constants. + private const string CustomEventNameAttribute = "microsoft.custom_event.name"; + private const string AvailabilityIdAttribute = "microsoft.availability.id"; + private const string AvailabilityNameAttribute = "microsoft.availability.name"; + private const string AvailabilityDurationAttribute = "microsoft.availability.duration"; + private const string AvailabilitySuccessAttribute = "microsoft.availability.success"; + private const string AvailabilityRunLocationAttribute = "microsoft.availability.runLocation"; + + public IReadOnlyDictionary GeneratedPerTenant => _routingProcessor.Counts; + + /// + /// Emits every telemetry shape the log exporter can produce - trace (message), exception, + /// custom event, and availability - cycling through them so a routed batch carries a mix. + /// The classifying attributes are attached through a list-valued log state, which the SDK + /// surfaces verbatim as ; the routing processor then appends + /// the tenant tags in its OnEnd. + /// + public void GenerateLogs(int count) + { + var logger = _loggerFactory.CreateLogger(); + + for (int i = 0; i < count; i++) + { + switch (i % 4) + { + case 0: + // Trace / MessageData: an ordinary structured log with no special attributes. + logger.LogInformation("MultiTenantTrace-{iteration} from {source}.", i, "demo"); + break; + + case 1: + // ExceptionData: any LogRecord carrying an exception becomes an exception. + try + { + throw new InvalidOperationException($"Injected failure #{i}"); + } + catch (Exception ex) + { + logger.LogError(ex, "MultiTenantException-{iteration} failed.", i); + } + break; + + case 2: + // EventData: the microsoft.custom_event.name attribute names a custom event. + Emit( + logger, + LogLevel.Information, + $"MultiTenantEvent-{i}", + exception: null, + new KeyValuePair(CustomEventNameAttribute, "MultiTenantDemoEvent"), + new KeyValuePair("demo.iteration", i)); + break; + + default: + // AvailabilityData: requires id, name, duration, and success together. + Emit( + logger, + LogLevel.Information, + $"MultiTenantAvailability-{i}", + exception: null, + new KeyValuePair(AvailabilityIdAttribute, Guid.NewGuid().ToString("N")), + new KeyValuePair(AvailabilityNameAttribute, "MultiTenantDemoTest"), + new KeyValuePair(AvailabilityDurationAttribute, "00:00:01.500"), + new KeyValuePair(AvailabilitySuccessAttribute, i % 8 != 3), + new KeyValuePair(AvailabilityRunLocationAttribute, "demo-region")); + break; + } + + if (i % 250 == 0) + { + Thread.Sleep(10); + } + } + } + + /// + /// Logs with an explicit list-valued state so arbitrary attribute keys (including the + /// dotted microsoft.* classifiers, which are not valid message-template placeholders) + /// land verbatim on . + /// + private static void Emit(ILogger logger, LogLevel level, string message, Exception? exception, params KeyValuePair[] attributes) + { + var state = new List>(attributes); + logger.Log(level, new EventId(0), state, exception, (_, _) => message); + } + + public void Dispose() => _loggerFactory.Dispose(); + + /// + /// Stamps each with a randomly chosen tenant's routing attributes, so + /// one process feeds all components and every export batch spans several ingestion endpoints. + /// Attributes are the routing input for logs (scopes are not consulted), so they must land in + /// before the exporter runs. + /// + private sealed class TenantRoutingLogProcessor : BaseProcessor + { + private const string InstrumentationKeyAttributeName = "microsoft.instrumentation_key"; + private const string IngestionEndpointAttributeName = "microsoft.ingestion_endpoint"; + + private readonly IReadOnlyList _routes; + private readonly string _runId; + private readonly Random _random = new(Seed: 42); + private readonly Dictionary _counts = new(StringComparer.Ordinal); + private readonly object _lock = new(); + + internal TenantRoutingLogProcessor(IReadOnlyList routes, string runId) + { + _routes = routes; + _runId = runId; + + foreach (var route in routes) + { + _counts[route.Name] = 0; + } + } + + internal IReadOnlyDictionary Counts => _counts; + + public override void OnEnd(LogRecord logRecord) + { + MultiTenantTraceDemo.TenantRoute route; + + lock (_lock) + { + route = _routes[_random.Next(_routes.Count)]; + _counts[route.Name]++; + } + + var attributes = new List>(); + + if (logRecord.Attributes != null) + { + attributes.AddRange(logRecord.Attributes); + } + + attributes.Add(new KeyValuePair(InstrumentationKeyAttributeName, route.InstrumentationKey)); + attributes.Add(new KeyValuePair(IngestionEndpointAttributeName, route.IngestionEndpoint)); + + // Survives into customDimensions, so a query can count what actually arrived. + attributes.Add(new KeyValuePair("demo.run_id", _runId)); + attributes.Add(new KeyValuePair("demo.tenant", route.Name)); + + logRecord.Attributes = attributes; + } + } + } +} diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Program.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Program.cs index 8f53042464e1..00cdcb62b85c 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Program.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Program.cs @@ -36,6 +36,7 @@ public static void Main(string[] args) if (args.Length > 0 && string.Equals(args[0], "multitenant", StringComparison.OrdinalIgnoreCase)) { var faultEndpoints = Array.Exists(args, a => string.Equals(a, "down", StringComparison.OrdinalIgnoreCase)); + var logs = Array.Exists(args, a => string.Equals(a, "logs", StringComparison.OrdinalIgnoreCase)); var count = 1000; foreach (var arg in args) @@ -47,7 +48,15 @@ public static void Main(string[] args) } } - RunMultiTenantDemo(count, faultEndpoints); + if (logs) + { + RunMultiTenantLogDemo(count, faultEndpoints); + } + else + { + RunMultiTenantDemo(count, faultEndpoints); + } + return; } @@ -127,6 +136,65 @@ private static void RunMultiTenantDemo(int activityCount, bool faultEndpoints) Console.WriteLine($"Done in {stopwatch.Elapsed.TotalSeconds:F1}s. Query each component for demo.run_id == '{runId}'."); } + private static void RunMultiTenantLogDemo(int logCount, bool faultEndpoints) + { + var hostConnectionString = Environment.GetEnvironmentVariable(HostConnectionStringVariable); + var routes = ParseRoutes(Environment.GetEnvironmentVariable(RouteConnectionStringsVariable)); + + if (string.IsNullOrWhiteSpace(hostConnectionString) || routes.Count == 0) + { + Console.WriteLine($"Set {HostConnectionStringVariable} to the exporter's own connection string,"); + Console.WriteLine($"and {RouteConnectionStringsVariable} to a comma-separated list of one connection"); + Console.WriteLine("string per tenant, using components in different regions."); + return; + } + + // Before any exporter type is touched: the gate is read once into a static. + MultiTenantTraceDemo.EnableMultiTenantExport(); + + using var listener = new ExporterEventListener(); + + var runId = Guid.NewGuid().ToString("N"); + + var distinctEndpoints = new HashSet(routes.ConvertAll(r => r.IngestionEndpoint), StringComparer.Ordinal).Count; + + Console.WriteLine($"Run id : {runId}"); + Console.WriteLine($"Logs : {logCount} log records"); + Console.WriteLine($"Routes : {string.Join(", ", routes.ConvertAll(r => r.Name))}"); + Console.WriteLine($"Groups : {distinctEndpoints} distinct endpoint(s), so expect {distinctEndpoints} routed POST(s) per export"); + Console.WriteLine($"Endpoints : {(faultEndpoints ? "FAULTED (503 injected)" : "live")}"); + Console.WriteLine(); + + ReportStoredBlobs("stored before"); + + var stopwatch = Stopwatch.StartNew(); + + using (var demo = new MultiTenantLogDemo(hostConnectionString, routes, runId, faultEndpoints)) + { + demo.GenerateLogs(logCount); + + Console.WriteLine("Generated, flushing..."); + + foreach (var pair in demo.GeneratedPerTenant) + { + Console.WriteLine($" {pair.Key,-12} {pair.Value}"); + } + + if (!faultEndpoints) + { + // Give the storage drain a chance to run before the provider is torn down. + Thread.Sleep(TimeSpan.FromSeconds(15)); + } + } + + stopwatch.Stop(); + + ReportStoredBlobs("stored after"); + + Console.WriteLine(); + Console.WriteLine($"Done in {stopwatch.Elapsed.TotalSeconds:F1}s. Query each component for demo.run_id == '{runId}'."); + } + /// /// Turns connection strings into routes, naming each after its ingestion host so the console /// output and the demo.tenant dimension are readable. diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Traces/MultiTenantTraceDemo.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Traces/MultiTenantTraceDemo.cs index 50862293e5c0..a83e9756f829 100644 --- a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Traces/MultiTenantTraceDemo.cs +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Demo/Traces/MultiTenantTraceDemo.cs @@ -100,7 +100,7 @@ public void GenerateTraces(int count) /// retriable-failure path: back off the endpoint and persist the batch to that endpoint's /// partition. Statsbeat and any other host traffic is left alone. /// - private sealed class FaultInjectionPolicy : HttpPipelinePolicy + internal sealed class FaultInjectionPolicy : HttpPipelinePolicy { private readonly HashSet _faultedHosts = new(StringComparer.OrdinalIgnoreCase); @@ -170,7 +170,7 @@ protected override bool TryGetHeaderValues(string name, out IEnumerable } /// Reports where each batch went and what ingestion said about it. - private sealed class IngestionLoggingPolicy : HttpPipelinePolicy + internal sealed class IngestionLoggingPolicy : HttpPipelinePolicy { public override void Process(HttpMessage message, ReadOnlyMemory pipeline) { diff --git a/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/MultiTenantLogRoutingTests.cs b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/MultiTenantLogRoutingTests.cs new file mode 100644 index 000000000000..24143525645a --- /dev/null +++ b/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/tests/Azure.Monitor.OpenTelemetry.Exporter.Tests/MultiTenantLogRoutingTests.cs @@ -0,0 +1,633 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +using Azure.Monitor.OpenTelemetry.Exporter.Internals; +using Azure.Monitor.OpenTelemetry.Exporter.Internals.CustomerSdkStats; +using Azure.Monitor.OpenTelemetry.Exporter.Internals.Diagnostics; +using Azure.Monitor.OpenTelemetry.Exporter.Internals.MultiTenant; +using Azure.Monitor.OpenTelemetry.Exporter.Models; +using Azure.Monitor.OpenTelemetry.Exporter.Tests.CommonTestFramework; + +using Microsoft.Extensions.Logging; + +using OpenTelemetry; +using OpenTelemetry.Logs; + +using Xunit; + +namespace Azure.Monitor.OpenTelemetry.Exporter.Tests +{ + /// + /// The logs counterpart to : routing reads + /// instead of Activity tags, but the grouping, dropping, and + /// exporter gate behave the same. Because the SDK pools and recycles + /// instances, every conversion runs inside a batch export where the records are simultaneously + /// alive rather than by holding record references across calls. + /// + public class MultiTenantLogRoutingTests + { + private const string SourceName = nameof(MultiTenantLogRoutingTests); + private const string EastUs = "https://eastus-1.in.applicationinsights.azure.com/"; + private const string WestUs = "https://westus-2.in.applicationinsights.azure.com/"; + + private const string CustomEventAttributeName = "microsoft.custom_event.name"; + private const string AvailabilityIdAttributeName = "microsoft.availability.id"; + private const string AvailabilityNameAttributeName = "microsoft.availability.name"; + private const string AvailabilityDurationAttributeName = "microsoft.availability.duration"; + private const string AvailabilitySuccessAttributeName = "microsoft.availability.success"; + + private static KeyValuePair[] AvailabilityMarkers() => new[] + { + new KeyValuePair(AvailabilityIdAttributeName, "availability-id"), + new KeyValuePair(AvailabilityNameAttributeName, "MyTest"), + new KeyValuePair(AvailabilityDurationAttributeName, "00:00:01"), + new KeyValuePair(AvailabilitySuccessAttributeName, "true"), + }; + + [Fact] + public void MixedInstrumentationKeysOnOneEndpointCollapseToOneGroup() + { + var routeBatch = Convert( + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-b"), Endpoint(EastUs)), + Emit(Ikey("ikey-c"), Endpoint(EastUs))); + + Assert.Equal(1, routeBatch.Count); + Assert.Equal(EastUs, routeBatch[0].IngestionEndpoint); + Assert.Equal(3, routeBatch[0].TelemetryItems.Count); + } + + [Fact] + public void DistinctEndpointsBecomeDistinctGroups() + { + var routeBatch = Convert( + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-a"), Endpoint(WestUs)), + Emit(Ikey("ikey-b"), Endpoint(EastUs))); + + Assert.Equal(2, routeBatch.Count); + Assert.Equal(2, routeBatch[0].TelemetryItems.Count); + Assert.Single(routeBatch[1].TelemetryItems); + } + + [Fact] + public void EachItemCarriesItsOwnInstrumentationKey() + { + var routeBatch = Convert( + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-b"), Endpoint(EastUs))); + + Assert.Equal( + new[] { "ikey-a", "ikey-b" }, + routeBatch[0].TelemetryItems.Select(item => item.InstrumentationKey)); + } + + /// + /// On the routed path they are consumed, so they must not also appear as dimensions. + /// + [Fact] + public void RoutedTelemetryDoesNotCarryTheRoutingTagsAsCustomDimensions() + { + var routeBatch = Convert(Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + var properties = ((MessageData)routeBatch[0].TelemetryItems.Single().Data!.BaseData).Properties; + Assert.DoesNotContain(SemanticConventions.AttributeMicrosoftInstrumentationKey, properties.Keys); + Assert.DoesNotContain(SemanticConventions.AttributeMicrosoftIngestionEndpoint, properties.Keys); + } + + [Theory] + [InlineData(null, EastUs)] + [InlineData("", EastUs)] + [InlineData(" ", EastUs)] + [InlineData("ikey-a", null)] + [InlineData("ikey-a", "")] + [InlineData("ikey-a", "not-a-uri")] + [InlineData("ikey-a", "/relative/path")] + [InlineData("ikey-a", "ftp://example.com/")] + public void LogWithoutAValidRouteIsDropped(string? instrumentationKey, string? ingestionEndpoint) + { + var attributes = new List>(); + if (instrumentationKey != null) + { + attributes.Add(Ikey(instrumentationKey)); + } + + if (ingestionEndpoint != null) + { + attributes.Add(Endpoint(ingestionEndpoint)); + } + + Assert.Equal(0, Convert(Emit(attributes.ToArray())).Count); + } + + /// + /// A non-string value stringifies unpredictably, so it is dropped rather than routed, exactly + /// as the trace path rejects an array-valued tag. + /// + [Fact] + public void NonStringRoutingValueIsRejectedRatherThanStringified() + { + var routeBatch = Convert(Emit( + new KeyValuePair(SemanticConventions.AttributeMicrosoftInstrumentationKey, new[] { "ikey-a", "ikey-b" }), + Endpoint(EastUs))); + + Assert.Equal(0, routeBatch.Count); + } + + /// + /// First occurrence of each routing key wins, matching how the trace path fills an AzMonList. + /// + [Fact] + public void FirstOccurrenceOfARepeatedRoutingKeyWins() + { + var routeBatch = Convert(Emit( + Ikey("ikey-a"), + Endpoint(EastUs), + Ikey("ikey-b"), + Endpoint(WestUs))); + + Assert.Equal(1, routeBatch.Count); + Assert.Equal(EastUs, routeBatch[0].IngestionEndpoint); + Assert.Equal("ikey-a", routeBatch[0].TelemetryItems.Single().InstrumentationKey); + } + + [Fact] + public void InstrumentationKeyIsTrimmedSoSpacingDoesNotCreateATenant() + { + var routeBatch = Convert( + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey(" ikey-a "), Endpoint(EastUs))); + + Assert.Equal(1, routeBatch.Count); + Assert.All(routeBatch[0].TelemetryItems, item => Assert.Equal("ikey-a", item.InstrumentationKey)); + } + + [Fact] + public void OneUnroutableLogDoesNotDropTheRestOfTheBatch() + { + var routeBatch = Convert( + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(), + Emit(Ikey("ikey-b"), Endpoint(EastUs))); + + Assert.Equal(1, routeBatch.Count); + Assert.Equal(2, routeBatch[0].TelemetryItems.Count); + } + + /// + /// The availability marker makes the property loop break early, so routing must be detected in + /// its own pass: a route stamped after the marker must still be found, and neither routing tag + /// may leak into the availability envelope's properties. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AvailabilityLogRoutesRegardlessOfWhereTheRoutingTagsSit(bool routingTagsBeforeMarker) + { + var routingTags = new[] { Ikey("ikey-a"), Endpoint(EastUs) }; + var attributes = routingTagsBeforeMarker + ? routingTags.Concat(AvailabilityMarkers()).ToArray() + : AvailabilityMarkers().Concat(routingTags).ToArray(); + + var routeBatch = Convert(Emit(attributes)); + + Assert.Equal(1, routeBatch.Count); + Assert.Equal(EastUs, routeBatch[0].IngestionEndpoint); + + var telemetryItem = routeBatch[0].TelemetryItems.Single(); + Assert.Equal("AvailabilityData", telemetryItem.Data!.BaseType); + Assert.Equal("ikey-a", telemetryItem.InstrumentationKey); + + var properties = ((AvailabilityData)telemetryItem.Data!.BaseData).Properties; + Assert.DoesNotContain(SemanticConventions.AttributeMicrosoftInstrumentationKey, properties.Keys); + Assert.DoesNotContain(SemanticConventions.AttributeMicrosoftIngestionEndpoint, properties.Keys); + } + + /// + /// Nothing consumes the routing attributes outside the multi-tenant conversion, so on the + /// single-tenant path they must survive as ordinary custom dimensions rather than be dropped. + /// + [Fact] + public void SingleTenantPathKeepsRoutingTagsAsCustomDimensions() + { + var telemetryItems = ConvertSingleTenant("exporter-ikey", Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + var telemetryItem = telemetryItems.Single(); + Assert.Equal("exporter-ikey", telemetryItem.InstrumentationKey); + + var properties = ((MessageData)telemetryItem.Data!.BaseData).Properties; + Assert.Equal("ikey-a", properties[SemanticConventions.AttributeMicrosoftInstrumentationKey]); + Assert.Equal(EastUs, properties[SemanticConventions.AttributeMicrosoftIngestionEndpoint]); + } + + /// + /// Routing changes where an envelope goes and nothing about how it is built. Both sides use the + /// same instrumentation key, so this compares the conversion itself across every log shape. + /// + [Fact] + public void RoutedConversionProducesTheSameEnvelopesAsSingleTenant() + { + var sharedException = new InvalidOperationException("boom"); + + var corpus = new (string Message, Exception? Exception, KeyValuePair[] Markers)[] + { + ("message body", null, Array.Empty>()), + ("failed body", sharedException, Array.Empty>()), + ("event body", null, new[] { new KeyValuePair(CustomEventAttributeName, "my-event") }), + ("availability body", null, AvailabilityMarkers()), + }; + + // Without the routing tags the two paths see identical input, so any remaining difference + // is the conversion itself rather than the tags one path consumes. + var singleTenantItems = ConvertSingleTenant( + "ikey-a", + corpus.Select(entry => Emit(entry.Message, entry.Exception, entry.Markers)).ToArray()); + + var routeBatch = Convert( + corpus.Select(entry => Emit(entry.Message, entry.Exception, entry.Markers.Concat(new[] { Ikey("ikey-a"), Endpoint(EastUs) }).ToArray())).ToArray()); + + var singleTenant = Encoding.UTF8.GetString(HttpPipelineHelper.GetSerializedContent(singleTenantItems)); + var multiTenant = Encoding.UTF8.GetString(HttpPipelineHelper.GetSerializedContent(routeBatch[0].TelemetryItems)); + + Assert.Equal(Normalize(singleTenant), Normalize(multiTenant)); + } + + [Fact] + public void GateOffKeepsTheSingleTenantPath() + { + var run = RunExporter(multiTenantEnabled: false, Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + Assert.Equal(ExportResult.Success, run.Result); + Assert.Equal(1, run.Transmitter.TrackAsyncCallCount); + Assert.Equal(run.Transmitter.InstrumentationKey, run.Transmitter.TelemetryItems.Single().InstrumentationKey); + } + + /// + /// The data-boundary contract: routed telemetry must never reach the exporter's own + /// connection string. + /// + [Fact] + public void GateOnNeverFallsBackToTheExportersOwnTransmitter() + { + var run = RunExporter( + multiTenantEnabled: true, + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-b"), Endpoint(WestUs))); + + Assert.Equal(ExportResult.Success, run.Result); + Assert.Equal(0, run.Transmitter.TrackAsyncCallCount); + Assert.Empty(run.Transmitter.TelemetryItems); + } + + [Fact] + public void EachEndpointGroupIsSentToItsOwnEndpoint() + { + var run = RunExporter( + multiTenantEnabled: true, + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-b"), Endpoint(WestUs)), + Emit(Ikey("ikey-c"), Endpoint(EastUs))); + + Assert.Equal(2, run.Transmitter.Sends.Count); + + var eastUs = run.Transmitter.Sends.Single(send => send.IngestionEndpoint == EastUs); + Assert.Equal(new[] { "ikey-a", "ikey-c" }, eastUs.TelemetryItems.Select(item => item.InstrumentationKey)); + + var westUs = run.Transmitter.Sends.Single(send => send.IngestionEndpoint == WestUs); + Assert.Equal(new[] { "ikey-b" }, westUs.TelemetryItems.Select(item => item.InstrumentationKey)); + } + + [Fact] + public void ManyTenantsInOneRegionBecomeOneSend() + { + var run = RunExporter( + multiTenantEnabled: true, + Emit(Ikey("ikey-a"), Endpoint(EastUs)), + Emit(Ikey("ikey-b"), Endpoint(EastUs)), + Emit(Ikey("ikey-c"), Endpoint(EastUs))); + + Assert.Single(run.Transmitter.Sends); + Assert.Equal(3, run.Transmitter.Sends[0].TelemetryItems.Length); + } + + [Fact] + public void TransmissionFailureIsReportedToTheProvider() + { + var run = RunExporter( + configure: transmitter => transmitter.MultiTenantResult = ExportResult.Failure, + createExporter: transmitter => new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true), + Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + Assert.Equal(ExportResult.Failure, run.Result); + Assert.Single(run.Transmitter.Sends); + } + + [Fact] + public void GateOnWithNoRoutableLogReportsSuccess() + { + var run = RunExporter(multiTenantEnabled: true, Emit()); + + Assert.Equal(ExportResult.Success, run.Result); + Assert.Equal(0, run.Transmitter.TrackAsyncCallCount); + Assert.Empty(run.Transmitter.Sends); + } + + [Fact] + public void GateOnWithAnEmptyBatchReportsSuccess() + { + var transmitter = new MockTransmitter(new List()); + using var exporter = new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true); + + Assert.Equal(ExportResult.Success, exporter.Export(new Batch(Array.Empty(), 0))); + } + + [Fact] + public void RepeatedExportsLeaveTheCachedRouteBatchEmpty() + { + var transmitter = new MockTransmitter(new List()); + using var exporter = new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true); + + WithLiveBatch(batch => exporter.Export(batch), Emit(Ikey("ikey-a"), Endpoint(EastUs)), Emit(Ikey("ikey-b"), Endpoint(EastUs))); + WithLiveBatch(batch => exporter.Export(batch), Emit(Ikey("ikey-c"), Endpoint(WestUs))); + + var routeBatch = (EndpointRouteBatch?)typeof(AzureMonitorLogExporter) + .GetField("_routeBatch", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(exporter); + + Assert.NotNull(routeBatch); + Assert.Equal(0, routeBatch!.Count); + } + + /// + /// With the gate off the multi-tenant machinery must not even be allocated. + /// + [Fact] + public void GateOffAllocatesNoRouteBatch() + { + var run = RunExporter(multiTenantEnabled: false, Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + var routeBatch = typeof(AzureMonitorLogExporter) + .GetField("_routeBatch", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(run.Exporter); + + Assert.Null(routeBatch); + } + + [Fact] + public void MultiTenantExportRequiresAMultiTenantTransmitter() + { + var transmitter = new SingleTenantOnlyTransmitter(); + + Assert.Throws( + () => new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true)); + + Assert.True(transmitter.Disposed); + } + + [Fact] + public void GateDefaultsToOff() + { + Assert.False(MultiTenantConfig.Enabled); + + var run = RunExporter( + configure: null, + createExporter: transmitter => new AzureMonitorLogExporter(transmitter), + Emit(Ikey("ikey-a"), Endpoint(EastUs))); + + Assert.Equal(ExportResult.Success, run.Result); + Assert.Equal(1, run.Transmitter.TrackAsyncCallCount); + } + + /// + /// Trace-based logs sampling runs in the OTel pipeline before the exporter, so a routed log + /// tied to an unsampled parent span never reaches the routing path, while a sampled or + /// trace-less routed log does. + /// + [Fact] + public void TraceBasedFilteringDropsUnsampledRoutedLogsBeforeRouting() + { + var transmitter = new MockTransmitter(new List()); + using var exporter = new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true); + + using (var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.IncludeFormattedMessage = true; + options.AddProcessor(new LogFilteringProcessor(exporter)); + }); + builder.AddFilter(SourceName, LogLevel.Trace); + })) + { + var logger = loggerFactory.CreateLogger(SourceName); + + using (var unsampled = new Activity("unsampled")) + { + unsampled.ActivityTraceFlags = ActivityTraceFlags.None; + unsampled.Start(); + Emit(Ikey("ikey-dropped"), Endpoint(EastUs))(logger); + } + + using (var sampled = new Activity("sampled")) + { + sampled.ActivityTraceFlags = ActivityTraceFlags.Recorded; + sampled.Start(); + Emit(Ikey("ikey-sampled"), Endpoint(EastUs))(logger); + } + + // No parent span at all: reaches routing. + Emit(Ikey("ikey-traceless"), Endpoint(WestUs))(logger); + } + + var routed = transmitter.Sends + .SelectMany(send => send.TelemetryItems.Select(item => item.InstrumentationKey)) + .ToList(); + + Assert.DoesNotContain("ikey-dropped", routed); + Assert.Contains("ikey-sampled", routed); + Assert.Contains("ikey-traceless", routed); + } + + /// + /// On a persist-only shutdown a routed log still goes through the multi-tenant + /// path (not TrackAsync), exercising the + /// log-exporter-specific wiring. + /// + [Fact] + public void RoutedLogUsesTheMultiTenantTrackPathDuringPersistOnlyShutdown() + { + var transmitter = new MockTransmitter(new List()); + using var exporter = new AzureMonitorLogExporter(transmitter, multiTenantEnabled: true); + + using (var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.IncludeFormattedMessage = true; + options.AddProcessor(new AzureMonitorBatchLogRecordExportProcessor(exporter)); + }); + builder.AddFilter(SourceName, LogLevel.Trace); + })) + { + var logger = loggerFactory.CreateLogger(SourceName); + Emit(Ikey("ikey-a"), Endpoint(EastUs))(logger); + + // Disposal shuts the processor down; persist-on-shutdown is on by default. + } + + Assert.True(transmitter.PersistOnlyScopeCount >= 1); + Assert.Equal(0, transmitter.TrackAsyncCallCount); + Assert.Single(transmitter.Sends); + Assert.Equal(EastUs, transmitter.Sends[0].IngestionEndpoint); + Assert.Equal(new[] { "ikey-a" }, transmitter.Sends[0].TelemetryItems.Select(item => item.InstrumentationKey)); + } + + private EndpointRouteBatch Convert(params Action[] emits) + { + var routeBatch = new EndpointRouteBatch(); + WithLiveBatch(batch => LogsHelper.OtelToAzureMonitorLogsMultiTenant(batch, null, routeBatch), emits); + return routeBatch; + } + + private List ConvertSingleTenant(string instrumentationKey, params Action[] emits) + { + List telemetryItems = new(); + WithLiveBatch(batch => telemetryItems = LogsHelper.OtelToAzureMonitorLogs(batch, null, instrumentationKey).TelemetryItems, emits); + return telemetryItems; + } + + private ExporterRun RunExporter(bool multiTenantEnabled, params Action[] emits) + => RunExporter(configure: null, createExporter: transmitter => new AzureMonitorLogExporter(transmitter, multiTenantEnabled), emits); + + private ExporterRun RunExporter(Action? configure, Func createExporter, params Action[] emits) + { + var transmitter = new MockTransmitter(new List()); + configure?.Invoke(transmitter); + + var exporter = createExporter(transmitter); + var run = new ExporterRun { Transmitter = transmitter, Exporter = exporter, Result = ExportResult.Success }; + + WithLiveBatch(batch => run.Result = exporter.Export(batch), emits); + + return run; + } + + /// + /// Emits the records through a batch processor and hands the live to + /// during a single forced flush, so the pooled records are all valid at + /// once and are never referenced after they return to the pool. + /// + private void WithLiveBatch(Action> use, params Action[] emits) + { + var exporter = new CaptureExporter(use); + var processor = new BatchLogRecordExportProcessor( + exporter, + maxQueueSize: 4096, + scheduledDelayMilliseconds: 60000, + exporterTimeoutMilliseconds: 30000, + maxExportBatchSize: 4096); + + using (var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.IncludeFormattedMessage = true; + options.AddProcessor(processor); + }); + builder.AddFilter(SourceName, LogLevel.Trace); + })) + { + var logger = loggerFactory.CreateLogger(SourceName); + foreach (var emit in emits) + { + emit(logger); + } + + processor.ForceFlush(); + } + } + + private static KeyValuePair Ikey(object? value) + => new(SemanticConventions.AttributeMicrosoftInstrumentationKey, value); + + private static KeyValuePair Endpoint(object? value) + => new(SemanticConventions.AttributeMicrosoftIngestionEndpoint, value); + + private static Action Emit(params KeyValuePair[] attributes) + => Emit("Test log message", null, attributes); + + private static Action Emit(string message, Exception? exception, params KeyValuePair[] attributes) + { + // A list state is surfaced verbatim as LogRecord.Attributes, which lets a test place the + // routing tags at any position (including after an availability marker) and use non-string + // values without going through structured message formatting. + var state = attributes.ToList(); + return logger => logger.Log(LogLevel.Information, new EventId(0), state, exception, (_, _) => message); + } + + /// + /// Timestamps differ between two emissions of the same corpus; nothing else may. + /// + private static string Normalize(string payload) => Regex.Replace( + payload, + "\"(time)\":\"[^\"]*\"", + "\"$1\":\"\""); + + private sealed class ExporterRun + { + public ExportResult Result { get; set; } + + public MockTransmitter Transmitter { get; set; } = null!; + + public AzureMonitorLogExporter Exporter { get; set; } = null!; + } + + private sealed class CaptureExporter : BaseExporter + { + private readonly Action> _onExport; + + public CaptureExporter(Action> onExport) => _onExport = onExport; + + public override ExportResult Export(in Batch batch) + { + _onExport(batch); + return ExportResult.Success; + } + } + + private sealed class SingleTenantOnlyTransmitter : ITransmitter + { + public string InstrumentationKey => "single-tenant-ikey"; + + public bool Disposed { get; private set; } + + public ValueTask TrackAsync(IEnumerable telemetryItems, TelemetrySchemaTypeCounter telemetrySchemaTypeCounter, TelemetryItemOrigin origin, bool async, CancellationToken cancellationToken) + => new(ExportResult.Success); + + public IDisposable BeginPersistOnlyScope() => new NoopScope(); + + public void DrainStorage(int waitMilliseconds) + { + } + + public void Dispose() => Disposed = true; + + private sealed class NoopScope : IDisposable + { + public void Dispose() + { + } + } + } + } +}