From 65792c0b48117d88861a8b446fbed7d463696ec8 Mon Sep 17 00:00:00 2001 From: Long Date: Wed, 22 Jan 2025 17:50:59 +0000 Subject: [PATCH] First commit --- .../ServiceContext}/EmptyServiceContext.cs | 10 +- .../ServiceContext}/IServiceContext.cs | 2 +- src/Hosting.Services/HostBuilderExtensions.cs | 12 +- .../Internal/OmexServiceFabricContext.cs | 2 +- src/Hosting/ServiceCollectionExtensions.cs | 10 +- src/Logging/InitializationLogger.cs | 21 +-- .../EventSource/OmexLogEventSender.cs | 126 ---------------- .../EventSource/OmexLogEventSource.cs | 134 ------------------ .../ServiceInitializationEventSource.cs | 1 - .../Internal/OmexLoggerOptionsSetup.cs | 17 --- src/Logging/Internal/OmexLoggerProvider.cs | 46 ------ src/Logging/ServiceCollectionExtensions.cs | 48 +------ .../HostBuilderExtensionsTests.cs | 7 +- .../OmexServiceFabricContextTests.cs | 2 +- .../HostBuilderExtensionsTests.cs | 3 +- .../EmptyServiceContextTests.cs | 1 + .../OmexLogEventSenderTests.cs | 68 --------- .../OmexLoggerProviderTests.cs | 69 --------- .../ServiceCollectionExtensionsTests.cs | 5 +- .../ServiceCollectionTests.cs | 24 +--- 20 files changed, 39 insertions(+), 569 deletions(-) rename src/{Logging/Internal/EventSource => Abstractions/ServiceContext}/EmptyServiceContext.cs (54%) rename src/{Logging => Abstractions/ServiceContext}/IServiceContext.cs (86%) delete mode 100644 src/Logging/Internal/EventSource/OmexLogEventSender.cs delete mode 100644 src/Logging/Internal/EventSource/OmexLogEventSource.cs delete mode 100644 src/Logging/Internal/OmexLoggerOptionsSetup.cs delete mode 100644 src/Logging/Internal/OmexLoggerProvider.cs delete mode 100644 tests/Logging.UnitTests/OmexLogEventSenderTests.cs delete mode 100644 tests/Logging.UnitTests/OmexLoggerProviderTests.cs diff --git a/src/Logging/Internal/EventSource/EmptyServiceContext.cs b/src/Abstractions/ServiceContext/EmptyServiceContext.cs similarity index 54% rename from src/Logging/Internal/EventSource/EmptyServiceContext.cs rename to src/Abstractions/ServiceContext/EmptyServiceContext.cs index f0b6f0d4..e650c68a 100644 --- a/src/Logging/Internal/EventSource/EmptyServiceContext.cs +++ b/src/Abstractions/ServiceContext/EmptyServiceContext.cs @@ -3,15 +3,21 @@ using System; -namespace Microsoft.Omex.Extensions.Logging +namespace Microsoft.Omex.Extensions.Abstractions.ServiceContext { /// /// IServiceContext without any information /// - internal class EmptyServiceContext : IServiceContext + public class EmptyServiceContext : IServiceContext { + /// + /// Service fabric PartitionId + /// public Guid PartitionId => Guid.Empty; + /// + /// Service fabric + /// public long ReplicaOrInstanceId => 0; } } diff --git a/src/Logging/IServiceContext.cs b/src/Abstractions/ServiceContext/IServiceContext.cs similarity index 86% rename from src/Logging/IServiceContext.cs rename to src/Abstractions/ServiceContext/IServiceContext.cs index 2a1d9c4a..502c5b07 100644 --- a/src/Logging/IServiceContext.cs +++ b/src/Abstractions/ServiceContext/IServiceContext.cs @@ -3,7 +3,7 @@ using System; -namespace Microsoft.Omex.Extensions.Logging +namespace Microsoft.Omex.Extensions.Abstractions.ServiceContext { /// /// Interface with service context information diff --git a/src/Hosting.Services/HostBuilderExtensions.cs b/src/Hosting.Services/HostBuilderExtensions.cs index 6fb4ede5..62f80d37 100644 --- a/src/Hosting.Services/HostBuilderExtensions.cs +++ b/src/Hosting.Services/HostBuilderExtensions.cs @@ -8,9 +8,11 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Configuration; using Microsoft.Omex.Extensions.Abstractions; using Microsoft.Omex.Extensions.Abstractions.Accessors; using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; using Microsoft.Omex.Extensions.Logging; using Microsoft.ServiceFabric.Data; @@ -97,20 +99,20 @@ private static IHost BuildServiceFabricService( .AddOmexServiceFabricDependencies() .AddSingleton() .AddHostedService(); + collection.TryAddTransient(); + collection.TryAddTransient(); }) .UseDefaultServiceProvider(options => { options.ValidateOnBuild = true; options.ValidateScopes = true; }) -#pragma warning disable OMEX188 // AddOmexLogging using OmexLogger is obsolete. DiagnosticId = "OMEX188" - .ConfigureLogging(builder => builder.AddOmexLogging()) -#pragma warning restore OMEX188 // AddOmexLogging using OmexLogger is obsolete. DiagnosticId = "OMEX188" + .ConfigureLogging(builder => builder.AddConfiguration()) .Build(); -#pragma warning disable OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" + InitializationLogger.CustomizeInitializationLoggerBuilder(loggingBuilder => loggingBuilder.AddConsole()); + InitializationLogger.LogInitializationSucceed(serviceNameForLogging); -#pragma warning restore OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" return host; } diff --git a/src/Hosting.Services/Internal/OmexServiceFabricContext.cs b/src/Hosting.Services/Internal/OmexServiceFabricContext.cs index c8592cb7..5f7d31ad 100644 --- a/src/Hosting.Services/Internal/OmexServiceFabricContext.cs +++ b/src/Hosting.Services/Internal/OmexServiceFabricContext.cs @@ -4,7 +4,7 @@ using System; using System.Fabric; using Microsoft.Omex.Extensions.Abstractions; -using Microsoft.Omex.Extensions.Logging; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; namespace Microsoft.Omex.Extensions.Hosting.Services { diff --git a/src/Hosting/ServiceCollectionExtensions.cs b/src/Hosting/ServiceCollectionExtensions.cs index 1f85e8f1..78a68f0f 100644 --- a/src/Hosting/ServiceCollectionExtensions.cs +++ b/src/Hosting/ServiceCollectionExtensions.cs @@ -1,12 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Omex.Extensions.Hosting.Certificates; -using Microsoft.Omex.Extensions.Logging; namespace Microsoft.Omex.Extensions.Hosting { @@ -18,7 +16,6 @@ public static class ServiceCollectionExtensions /// /// Add Omex Logging and ActivitySource dependencies /// - [Obsolete($"Please do not use {nameof(AddOmexServices)} if you just want to use Legacy OmexLogger and ActivityEventSender because they are deprecated. Consider using a different telemetry solution. This method is pending for removal by 1 July 2024. Code: 8913598.")] public static IHostBuilder AddOmexServices(this IHostBuilder builder) => builder .ConfigureServices((context, collection) => collection.AddOmexServices()); @@ -26,13 +23,8 @@ public static IHostBuilder AddOmexServices(this IHostBuilder builder) => /// /// Add Omex Logging and ActivitySource dependencies /// - [Obsolete($"Please do not use {nameof(AddOmexServices)} if you just want to use Legacy OmexLogger and ActivityEventSender because they are deprecated. Consider using a different telemetry solution. This method is pending for removal by 1 July 2024. Code: 8913598.")] public static IServiceCollection AddOmexServices(this IServiceCollection collection) => -#pragma warning disable OMEX188 // OmexLogger and OmexLogEventSource are obsolete and pending for removal by 1 July 2024. Please consider using a different Logger. - collection - .AddOmexLogging() -#pragma warning restore OMEX188 // OmexLogger and OmexLogEventSource are obsolete and pending for removal by 1 July 2024. Please consider using a different Logger. - .AddOmexActivitySource(); + collection.AddOmexActivitySource(); /// /// Add Omex Logging and ActivitySource dependencies diff --git a/src/Logging/InitializationLogger.cs b/src/Logging/InitializationLogger.cs index 44d0b978..651ee23d 100644 --- a/src/Logging/InitializationLogger.cs +++ b/src/Logging/InitializationLogger.cs @@ -11,27 +11,28 @@ namespace Microsoft.Omex.Extensions.Logging /// InitializationLogger is the logger to be used before the proper ILogger from DI is set. /// Not to be used as main logger. /// - [Obsolete($"{nameof(InitializationLogger)} using {nameof(OmexLogger)} is obsolete and is pending for removal by 1 July 2024.", DiagnosticId = "OMEX188")] public static class InitializationLogger { /// /// Instance of logger /// public static ILogger Instance { get; private set; } = LoggerFactory.Create(builder => - { - builder.LoadInitializationLogger(); - }).CreateLogger("Initial-Logging"); - - private static ILoggingBuilder LoadInitializationLogger(this ILoggingBuilder builder) { if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") { builder.AddConsole(); } - builder.AddOmexLogging(); - return builder; - } + s_loggingBuilderAction?.Invoke(builder); + }).CreateLogger("Initial-Logging"); + + /// + /// Action to customize the initialization logger builder + /// + /// + public static void CustomizeInitializationLoggerBuilder(Action action) => s_loggingBuilderAction = action; + + private static Action? s_loggingBuilderAction; /// /// Log on successful building @@ -56,7 +57,7 @@ public static void LogInitializationSucceed(string serviceNameForLogging, string /// Service name for logging /// Exception to log /// Message to log - public static void LogInitializationFail(string serviceNameForLogging, Exception? ex = null, string message = "") + public static void LogInitializationFail(string serviceNameForLogging, Exception? ex = null, string message = "") { ServiceInitializationEventSource.Instance.LogHostFailed(ex?.ToString() ?? string.Empty, serviceNameForLogging, message); Instance.LogError(Tag.Create(), ex, message); diff --git a/src/Logging/Internal/EventSource/OmexLogEventSender.cs b/src/Logging/Internal/EventSource/OmexLogEventSender.cs deleted file mode 100644 index 1cb81017..00000000 --- a/src/Logging/Internal/EventSource/OmexLogEventSender.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics; -using System.Globalization; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Abstractions.Activities; -using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; - -namespace Microsoft.Omex.Extensions.Logging -{ - [Obsolete($"{nameof(OmexLogEventSender)} is obsolete and pending for removal by 1 July 2024.", DiagnosticId = "OMEX188")] - internal sealed class OmexLogEventSender : ILogEventSender - { - static OmexLogEventSender() - { - using Process process = Process.GetCurrentProcess(); - s_processName = string.Format(CultureInfo.InvariantCulture, "{0} (0x{1:X4})", process.ProcessName, process.Id); - } - - public OmexLogEventSender(OmexLogEventSource eventSource, IExecutionContext executionContext, IServiceContext context, IOptionsMonitor options) - { - m_eventSource = eventSource; - m_executionContext = executionContext; - m_serviceContext = context; - m_options = options; - } - - public void LogMessage(Activity? activity, string category, LogLevel level, EventId eventId, int threadId, string message, Exception? exception) - { - if (!IsEnabled(level)) - { - return; - } - - // NOTE: Currently, we're not doing anything with the exception as the message when an exception is logged will already contain the exception details. - // However, in the future, it's possible we might want to log details, such as exception type or exception message, in separate columns. - - Guid partitionId = m_serviceContext.PartitionId; - long replicaId = m_serviceContext.ReplicaOrInstanceId; - string applicationName = m_executionContext.ApplicationName; - string serviceName = m_executionContext.ServiceName; - string buildVersion = m_executionContext.BuildVersion; - string machineId = m_executionContext.MachineId; - - string tagName = eventId.Name ?? string.Empty; - // In case if tag created using Tag.Create (line number and file in description) it's better to display decimal number - string tagId = string.IsNullOrWhiteSpace(eventId.Name) - ? eventId.ToTagId() - : eventId.Id.ToString(CultureInfo.InvariantCulture); - - string activityId = string.Empty; - ActivityTraceId activityTraceId = default; - Guid obsoleteCorrelationId = Guid.Empty; - uint obsoleteTransactionId = 0u; - bool isHealthCheck = false; - if (activity != null) - { - activityId = activity.Id ?? string.Empty; - activityTraceId = activity.TraceId; - isHealthCheck = activity.IsHealthCheck(); - - if (m_options.CurrentValue.AddObsoleteCorrelationToActivity) - { -#pragma warning disable CS0618 // We are using obsolete correlation to support logging correlation from old Omex services - obsoleteCorrelationId = activity.GetObsoleteCorrelationId() ?? activity.GetRootIdAsGuid() ?? Guid.Empty; - obsoleteTransactionId = activity.GetObsoleteTransactionId() ?? 0u; -#pragma warning restore CS0618 - } - } - - string traceIdAsString = activityTraceId.ToHexString(); - - //Event methods should have all information as parameters so we are passing them each time - // Possible Breaking changes: - // 1. ThreadId type Changed from string to avoid useless string creation - // 2. New fields added: - // a. tagName to events since it will have more useful information - // b. activityId required for tracking net core activity - // c. activityTraceId required for tracking net core activity - switch (level) - { - case LogLevel.None: - break; - case LogLevel.Trace: - m_eventSource.LogSpamServiceMessage(applicationName, serviceName, machineId, buildVersion, s_processName, partitionId, replicaId, - activityId, traceIdAsString, obsoleteCorrelationId, obsoleteTransactionId, "Spam", category, tagId, tagName, threadId, message, isHealthCheck); - break; - case LogLevel.Debug: - m_eventSource.LogVerboseServiceMessage(applicationName, serviceName, machineId, buildVersion, s_processName, partitionId, replicaId, - activityId, traceIdAsString, obsoleteCorrelationId, obsoleteTransactionId, "Verbose", category, tagId, tagName, threadId, message, isHealthCheck); - break; - case LogLevel.Information: - m_eventSource.LogInfoServiceMessage(applicationName, serviceName, machineId, buildVersion, s_processName, partitionId, replicaId, - activityId, traceIdAsString, obsoleteCorrelationId, obsoleteTransactionId, "Info", category, tagId, tagName, threadId, message, isHealthCheck); - break; - case LogLevel.Warning: - m_eventSource.LogWarningServiceMessage(applicationName, serviceName, machineId, buildVersion, s_processName, partitionId, replicaId, - activityId, traceIdAsString, obsoleteCorrelationId, obsoleteTransactionId, "Warning", category, tagId, tagName, threadId, message, isHealthCheck); - break; - case LogLevel.Error: - case LogLevel.Critical: - m_eventSource.LogErrorServiceMessage(applicationName, serviceName, machineId, buildVersion, s_processName, partitionId, replicaId, - activityId, traceIdAsString, obsoleteCorrelationId, obsoleteTransactionId, "Error", category, tagId, tagName, threadId, message, isHealthCheck); - break; - default: - throw new ArgumentException(FormattableString.Invariant($"Unknown EventLevel: {level}")); - } - } - - public bool IsEnabled(LogLevel level) => - level switch - { - LogLevel.None => false, - _ => m_eventSource.IsEnabled() - }; - - private readonly OmexLogEventSource m_eventSource; - private readonly IServiceContext m_serviceContext; - private readonly IOptionsMonitor m_options; - private readonly IExecutionContext m_executionContext; - private static readonly string s_processName; - } -} diff --git a/src/Logging/Internal/EventSource/OmexLogEventSource.cs b/src/Logging/Internal/EventSource/OmexLogEventSource.cs deleted file mode 100644 index 50678e51..00000000 --- a/src/Logging/Internal/EventSource/OmexLogEventSource.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics.Tracing; -using Microsoft.Omex.Extensions.Abstractions.EventSources; - -namespace Microsoft.Omex.Extensions.Logging -{ - // Renamed from Microsoft-OMEX-Logs to avoid conflict with sources in other libraries - [Obsolete($"{nameof(OmexLogEventSource)} is obsolete and pending for removal by 1 July 2024.", DiagnosticId = "OMEX188")] - [EventSource(Name = "Microsoft-OMEX-Logs-Ext")] - internal sealed class OmexLogEventSource : EventSource - { - [Event((int)EventSourcesEventIds.LogError, Level = EventLevel.Error, Message = "{12}:{13} {16}", Version = 7)] - public void LogErrorServiceMessage( - string applicationName, - string serviceName, - string agentName, - string buildVersion, - string processName, - Guid partitionId, - long replicaId, - string activityId, - string activityTraceId, - Guid correlationId, - uint transactionId, - string level, - string category, - string tagId, - string tagName, - int threadId, - string message, - bool isHealthCheck) => - WriteEvent((int)EventSourcesEventIds.LogError, applicationName, serviceName, agentName, buildVersion, processName, partitionId, replicaId, - activityId, activityTraceId, correlationId, transactionId, level, category, tagId, tagName, threadId, message, isHealthCheck); - - [Event((int)EventSourcesEventIds.LogWarning, Level = EventLevel.Warning, Message = "{12}:{13} {16}", Version = 7)] - public void LogWarningServiceMessage( - string applicationName, - string serviceName, - string agentName, - string buildVersion, - string processName, - Guid partitionId, - long replicaId, - string activityId, - string activityTraceId, - Guid correlationId, - uint transactionId, - string level, - string category, - string tagId, - string tagName, - int threadId, - string message, - bool isHealthCheck) => - WriteEvent((int)EventSourcesEventIds.LogWarning, applicationName, serviceName, agentName, buildVersion, processName, partitionId, replicaId, - activityId, activityTraceId, correlationId, transactionId, level, category, tagId, tagName, threadId, message, isHealthCheck); - - [Event((int)EventSourcesEventIds.LogInfo, Level = EventLevel.Informational, Message = "{12}:{13} {16}", Version = 7)] - public void LogInfoServiceMessage( - string applicationName, - string serviceName, - string agentName, - string buildVersion, - string processName, - Guid partitionId, - long replicaId, - string activityId, - string activityTraceId, - Guid correlationId, - uint transactionId, - string level, - string category, - string tagId, - string tagName, - int threadId, - string message, - bool isHealthCheck) => - WriteEvent((int)EventSourcesEventIds.LogInfo, applicationName, serviceName, agentName, buildVersion, processName, partitionId, replicaId, - activityId, activityTraceId, correlationId, transactionId, level, category, tagId, tagName, threadId, message, isHealthCheck); - - [Event((int)EventSourcesEventIds.LogVerbose, Level = EventLevel.Verbose, Message = "{12}:{13} {16}", Version = 7)] - public void LogVerboseServiceMessage( - string applicationName, - string serviceName, - string agentName, - string buildVersion, - string processName, - Guid partitionId, - long replicaId, - string activityId, - string activityTraceId, - Guid correlationId, - uint transactionId, - string level, - string category, - string tagId, - string tagName, - int threadId, - string message, - bool isHealthCheck) => - WriteEvent((int)EventSourcesEventIds.LogVerbose, applicationName, serviceName, agentName, buildVersion, processName, partitionId, replicaId, - activityId, activityTraceId, correlationId, transactionId, level, category, tagId, tagName, threadId, message, isHealthCheck); - - [Event((int)EventSourcesEventIds.LogSpam, Level = EventLevel.Verbose, Message = "{12}:{13} {16}", Version = 7)] - public void LogSpamServiceMessage( - string applicationName, - string serviceName, - string agentName, - string buildVersion, - string processName, - Guid partitionId, - long replicaId, - string activityId, - string activityTraceId, - Guid correlationId, - uint transactionId, - string level, - string category, - string tagId, - string tagName, - int threadId, - string message, - bool isHealthCheck) => - WriteEvent((int)EventSourcesEventIds.LogSpam, applicationName, serviceName, agentName, buildVersion, processName, partitionId, replicaId, - activityId, activityTraceId, correlationId, transactionId, level, category, tagId, tagName, threadId, message, isHealthCheck); - - public static OmexLogEventSource Instance { get; } = new OmexLogEventSource(); - - private OmexLogEventSource() { } - } -} diff --git a/src/Logging/Internal/EventSource/ServiceInitializationEventSource.cs b/src/Logging/Internal/EventSource/ServiceInitializationEventSource.cs index 1bb7f6da..db9c1839 100644 --- a/src/Logging/Internal/EventSource/ServiceInitializationEventSource.cs +++ b/src/Logging/Internal/EventSource/ServiceInitializationEventSource.cs @@ -11,7 +11,6 @@ namespace Microsoft.Omex.Extensions.Logging /// Service Fabric event source /// [EventSource(Name = "Microsoft-OMEX-HostLogs")] - [Obsolete($"{nameof(ServiceInitializationEventSource)} is obsolete and is pending for removal by 1 July 2024.", DiagnosticId = "OMEX188")] internal sealed class ServiceInitializationEventSource : EventSource { /// diff --git a/src/Logging/Internal/OmexLoggerOptionsSetup.cs b/src/Logging/Internal/OmexLoggerOptionsSetup.cs deleted file mode 100644 index d559d188..00000000 --- a/src/Logging/Internal/OmexLoggerOptionsSetup.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using Microsoft.Extensions.Logging.Configuration; -using Microsoft.Extensions.Options; - -namespace Microsoft.Omex.Extensions.Logging; - -internal class OmexLoggerOptionsSetup : ConfigureFromConfigurationOptions -{ - [Obsolete("OmexLoggerOptionsSetup is deprecated and pending for removal on 1 July 2024", DiagnosticId = "OMEX188")] - public OmexLoggerOptionsSetup(ILoggerProviderConfiguration providerConfiguration) - : base(providerConfiguration.Configuration) - { - } -} diff --git a/src/Logging/Internal/OmexLoggerProvider.cs b/src/Logging/Internal/OmexLoggerProvider.cs deleted file mode 100644 index 5ee8c031..00000000 --- a/src/Logging/Internal/OmexLoggerProvider.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Logging.Replayable; -using Microsoft.Omex.Extensions.Logging.Scrubbing; - -namespace Microsoft.Omex.Extensions.Logging -{ - [ProviderAlias("Omex")] - [Obsolete($"{nameof(OmexLogger)} and {nameof(OmexLogEventSource)} are obsolete and pending for removal by 1 July 2024. Please consider using a different logging solution.", DiagnosticId = "OMEX188")] - internal class OmexLoggerProvider : ILoggerProvider, ISupportExternalScope - { - public OmexLoggerProvider( - ILogEventSender logsEventSender, - IExternalScopeProvider defaultExternalScopeProvider, - IEnumerable textScrubbers, - IOptions options, - ILogEventReplayer? replayer = null) - { - m_logsEventSender = logsEventSender; - m_defaultExternalScopeProvider = defaultExternalScopeProvider; - m_textScrubbers = textScrubbers; - m_options = options; - m_replayer = replayer; - } - - public ILogger CreateLogger(string categoryName) => - new OmexLogger(m_logsEventSender, m_externalScopeProvider ?? m_defaultExternalScopeProvider, m_textScrubbers, categoryName, m_options.Value, m_replayer); - - public void Dispose() { } - - public void SetScopeProvider(IExternalScopeProvider scopeProvider) => m_externalScopeProvider = scopeProvider; - - private IExternalScopeProvider? m_externalScopeProvider; - - private readonly ILogEventSender m_logsEventSender; - private readonly IExternalScopeProvider m_defaultExternalScopeProvider; - private readonly IEnumerable m_textScrubbers; - private readonly IOptions m_options; - private readonly ILogEventReplayer? m_replayer; - } -} diff --git a/src/Logging/ServiceCollectionExtensions.cs b/src/Logging/ServiceCollectionExtensions.cs index c1c1df8b..765dbca3 100644 --- a/src/Logging/ServiceCollectionExtensions.cs +++ b/src/Logging/ServiceCollectionExtensions.cs @@ -1,15 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Configuration; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Abstractions.Activities.Processing; -using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; -using Microsoft.Omex.Extensions.Logging.Replayable; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; namespace Microsoft.Omex.Extensions.Logging { @@ -27,45 +21,5 @@ public static IServiceCollection AddOmexServiceContext(this ISe serviceCollection.TryAddTransient(); return serviceCollection; } - - /// - /// Adds Omex event logger to the factory - /// - /// The extension method argument - [Obsolete("OmexLogger and OmexLogEventSource are obsolete and pending for removal by 1 July 2024. Please consider using a different Logger.", DiagnosticId = "OMEX188")] - public static ILoggingBuilder AddOmexLogging(this ILoggingBuilder builder) - { - builder.AddConfiguration(); - builder.Services.AddOmexLogging(); - return builder; - } - - /// - /// Adds Omex event logger to the factory - /// - /// The extension method argument - /// The so that additional calls can be chained - [Obsolete("OmexLogger and OmexLogEventSource are obsolete and pending for removal by 1 July 2024. Please consider using a different Logger.", DiagnosticId = "OMEX188")] - public static IServiceCollection AddOmexLogging(this IServiceCollection serviceCollection) - { - serviceCollection.AddLogging(builder => - builder.AddConfiguration()); - - serviceCollection.TryAddTransient(); - serviceCollection.TryAddTransient(); - serviceCollection.TryAddTransient(); - - serviceCollection.TryAddSingleton(_ => OmexLogEventSource.Instance); - serviceCollection.TryAddSingleton(); - serviceCollection.TryAddSingleton(); - - serviceCollection.TryAddEnumerable(ServiceDescriptor.Transient()); - serviceCollection.TryAddEnumerable(ServiceDescriptor.Singleton()); - - serviceCollection.TryAddEnumerable(ServiceDescriptor.Singleton - , OmexLoggerOptionsSetup>()); - - return serviceCollection; - } } } diff --git a/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs b/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs index 761749dd..b515a352 100644 --- a/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs +++ b/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs @@ -7,10 +7,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Omex.Extensions.Abstractions; using Microsoft.Omex.Extensions.Abstractions.Accessors; using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; -using Microsoft.Omex.Extensions.Logging; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; using Microsoft.ServiceFabric.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -29,10 +30,9 @@ public void AddOmexServiceFabricDependencies_TypesRegistered(Type typeToResolve, { void CheckTypeRegistration() where TContext : ServiceContext { -#pragma warning disable CS0618 // Type or member is obsolete object? obj = new ServiceCollection() + .AddLogging(builder => builder.AddProvider(NullLoggerProvider.Instance)) .AddOmexServiceFabricDependencies() -#pragma warning restore CS0618 // Type or member is obsolete .AddSingleton(new Mock().Object) .BuildServiceProvider() .GetService(typeToResolve); @@ -53,7 +53,6 @@ void CheckTypeRegistration() where TContext : ServiceContext [DataRow(typeof(IServiceContext), typeof(OmexServiceFabricContext))] [DataRow(typeof(IExecutionContext), typeof(ServiceFabricExecutionContext))] [DataRow(typeof(ActivitySource), null)] - [DataRow(typeof(ILogger), null)] [DataRow(typeof(IHostedService), typeof(OmexHostedService))] [DataRow(typeof(IOmexServiceRegistrator), typeof(OmexStatelessServiceRegistrator))] [DataRow(typeof(IAccessor), typeof(Accessor))] diff --git a/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs b/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs index 18ec0a15..b97b2280 100644 --- a/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs +++ b/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs @@ -3,7 +3,7 @@ using System.Fabric; using Microsoft.Omex.Extensions.Abstractions.Accessors; -using Microsoft.Omex.Extensions.Logging; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; using Microsoft.VisualStudio.TestTools.UnitTesting; using ServiceFabric.Mocks; diff --git a/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs b/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs index a9175e1c..095d77ec 100644 --- a/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs +++ b/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting.Internal; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Omex.Extensions.Hosting.Certificates; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -19,10 +20,10 @@ public class HostBuilderExtensionsTests [DataTestMethod] [DataRow(typeof(ILogger))] [DataRow(typeof(ActivitySource))] - [Obsolete("Obsolete")] public void AddOmexServices_TypesRegistered(Type type) { object? collectionObj = new ServiceCollection() + .AddLogging(builder => builder.AddProvider(NullLoggerProvider.Instance)) .AddSingleton(new ConfigurationBuilder().Build()) // Added IConfiguration because one of the dependency depends on IOptions which in turn depends on IConfiguration .AddSingleton(new HostingEnvironment()) .AddOmexServices() diff --git a/tests/Logging.UnitTests/EmptyServiceContextTests.cs b/tests/Logging.UnitTests/EmptyServiceContextTests.cs index 139e332c..2bedf3a1 100644 --- a/tests/Logging.UnitTests/EmptyServiceContextTests.cs +++ b/tests/Logging.UnitTests/EmptyServiceContextTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Omex.Extensions.Logging.UnitTests diff --git a/tests/Logging.UnitTests/OmexLogEventSenderTests.cs b/tests/Logging.UnitTests/OmexLogEventSenderTests.cs deleted file mode 100644 index 0651c706..00000000 --- a/tests/Logging.UnitTests/OmexLogEventSenderTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics; -using System.Diagnostics.Tracing; -using System.Linq; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Abstractions.EventSources; -using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; -using Microsoft.Omex.Extensions.Testing.Helpers; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - [Obsolete("InitializationLogger using OmexLogger is obsolete and is pending for removal by 1 July 2024.", DiagnosticId = "OMEX188")] - [TestClass] - public class OmexLogEventSenderTests - { - [DataTestMethod] - [DataRow(EventLevel.Error, LogLevel.Critical, EventSourcesEventIds.LogError)] - [DataRow(EventLevel.Error, LogLevel.Error, EventSourcesEventIds.LogError)] - [DataRow(EventLevel.Warning, LogLevel.Warning, EventSourcesEventIds.LogWarning)] - [DataRow(EventLevel.Informational, LogLevel.Information, EventSourcesEventIds.LogInfo)] - [DataRow(EventLevel.Verbose, LogLevel.Debug, EventSourcesEventIds.LogVerbose)] - [DataRow(EventLevel.Verbose, LogLevel.Trace, EventSourcesEventIds.LogSpam)] - public void LogMessage_CreatesProperEvents(EventLevel eventLevel, LogLevel logLevel, EventSourcesEventIds eventId) - { - using TestEventListener listener = new(); - listener.EnableEvents(OmexLogEventSource.Instance, eventLevel); - listener.EnableEvents(ServiceInitializationEventSource.Instance, EventLevel.Informational); - - const string message = "Test message"; - const string category = "Test category"; - const int tagId = 0xFFF9; - using Activity activity = new("Test activity"); - activity.Start().Stop(); // Start and stop the activity to get the correlation ID. - - Mock> mockOptions = new(); - mockOptions.Setup(m => m.CurrentValue).Returns(new OmexLoggingOptions()); - - OmexLogEventSender logsSender = new( - OmexLogEventSource.Instance, - new Mock().Object, - new EmptyServiceContext(), - mockOptions.Object); - - logsSender.LogMessage(activity, category, logLevel, tagId, 0, message, new Exception("Not expected to be part of the event")); - - EventWrittenEventArgs eventInfo = listener.EventsInformation.Single(e => e.EventId == (int)eventId); - eventInfo.AssertPayload("message", message); - eventInfo.AssertPayload("category", category); - eventInfo.AssertPayload("activityId", activity.Id); - eventInfo.AssertPayload("tagId", tagId.ToString("x4")); - - InitializationLogger.LogInitializationSucceed(category, message); - eventInfo = listener.EventsInformation.Single(e => e.EventId == (int)EventSourcesEventIds.GenericHostBuildSucceeded); - eventInfo.AssertPayload("message", "Initialization successful for Test category, Test message"); - - const string newMessage = "New message"; - InitializationLogger.LogInitializationFail(category, new Exception("Not expected to be part of the event"), newMessage); - eventInfo = listener.EventsInformation.Single(e => e.EventId == (int)EventSourcesEventIds.GenericHostFailed); - eventInfo.AssertPayload("message", newMessage); - } - } -} diff --git a/tests/Logging.UnitTests/OmexLoggerProviderTests.cs b/tests/Logging.UnitTests/OmexLoggerProviderTests.cs deleted file mode 100644 index d661586f..00000000 --- a/tests/Logging.UnitTests/OmexLoggerProviderTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Logging.Scrubbing; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - [TestClass] - [Obsolete("OmexLogger is Obsolete and pending for removal on 1 July 2024.", DiagnosticId = "OMEX188")] - public class OmexLoggerProviderTests - { - [TestMethod] - public void CreateLogger_PropagatesCategory() - { - const string testCategory = "SomeCategoryName"; - const string testMessage = "TestMessage"; - Mock mockEventSource = new(); - IExternalScopeProvider mockExternalScopeProvider = new Mock().Object; - - Mock> mockOmexLoggingOption = new(); - OmexLoggingOptions omexLoggingOptions = new OmexLoggingOptions() { OmexLoggerEnabled = true }; - mockOmexLoggingOption.Setup(m => m.Value).Returns(omexLoggingOptions); - - ILoggerProvider loggerProvider = new OmexLoggerProvider(mockEventSource.Object, mockExternalScopeProvider, Array.Empty(), mockOmexLoggingOption.Object); - ILogger logger = loggerProvider.CreateLogger(testCategory); - - Assert.IsInstanceOfType(logger, typeof(OmexLogger)); - - mockEventSource.Setup(e => e.IsEnabled(It.IsAny())).Returns(true); - - logger.LogError(testMessage); - - mockEventSource.Verify(e => e.LogMessage(It.IsAny(), testCategory, LogLevel.Error, It.IsAny(), It.IsAny(), testMessage, It.IsAny()), Times.Once); - } - - [TestMethod] - [DataTestMethod] - [DataRow(true)] - [DataRow(false)] - public void CreateLogger_Control_OmexLoggerEnabledBoolean_LogProducedAccordingly(bool omexLoggerEnabled) - { - const string testCategory = "SomeCategoryName"; - const string testMessage = "TestMessage"; - Mock mockEventSource = new(); - IExternalScopeProvider mockExternalScopeProvider = new Mock().Object; - - Mock> mockOmexLoggingOption = new(); - OmexLoggingOptions omexLoggingOptions = new OmexLoggingOptions() { OmexLoggerEnabled = omexLoggerEnabled }; - mockOmexLoggingOption.Setup(m => m.Value).Returns(omexLoggingOptions); - - ILoggerProvider loggerProvider = new OmexLoggerProvider(mockEventSource.Object, mockExternalScopeProvider, Array.Empty(), mockOmexLoggingOption.Object); - ILogger logger = loggerProvider.CreateLogger(testCategory); - - Assert.IsInstanceOfType(logger, typeof(OmexLogger)); - - mockEventSource.Setup(e => e.IsEnabled(It.IsAny())).Returns(true); - - logger.LogError(testMessage); - - mockEventSource.Verify(e => e.LogMessage(It.IsAny(), testCategory, LogLevel.Error, It.IsAny(), It.IsAny(), testMessage, It.IsAny()), omexLoggerEnabled ? Times.Once : Times.Never); - } - } -} diff --git a/tests/Logging.UnitTests/Scrubbing/ServiceCollectionExtensionsTests.cs b/tests/Logging.UnitTests/Scrubbing/ServiceCollectionExtensionsTests.cs index 9b67a16d..bcd17654 100644 --- a/tests/Logging.UnitTests/Scrubbing/ServiceCollectionExtensionsTests.cs +++ b/tests/Logging.UnitTests/Scrubbing/ServiceCollectionExtensionsTests.cs @@ -133,7 +133,7 @@ public void AddRegexLogScrubbingRule_WithMatchEvaluator_Scrubs(string input, str public void AddRegexLogScrubbingRule_Scrubs(string input, string expected) { ILoggingBuilder builder2 = new MockLoggingBuilder() - .AddRegexLogScrubbingRule(Regex,"REDACTED&"); + .AddRegexLogScrubbingRule(Regex, "REDACTED&"); ILogScrubbingRule[] logScrubbingRules = GetTypeRegistrations(builder2.Services); @@ -142,10 +142,7 @@ public void AddRegexLogScrubbingRule_Scrubs(string input, string expected) private static ILogScrubbingRule[] GetTypeRegistrations(IServiceCollection collection) { -#pragma warning disable OMEX188 // AddOmexLogging uses OmexLogger and OmexLogEventSource which are obsolete and pending for removal by 1 July 2024. DiagnosticId = "OMEX188" IEnumerable objects = collection - .AddOmexLogging() -#pragma warning restore OMEX188 // AddOmexLogging uses OmexLogger and OmexLogEventSource which are obsolete and pending for removal by 1 July 2024. DiagnosticId = "OMEX188" .BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, diff --git a/tests/Logging.UnitTests/ServiceCollectionTests.cs b/tests/Logging.UnitTests/ServiceCollectionTests.cs index 9eca29b1..8c57c252 100644 --- a/tests/Logging.UnitTests/ServiceCollectionTests.cs +++ b/tests/Logging.UnitTests/ServiceCollectionTests.cs @@ -4,6 +4,7 @@ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Omex.Extensions.Abstractions.ServiceContext; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Omex.Extensions.Logging.UnitTests @@ -26,10 +27,6 @@ public void AddOmexServiceContext_OverridesContextType() IServiceCollection collection = new ServiceCollection() .AddOmexServiceContext(); -#pragma warning disable OMEX188 // AddOmexLogging method is obsolete. DiagnosticId = "OMEX188" - collection.AddOmexLogging(); -#pragma warning restore OMEX188 // AddOmexLogging method is obsolete. DiagnosticId = "OMEX188" - IServiceContext context = ValidateTypeRegistration(collection); Assert.IsInstanceOfType(context, @@ -37,29 +34,10 @@ public void AddOmexServiceContext_OverridesContextType() "Call of AddOmexServiceContext before AddOmexLogging should override IServiceCollection implementation"); } - [TestMethod] - [Obsolete("AddOmexLogging method is obsolete.", DiagnosticId = "OMEX188")] - public void AddOmexLoggerOnServiceCollection_RegistersLogger() - { - IServiceCollection collection = new ServiceCollection().AddOmexLogging(); - ValidateTypeRegistration>(collection); - } - - [TestMethod] - [Obsolete("AddOmexLogging method is obsolete.", DiagnosticId = "OMEX188")] - public void AddOmexLoggerOnLogBuilder_RegistersLogger() - { - ILoggingBuilder builder = new MockLoggingBuilder().AddOmexLogging(); - ValidateTypeRegistration>(builder.Services); - } - private T ValidateTypeRegistration(IServiceCollection collection) where T : class { -#pragma warning disable OMEX188 // AddOmexLogging method is obsolete. DiagnosticId = "OMEX188" T obj = collection - .AddOmexLogging() -#pragma warning restore OMEX188 // AddOmexLogging method is obsolete. DiagnosticId = "OMEX188" .BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true,