diff --git a/src/Abstractions/EventSources/EventSourcesEventIds.cs b/src/Abstractions/EventSources/EventSourcesEventIds.cs index fc95d45b..090265e8 100644 --- a/src/Abstractions/EventSources/EventSourcesEventIds.cs +++ b/src/Abstractions/EventSources/EventSourcesEventIds.cs @@ -11,31 +11,6 @@ namespace Microsoft.Omex.Extensions.Abstractions.EventSources /// public enum EventSourcesEventIds { - /// - /// Event Id for logging general info message - /// - LogInfo = 1, - - /// - /// Event Id for logging error message - /// - LogError = 2, - - /// - /// Event Id for logging warning message - /// - LogWarning = 3, - - /// - /// Event Id for logging verbose message - /// - LogVerbose = 4, - - /// - /// Event Id for logging spam message - /// - LogSpam = 5, - /// /// Event Id for logging activities /// @@ -45,40 +20,5 @@ public enum EventSourcesEventIds /// Event Id for logging test activities /// LogActivityTestContext = 7, - - /// - /// Event Id for service type registered - /// - ServiceTypeRegistered = 11, - - /// - /// Event Id for service host initialization failed - /// - ServiceHostInitializationFailed = 12, - - /// - /// Event Id for actor type registered - /// - ActorTypeRegistered = 13, - - /// - /// Event Id for actor host initialization failed - /// - ActorHostInitializationFailed = 14, - - /// - /// Event Id for logging Analytics information - /// - LogAnalytics = 15, - - /// - /// Event Id for generic host build succeded - /// - GenericHostBuildSucceeded = 16, - - /// - /// Event Id for generic host build failed - /// - GenericHostFailed = 17 } } diff --git a/src/Hosting.Services/HostBuilderExtensions.cs b/src/Hosting.Services/HostBuilderExtensions.cs index 6fb4ede5..31a484de 100644 --- a/src/Hosting.Services/HostBuilderExtensions.cs +++ b/src/Hosting.Services/HostBuilderExtensions.cs @@ -7,11 +7,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using Microsoft.Omex.Extensions.Abstractions; using Microsoft.Omex.Extensions.Abstractions.Accessors; using Microsoft.Omex.Extensions.Abstractions.ExecutionContext; -using Microsoft.Omex.Extensions.Logging; using Microsoft.ServiceFabric.Data; namespace Microsoft.Omex.Extensions.Hosting.Services @@ -58,8 +56,6 @@ public static IServiceCollection AddOmexServiceFabricDependencies(this } collection.TryAddAccessor(); - - collection.TryAddSingleton(); collection.TryAddSingleton(); return collection.AddOmexServices(); @@ -75,53 +71,35 @@ private static IHost BuildServiceFabricService( { string serviceNameForLogging = serviceName; - try + if (string.IsNullOrWhiteSpace(serviceName)) { - if (string.IsNullOrWhiteSpace(serviceName)) - { - // use executing assembly name for logging since application name not available - serviceNameForLogging = Assembly.GetExecutingAssembly().GetName().FullName; - throw new ArgumentException("Service type name is null of whitespace", nameof(serviceName)); - } - - builderAction(new ServiceFabricHostBuilder(builder)); - - IHost host = builder - .ConfigureServices((context, collection) => - { - collection - .Configure(options => - { - options.ServiceTypeName = serviceName; - }) - .AddOmexServiceFabricDependencies() - .AddSingleton() - .AddHostedService(); - }) - .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" - .Build(); + // use executing assembly name for logging since application name not available + serviceNameForLogging = Assembly.GetExecutingAssembly().GetName().FullName; + throw new ArgumentException("Service type name is null of whitespace", nameof(serviceName)); + } -#pragma warning disable OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" - InitializationLogger.LogInitializationSucceed(serviceNameForLogging); -#pragma warning restore OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" + builderAction(new ServiceFabricHostBuilder(builder)); - return host; - } - catch (Exception e) - { -#pragma warning disable OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" - InitializationLogger.LogInitializationFail(serviceNameForLogging, e); -#pragma warning restore OMEX188 // InitializationLogger using OmexLogger is obsolete. DiagnosticId = "OMEX188" + IHost host = builder + .ConfigureServices((context, collection) => + { + collection + .Configure(options => + { + options.ServiceTypeName = serviceName; + }) + .AddOmexServiceFabricDependencies() + .AddSingleton() + .AddHostedService(); + }) + .UseDefaultServiceProvider(options => + { + options.ValidateOnBuild = true; + options.ValidateScopes = true; + }) + .Build(); - throw; - } + return host; } internal static IServiceCollection TryAddAccessor(this IServiceCollection collection) diff --git a/src/Hosting.Services/Internal/OmexServiceFabricContext.cs b/src/Hosting.Services/Internal/OmexServiceFabricContext.cs deleted file mode 100644 index c8592cb7..00000000 --- a/src/Hosting.Services/Internal/OmexServiceFabricContext.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Fabric; -using Microsoft.Omex.Extensions.Abstractions; -using Microsoft.Omex.Extensions.Logging; - -namespace Microsoft.Omex.Extensions.Hosting.Services -{ - /// - /// Create wrapper from Service Fabric context to provide log information - /// - internal sealed class OmexServiceFabricContext : IServiceContext - { - public OmexServiceFabricContext(IAccessor accessor) - { - PartitionId = Guid.Empty; - ReplicaOrInstanceId = 0L; - accessor.OnFirstSet(UpdateState); - } - - /// - public Guid PartitionId { get; private set; } - - /// - public long ReplicaOrInstanceId { get; private set; } - - private void UpdateState(ServiceContext context) - { - PartitionId = context.PartitionId; - ReplicaOrInstanceId = context.ReplicaOrInstanceId; - } - } -} diff --git a/src/Hosting/Certificates/CertificateReader.cs b/src/Hosting/Certificates/CertificateReader.cs index 32f6fb17..93525f29 100644 --- a/src/Hosting/Certificates/CertificateReader.cs +++ b/src/Hosting/Certificates/CertificateReader.cs @@ -14,17 +14,11 @@ namespace Microsoft.Omex.Extensions.Hosting.Certificates internal class CertificateReader : ICertificateReader { private readonly ICertificateStore m_certificateStore; - private readonly ILogger m_logger; private readonly ConcurrentDictionary m_certificatesCache; - public CertificateReader(ICertificateStore certificateStore, ILogger logger) : this(certificateStore, logger as ILogger) - { - } - - internal CertificateReader(ICertificateStore certificateStore, ILogger logger) + public CertificateReader(ICertificateStore certificateStore) { m_certificateStore = certificateStore; - m_logger = logger; m_certificatesCache = new ConcurrentDictionary(); } @@ -42,15 +36,6 @@ internal CertificateReader(ICertificateStore certificateStore, ILogger logger) } } - if (matchingCertificate == null) - { - m_logger.LogError(Tag.Create(), "Could not find certificate with {0} thumbprint.", thumbprint); - } - else - { - m_logger.LogDebug(Tag.Create(), "Found certificate with {0} thumbprint.", thumbprint); - } - return matchingCertificate; } @@ -58,24 +43,13 @@ public IEnumerable GetCertificatesByCommonName(string commonNa { Validation.ThrowIfNullOrWhiteSpace(commonName, nameof(commonName)); - bool certFound = false; foreach (CertificateInformation info in LoadCertificates(storeName, refreshCache)) { if (string.Equals(info.CommonName, commonName, StringComparison.Ordinal)) { - certFound = true; yield return info.Certificate; } } - - if (certFound) - { - m_logger.LogDebug(Tag.Create(), "Found at least one certificate with {0} as common name.", commonName); - } - else - { - m_logger.LogError(Tag.Create(), "Could not find certificate with {0} as common name.", commonName); - } } public X509Certificate2? GetCertificateByCommonName(string commonName, bool refreshCache, StoreName storeName) => @@ -86,12 +60,7 @@ private CertificateInformation[] LoadCertificates(StoreName storeName, bool refr CertificateInformation[]? certificates; if (refreshCache || !m_certificatesCache.TryGetValue(storeName, out certificates)) { - m_logger.LogInformation(Tag.Create(), "Updating certificates cache for store '{0}'.", storeName); - certificates = m_certificateStore.GetAllCertificates(storeName, StoreLocation.LocalMachine).ToArray(); - - m_logger.LogInformation(Tag.Create(), "Inserting '{0}' certificates to certificates cache for store '{1}'.", certificates.Length, storeName); - m_certificatesCache[storeName] = certificates; } diff --git a/src/Hosting/Certificates/InitializationCertificateReader.cs b/src/Hosting/Certificates/InitializationCertificateReader.cs index ca2ac21c..e97b149a 100644 --- a/src/Hosting/Certificates/InitializationCertificateReader.cs +++ b/src/Hosting/Certificates/InitializationCertificateReader.cs @@ -17,8 +17,6 @@ public static class InitializationCertificateReader /// /// Instance of CertificateReader /// -#pragma warning disable OMEX188 // InitializationLogger using OmexLogger is obsolete and is pending for removal by 1 July 2024. - public static ICertificateReader Instance { get; } = new CertificateReader(new CertificateStore(), InitializationLogger.Instance); -#pragma warning restore OMEX188 // InitializationLogger using OmexLogger is obsolete and is pending for removal by 1 July 2024. + public static ICertificateReader Instance { get; } = new CertificateReader(new CertificateStore()); } } diff --git a/src/Hosting/ServiceCollectionExtensions.cs b/src/Hosting/ServiceCollectionExtensions.cs index 5e23f8e0..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 { @@ -26,11 +24,7 @@ public static IHostBuilder AddOmexServices(this IHostBuilder builder) => /// Add Omex Logging and ActivitySource dependencies /// 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/ILogEventSender.cs b/src/Logging/ILogEventSender.cs deleted file mode 100644 index a8d9bf66..00000000 --- a/src/Logging/ILogEventSender.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics; -using Microsoft.Extensions.Logging; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Event source to send log messages - /// - public interface ILogEventSender - { - /// - /// Is logging enabled for specified log level - /// - bool IsEnabled(LogLevel level); - - /// - /// Log message - /// - /// Activity for this log event - /// Log category - /// Log level - /// event Id - /// Id of the thread - /// Log message - /// The exception, if any, associated with the log. - void LogMessage(Activity? activity, string category, LogLevel level, EventId eventId, int threadId, string message, Exception? exception); - } -} diff --git a/src/Logging/IServiceContext.cs b/src/Logging/IServiceContext.cs deleted file mode 100644 index 2a1d9c4a..00000000 --- a/src/Logging/IServiceContext.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Interface with service context information - /// - public interface IServiceContext - { - /// - /// Partition Id - /// - Guid PartitionId { get; } - - /// - /// Replica Id or Instance Id - /// - long ReplicaOrInstanceId { get; } - } -} diff --git a/src/Logging/InitializationLogger.cs b/src/Logging/InitializationLogger.cs deleted file mode 100644 index 44d0b978..00000000 --- a/src/Logging/InitializationLogger.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using Microsoft.Extensions.Logging; -using Microsoft.Omex.Extensions.Abstractions; - -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; - } - - /// - /// Log on successful building - /// - /// Service name for logging - /// Message to log - public static void LogInitializationSucceed(string serviceNameForLogging, string message = "") - { - string logMessage = $"Initialization successful for {serviceNameForLogging}, {message}"; -#if NET5_0_OR_GREATER - ServiceInitializationEventSource.Instance.LogHostBuildSucceeded(Environment.ProcessId, serviceNameForLogging, logMessage); -#else - using Process process = Process.GetCurrentProcess(); - ServiceInitializationEventSource.Instance.LogHostBuildSucceeded(process.Id, serviceNameForLogging, logMessage); -#endif - Instance.LogInformation(Tag.Create(), logMessage); - } - - /// - /// Log on build failure - /// - /// Service name for logging - /// Exception to log - /// Message to log - 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/EmptyServiceContext.cs b/src/Logging/Internal/EventSource/EmptyServiceContext.cs deleted file mode 100644 index f0b6f0d4..00000000 --- a/src/Logging/Internal/EventSource/EmptyServiceContext.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// IServiceContext without any information - /// - internal class EmptyServiceContext : IServiceContext - { - public Guid PartitionId => Guid.Empty; - - public long ReplicaOrInstanceId => 0; - } -} 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 deleted file mode 100644 index 1bb7f6da..00000000 --- a/src/Logging/Internal/EventSource/ServiceInitializationEventSource.cs +++ /dev/null @@ -1,90 +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 -{ - /// - /// 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 - { - /// - /// Instance of service fabric event source - /// - public static ServiceInitializationEventSource Instance { get; } = new ServiceInitializationEventSource(); - - /// - /// Logs a generic host build success - /// - /// Host process id - /// Service type - /// Optional message - [NonEvent] - public void LogHostBuildSucceeded(int hostProcessId, string serviceType, string message = "") - { - if (!IsEnabled()) - { - return; - } - - string logMessage = string.IsNullOrWhiteSpace(message) ? - FormattableString.Invariant($"Service host process {hostProcessId} registered service type {serviceType}") : - message; - LogHostBuildSucceededInternal( - hostProcessId, - serviceType, - logMessage); - } - - /// - /// Logs a generic host failure - /// - /// Exception - /// Service type - /// Optional message - [NonEvent] - public void LogHostFailed(string exception, string serviceType, string message = "") - { - if (!IsEnabled()) - { - return; - } - string logMessage = string.IsNullOrWhiteSpace(message) ? - FormattableString.Invariant($"Service host initialization failed for {serviceType} with exception {exception}") : - message; - - LogHostFailedInternal( - exception, - serviceType, - logMessage); - } - - private ServiceInitializationEventSource() { } - - /// - /// Log host build succeeded - /// - /// Host process id - /// The service type - /// The message to be logged - [Event((int)EventSourcesEventIds.GenericHostBuildSucceeded, Level = EventLevel.Informational, Message = "{2}", Version = 1)] - private void LogHostBuildSucceededInternal(int hostProcessId, string serviceType, string message) => - WriteEvent((int)EventSourcesEventIds.GenericHostBuildSucceeded, hostProcessId, serviceType, message); - - /// - /// Log host build failed - /// - /// Exception to be logged - /// The service type - /// The message to be logged - [Event((int)EventSourcesEventIds.GenericHostFailed, Level = EventLevel.Error, Message = "{1}", Version = 1)] - private void LogHostFailedInternal(string exception, string serviceType, string message) => - WriteEvent((int)EventSourcesEventIds.GenericHostFailed, exception, serviceType, message); - } -} diff --git a/src/Logging/Internal/OmexLogger.cs b/src/Logging/Internal/OmexLogger.cs deleted file mode 100644 index c07d5307..00000000 --- a/src/Logging/Internal/OmexLogger.cs +++ /dev/null @@ -1,75 +0,0 @@ -// 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.Threading; -using Microsoft.Extensions.Logging; -using Microsoft.Omex.Extensions.Logging.Replayable; -using Microsoft.Omex.Extensions.Logging.Scrubbing; - -namespace Microsoft.Omex.Extensions.Logging -{ - internal class OmexLogger : ILogger - { - public OmexLogger( - ILogEventSender logsEventSource, - IExternalScopeProvider externalScopeProvider, - IEnumerable textScrubbers, - string categoryName, - OmexLoggingOptions omexLoggingOptions, - ILogEventReplayer? replayer = null) - { - m_logsEventSender = logsEventSource; - m_externalScopeProvider = externalScopeProvider; - m_textScrubbers = textScrubbers.ToArray(); // Convert to an array for improved iteration performance on each call. - m_categoryName = categoryName; - m_omexLoggingOptions = omexLoggingOptions; - m_replayer = replayer; - } - - public IDisposable? BeginScope(TState state) where TState : notnull => m_externalScopeProvider.Push(state); - - public bool IsEnabled(LogLevel logLevel) => m_omexLoggingOptions.OmexLoggerEnabled && m_logsEventSender.IsEnabled(logLevel); - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - { - if (!IsEnabled(logLevel)) - { - return; - } - - string message = formatter(state, exception); - if (exception != null) - { - message = string.Concat(message, Environment.NewLine, exception); // We need to concatenate with exception since the default formatter ignores it https://github.com/aspnet/Logging/issues/442 - } - - foreach (ILogScrubbingRule textScrubber in m_textScrubbers) - { - message = textScrubber.Scrub(message); - } - - int threadId = Thread.CurrentThread.ManagedThreadId; - Activity? activity = Activity.Current; - - m_logsEventSender.LogMessage(activity, m_categoryName, logLevel, eventId, threadId, message, exception); - - if (activity != null - && m_replayer != null - && m_replayer.IsReplayableMessage(logLevel)) - { - m_replayer.AddReplayLog(activity, new LogMessageInformation(m_categoryName, eventId, threadId, message, exception)); - } - } - - private readonly IExternalScopeProvider m_externalScopeProvider; - private readonly ILogEventSender m_logsEventSender; - private readonly ILogScrubbingRule[] m_textScrubbers; - private readonly string m_categoryName; - private readonly OmexLoggingOptions m_omexLoggingOptions; - private readonly ILogEventReplayer? m_replayer; - } -} 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/Internal/Replayable/ILogEventReplayer.cs b/src/Logging/Internal/Replayable/ILogEventReplayer.cs deleted file mode 100644 index 2f48b0f2..00000000 --- a/src/Logging/Internal/Replayable/ILogEventReplayer.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System.Diagnostics; -using Microsoft.Extensions.Logging; - -namespace Microsoft.Omex.Extensions.Logging.Replayable -{ - /// - /// Replays activity logs - /// - internal interface ILogEventReplayer - { - void ReplayLogs(Activity activity); - - bool IsReplayableMessage(LogLevel logLevel); - - void AddReplayLog(Activity activity, LogMessageInformation logMessage); - } -} diff --git a/src/Logging/Internal/Replayable/LogMessageInformation.cs b/src/Logging/Internal/Replayable/LogMessageInformation.cs deleted file mode 100644 index a3eb508d..00000000 --- a/src/Logging/Internal/Replayable/LogMessageInformation.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using Microsoft.Extensions.Logging; - -namespace Microsoft.Omex.Extensions.Logging.Replayable -{ - internal readonly struct LogMessageInformation - { - public string Category { get; } - public EventId EventId { get; } - public int ThreadId { get; } - public string Message { get; } - public Exception? Exception { get; } - - public LogMessageInformation(string category, EventId eventId, int threadId, string message, Exception? exception) - { - Category = category; - EventId = eventId; - ThreadId = threadId; - Message = message; - Exception = exception; - } - } -} diff --git a/src/Logging/Internal/Replayable/OmexLogEventReplayer.cs b/src/Logging/Internal/Replayable/OmexLogEventReplayer.cs deleted file mode 100644 index b5593301..00000000 --- a/src/Logging/Internal/Replayable/OmexLogEventReplayer.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System.Diagnostics; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Logging.Internal.Replayable; -using Microsoft.Omex.Extensions.Logging.Replayable; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Replays Trace and Debug logs with Info level if Activity marked as failed - /// - internal class OmexLogEventReplayer : ILogEventReplayer - { - private readonly ILogEventSender m_sender; - private readonly IOptionsMonitor m_options; - - public OmexLogEventReplayer(ILogEventSender sender, IOptionsMonitor options) - { - m_sender = sender; - m_options = options; - } - - public bool IsReplayableMessage(LogLevel logLevel) => - logLevel switch - { - LogLevel.Trace or LogLevel.Debug => m_options.CurrentValue.ReplayLogsInCaseOfError, - _ => false - }; - - public void AddReplayLog(Activity activity, LogMessageInformation logMessage) => - activity.AddReplayLog(logMessage, m_options.CurrentValue.MaxReplayedEventsPerActivity); - - public void ReplayLogs(Activity activity) - { - // Replay parent activity - if (activity.Parent != null) - { - ReplayLogs(activity.Parent); - } - - foreach (LogMessageInformation log in activity.GetReplayableLogs()) - { - string message = "[Replay] " + log.Message; // add prefix to mark log as replay - m_sender.LogMessage(activity, log.Category, LogLevel.Information, log.EventId, log.ThreadId, message, log.Exception); - } - } - } -} diff --git a/src/Logging/Internal/Replayable/ReplayableActivityExtensions.cs b/src/Logging/Internal/Replayable/ReplayableActivityExtensions.cs deleted file mode 100644 index 9bf34982..00000000 --- a/src/Logging/Internal/Replayable/ReplayableActivityExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.Omex.Extensions.Logging.Replayable; - -namespace Microsoft.Omex.Extensions.Logging.Internal.Replayable -{ - internal static class ReplayebleActivityExtensions - { - private const string ReplayableLogKey = "ReplayableLogKey"; - - private static ConcurrentQueue? GetReplayableLogsInternal(this Activity activity) => - activity.GetCustomProperty(ReplayableLogKey) as ConcurrentQueue; - - public static IEnumerable GetReplayableLogs(this Activity activity) => - activity.GetReplayableLogsInternal() ?? Enumerable.Empty(); - - public static void AddReplayLog(this Activity activity, LogMessageInformation logEvent, uint maxReplayedEventsPerActivity) - { - ConcurrentQueue? queue = activity.GetReplayableLogsInternal(); - if (queue == null) - { - queue = new ConcurrentQueue(); - activity.SetCustomProperty(ReplayableLogKey, queue); - } - - queue.Enqueue(logEvent); - - if (queue.Count > maxReplayedEventsPerActivity) - { - queue.TryDequeue(out _); - } - } - } -} diff --git a/src/Logging/Internal/Replayable/ReplayableActivityStopObserver.cs b/src/Logging/Internal/Replayable/ReplayableActivityStopObserver.cs deleted file mode 100644 index 4665b91c..00000000 --- a/src/Logging/Internal/Replayable/ReplayableActivityStopObserver.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Diagnostics; -using System.Linq; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Abstractions.Activities.Processing; - -namespace Microsoft.Omex.Extensions.Logging.Replayable -{ - internal class ReplayableActivityStopObserver : IActivityStopObserver - { - private readonly ILogEventReplayer m_logReplayer; - private readonly IOptionsMonitor m_options; - - public ReplayableActivityStopObserver(ILogEventReplayer logReplayer, IOptionsMonitor options) - { - m_logReplayer = logReplayer; - m_options = options; - } - - public void OnStop(Activity activity, object? payload) - { - if (ShouldReplayEvents(activity)) - { - m_logReplayer.ReplayLogs(activity); - } - } - - private bool ShouldReplayEvents(Activity activity) - { - if (!m_options.CurrentValue.ReplayLogsInCaseOfError) - { - return false; - } - - string? resultTagValue = activity.Tags.FirstOrDefault(p => string.Equals(p.Key, ActivityTagKeys.Result, StringComparison.Ordinal)).Value; - return string.Equals(ActivityResultStrings.SystemError, resultTagValue, StringComparison.Ordinal); - } - } -} diff --git a/src/Logging/OmexLoggingOptions.cs b/src/Logging/OmexLoggingOptions.cs deleted file mode 100644 index 096b7efd..00000000 --- a/src/Logging/OmexLoggingOptions.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Options for Omex logger - /// - internal class OmexLoggingOptions - { - /// - /// Should logs wrapped by the Activity be stored and replayed at a higher severity, in the event of an error. - /// Setting this to true will impact the performance of logging - /// - public bool ReplayLogsInCaseOfError { get; set; } = false; - - /// - /// Enabling this option will add CorrelationId guid to activity that will increase its size - /// - public bool AddObsoleteCorrelationToActivity { get; set; } = true; - - /// - /// Maximum number of events that activity can store for replay - /// - public uint MaxReplayedEventsPerActivity { get; set; } = 1000; - - /// - /// Enable or disable OmexLogger - /// - public bool OmexLoggerEnabled { get; set; } = false; - } -} diff --git a/src/Logging/ServiceCollectionExtensions.cs b/src/Logging/ServiceCollectionExtensions.cs deleted file mode 100644 index c1c1df8b..00000000 --- a/src/Logging/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,71 +0,0 @@ -// 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; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Extension methods for the class - /// - public static class ServiceCollectionExtensions - { - /// - /// Add IServiceContext to ServiceCollection - /// - public static IServiceCollection AddOmexServiceContext(this IServiceCollection serviceCollection) - where TServiceContext : class, IServiceContext - { - 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/src/Logging/TagsExtensions.cs b/src/Logging/TagsExtensions.cs deleted file mode 100644 index ec537a4e..00000000 --- a/src/Logging/TagsExtensions.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Globalization; -using System.Text; -using Microsoft.Extensions.Logging; - -namespace Microsoft.Omex.Extensions.Logging -{ - /// - /// Extensions for dealing with legacy Tag IDs. - /// - [Obsolete("Added for backward compatability, we are in a process of changing tagging system, please avoid using it if posible", false)] - public static class TagsExtensions - { - /// - /// Get the Tag id as a string, from an . - /// Please avoid using this method if posible, it's added to support old tag scenario and made internal for unit tests - /// - /// The event ID. - /// the tag as string - /// - /// In terms of the conversion from integer tag value to equivalent string reprsentation, the following scheme is used: - /// 1. If the integer tag <= 0x0000FFFF, treat the tag as special tag called numeric only tag. - /// Hence the string representation is direct conversion i.e. tag id 6700 == 6700 - /// 2. Else, if it's an alphanumeric tag, there are 2 different schemes to pack those. viz. 4 letter and 5 letter representations. - /// 2.1 four letter tags are converted by transforming each byte into it's equivalent ASCII. e.g. 0x61626364 => abcd - /// 2.2 five letter tags are converted by transforming lower 30 bits of the integer value into the symbol space a-z,0-9. - /// The conversion is done by treating each group of 6 bits as an index into the symbol space a,b,c,d, ... z, 0, 1, 2, ....9 - /// eg. 0x000101D0 = 00 000000 000000 010000 000111 010000 2 = aaqhq - /// - public static string ToTagId(this EventId eventId) - { - int tagId = eventId.Id; - - if (tagId <= 0xFFFF) - { - // Use straight numeric values - return tagId.ToString("x4", CultureInfo.InvariantCulture); - } - else if (tagId <= 0x3FFFFFFF) - { - // Use the lower 30 bits, grouped into 6 bits each, index into - // valuespace 'a'-'z','0'-'9' (reverse order) - char[] chars = new char[5]; - for (int i = 4; i >= 0; i--) - { - int charVal = tagId & 0x3F; - tagId >>= 6; - if (charVal > 25) - { - if (charVal > 35) - { - chars[i] = '?'; - } - else - { - chars[i] = (char)(charVal + 22); - } - } - else - { - chars[i] = (char)(charVal + 'a'); - } - } - - return new string(chars); - } - else - { - // Each byte represented as ASCII (reverse order) - byte[] bytes = BitConverter.GetBytes(tagId); - char[] characters = Encoding.ASCII.GetChars(bytes); - if (characters.Length > 0) - { - Array.Reverse(characters); - return new string(characters); - } - } - - return "0000"; - } - } -} diff --git a/src/ServiceFabricGuest.Abstractions/ServiceFabricClientFactory.cs b/src/ServiceFabricGuest.Abstractions/ServiceFabricClientFactory.cs index a2ed31ee..94c7bb18 100644 --- a/src/ServiceFabricGuest.Abstractions/ServiceFabricClientFactory.cs +++ b/src/ServiceFabricGuest.Abstractions/ServiceFabricClientFactory.cs @@ -19,8 +19,6 @@ public class ServiceFabricClientFactory /// Creates service fabric client wrapper instance and returns it. /// public static IServiceFabricClientWrapper Create(ServiceFabricRestClientOptions options) => -#pragma warning disable OMEX188 // InitializationCertificateReader using OmexLogger is obsolete. DiagnosticId = "OMEX188" new ServiceFabricClientWrapper(Options.Create(options), InitializationCertificateReader.Instance); -#pragma warning restore OMEX188 // InitializationCertificateReader using OmexLogger is obsolete. DiagnosticId = "OMEX188" } } diff --git a/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs b/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs index 25b608e0..2a106ed4 100644 --- a/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs +++ b/tests/Hosting.Services.UnitTests/HostBuilderExtensionsTests.cs @@ -7,10 +7,10 @@ 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.ServiceFabric.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -21,7 +21,6 @@ namespace Microsoft.Omex.Extensions.Hosting.Services.UnitTests public class HostBuilderExtensionsTests { [DataTestMethod] - [DataRow(typeof(IServiceContext), typeof(OmexServiceFabricContext))] [DataRow(typeof(IExecutionContext), typeof(ServiceFabricExecutionContext))] [DataRow(typeof(ActivitySource), null)] [DataRow(typeof(ILogger), null)] @@ -30,6 +29,7 @@ public void AddOmexServiceFabricDependencies_TypesRegistered(Type typeToResolve, void CheckTypeRegistration() where TContext : ServiceContext { object? obj = new ServiceCollection() + .AddLogging(builder => builder.AddProvider(NullLoggerProvider.Instance)) .AddOmexServiceFabricDependencies() .AddSingleton(new Mock().Object) .BuildServiceProvider() @@ -48,10 +48,8 @@ void CheckTypeRegistration() where TContext : ServiceContext } [DataTestMethod] - [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))] @@ -74,7 +72,6 @@ public void BuildStatelessService_RegisterTypes(Type type, Type? expectedImpleme } [DataTestMethod] - [DataRow(typeof(IServiceContext), typeof(OmexServiceFabricContext))] [DataRow(typeof(IExecutionContext), typeof(ServiceFabricExecutionContext))] [DataRow(typeof(ActivitySource), null)] [DataRow(typeof(ILogger), null)] diff --git a/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs b/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs deleted file mode 100644 index 18ec0a15..00000000 --- a/tests/Hosting.Services.UnitTests/OmexServiceFabricContextTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System.Fabric; -using Microsoft.Omex.Extensions.Abstractions.Accessors; -using Microsoft.Omex.Extensions.Logging; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ServiceFabric.Mocks; - -namespace Microsoft.Omex.Extensions.Hosting.Services.UnitTests -{ - [TestClass] - public class OmexServiceFabricContextTests - { - [TestMethod] - public void SetContext_SetsStatelessContext() => - TestContextSet(MockStatelessServiceContextFactory.Default); - - [TestMethod] - public void SetContext_StatefulContext() => - TestContextSet(MockStatefulServiceContextFactory.Default); - - public void TestContextSet(TContext serviceContext) - where TContext : ServiceContext - { - Accessor accessor = new(); - IAccessorSetter setter = accessor; - IServiceContext context = new OmexServiceFabricContext(accessor); - - Assert.AreEqual(default, context.PartitionId); - Assert.AreEqual(default, context.ReplicaOrInstanceId); - - setter.SetValue(serviceContext); - - Assert.AreEqual(serviceContext.PartitionId, context.PartitionId); - Assert.AreEqual(serviceContext.ReplicaOrInstanceId, context.ReplicaOrInstanceId); - } - } -} diff --git a/tests/Hosting.UnitTests/CertificateReaderTests.cs b/tests/Hosting.UnitTests/CertificateReaderTests.cs index c20ec1d4..36b3647c 100644 --- a/tests/Hosting.UnitTests/CertificateReaderTests.cs +++ b/tests/Hosting.UnitTests/CertificateReaderTests.cs @@ -170,7 +170,7 @@ private static (ICertificateReader reader, Action verify) CreateR .Setup(expression) .Returns(certificates.Select(cert => new CertificateInformation(cert))); - return (new CertificateReader(storeMock.Object, new NullLogger()), + return (new CertificateReader(storeMock.Object), (times, message) => { storeMock.Verify(expression, times, message); diff --git a/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs b/tests/Hosting.UnitTests/HostBuilderExtensionsTests.cs index 005af3e4..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; @@ -22,6 +23,7 @@ public class HostBuilderExtensionsTests 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 deleted file mode 100644 index 139e332c..00000000 --- a/tests/Logging.UnitTests/EmptyServiceContextTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - [TestClass] - public class EmptyServiceContextTests - { - [TestMethod] - public void Constructor_SetsDefaultValues() - { - EmptyServiceContext emptyContext = new(); - Assert.AreEqual(Guid.Empty, emptyContext.PartitionId); - Assert.AreEqual(0, emptyContext.ReplicaOrInstanceId); - } - } -} 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/OmexLoggerUnitTests.cs b/tests/Logging.UnitTests/OmexLoggerUnitTests.cs deleted file mode 100644 index f6f8d089..00000000 --- a/tests/Logging.UnitTests/OmexLoggerUnitTests.cs +++ /dev/null @@ -1,241 +0,0 @@ -// 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.Linq.Expressions; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Logging.Internal.Replayable; -using Microsoft.Omex.Extensions.Logging.Replayable; -using Microsoft.Omex.Extensions.Logging.Scrubbing; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - [TestClass] - public class OmexLoggerUnitTests - { - private static readonly Exception s_expectedPropagatedException = new("Test exception"); - - [TestMethod] - public void LogMessage_PropagatedToEventSource() - { - Mock eventSourceMock = CreateEventSourceMock(); - LogMessage(eventSourceMock, Array.Empty()); - eventSourceMock.Verify(s_logExpression, Times.Once); - } - - [TestMethod] - public void LogMessage_UseIsEnabledFlag() - { - Mock eventSourceMock = CreateEventSourceMock(false); - LogMessage(eventSourceMock, Array.Empty()); - eventSourceMock.Verify(s_logExpression, Times.Never); - } - - [TestMethod] - public void LogMessage_UseIsReplayableMessageFlag() - { - const string suffix = nameof(LogMessage_UseIsReplayableMessageFlag); - Mock eventSourceMock = CreateEventSourceMock(); - - using Activity activity = CreateActivity(suffix); - activity.Start(); - LogMessage(eventSourceMock, Array.Empty(), CreateLogReplayer(10)); - activity.Stop(); - - eventSourceMock.Verify(s_logExpression, Times.Once); - Assert.IsFalse(activity.GetReplayableLogs().Any(), "Log should not be stored for replay"); - } - - [TestMethod] - public void LogMessage_ReplayedMessageAndExceptionSaved() - { - const string suffix = nameof(LogMessage_ReplayedMessageAndExceptionSaved); - EventId eventId = CreateEventId(7, suffix); - string message = GetLogMessage(suffix); - Mock eventSourceMock = CreateEventSourceMock(); - - using Activity activity = CreateActivity(suffix); - activity.Start(); - (ILogger logger, _) = LogMessage(eventSourceMock, Array.Empty(), CreateLogReplayer(10), eventId.Id); - logger.LogDebug(eventId, s_expectedPropagatedException, message); - activity.Stop(); - - eventSourceMock.Verify(s_logExpression, Times.Exactly(2)); - LogMessageInformation info = activity.GetReplayableLogs().Single(); - - Assert.AreEqual(GetLogCategory(suffix), info.Category); - Assert.AreEqual(eventId, info.EventId); - StringAssert.Contains(info.Message, message); - StringAssert.Contains(info.Message, s_expectedPropagatedException.ToString()); - } - - [TestMethod] - public void Log_WithOneScrubber_ScrubbedReplayedAndExceptionSaved() - { - const string suffix = nameof(Log_WithOneScrubber_ScrubbedReplayedAndExceptionSaved); - EventId eventId = CreateEventId(7, suffix); - string message = GetLogMessage(suffix); - Mock eventSourceMock = CreateEventSourceMock(); - - using Activity activity = CreateActivity(suffix); - activity.Start(); - (ILogger logger, _) = LogMessage( - eventSourceMock, - new List { new RegexLogScrubbingRule("Message", "[REDACTED]") }, - CreateLogReplayer(10), - eventId.Id); - logger.LogDebug(eventId, s_expectedPropagatedException, message); - activity.Stop(); - - eventSourceMock.Verify(s_logExpression, Times.Exactly(2)); - LogMessageInformation info = activity.GetReplayableLogs().Single(); - - Assert.AreEqual(GetLogCategory(suffix), info.Category); - Assert.AreEqual(eventId, info.EventId); - StringAssert.Contains(info.Message, FormattableString.Invariant($"[REDACTED]-{suffix}")); - StringAssert.Contains(info.Message, s_expectedPropagatedException.ToString()); - } - - [TestMethod] - public void Log_WithMultipleScrubbers_ScrubbedReplayedAndExceptionSaved() - { - const string suffix = nameof(Log_WithMultipleScrubbers_ScrubbedReplayedAndExceptionSaved); - EventId eventId = CreateEventId(7, suffix); - string message = GetLogMessage(suffix); - Mock eventSourceMock = CreateEventSourceMock(); - - using Activity activity = CreateActivity(suffix); - activity.Start(); - (ILogger logger, _) = LogMessage( - eventSourceMock, - new List - { - new RegexLogScrubbingRule("Mes", "[REDACTED]"), - new RegexLogScrubbingRule("sage", "[REDACTED]") - }, - CreateLogReplayer(10), - eventId.Id); - logger.LogDebug(eventId, s_expectedPropagatedException, message); - activity.Stop(); - - eventSourceMock.Verify(s_logExpression, Times.Exactly(2)); - LogMessageInformation info = activity.GetReplayableLogs().Single(); - - Assert.AreEqual(GetLogCategory(suffix), info.Category); - Assert.AreEqual(eventId, info.EventId); - StringAssert.Contains(info.Message, FormattableString.Invariant($"[REDACTED][REDACTED]-{suffix}")); - StringAssert.Contains(info.Message, s_expectedPropagatedException.ToString()); - } - - [TestMethod] - public void LogMessage_ReplayedMessageSavedUntilTheLimit() - { - const string replayMessage1 = "ReplayMessage1"; - Exception exception1 = new ArgumentException("Error"); - const string replayMessage2 = "ReplayMessage2"; - Exception exception2 = new NullReferenceException("Error"); - - const string suffix = nameof(LogMessage_ReplayedMessageSavedUntilTheLimit); - const int eventId = 7; - Mock eventSourceMock = CreateEventSourceMock(); - - using Activity activity = CreateActivity(suffix); - activity.Start(); - (ILogger logger, _) = LogMessage(eventSourceMock, Array.Empty(), CreateLogReplayer(2), eventId); - logger.LogDebug(new DivideByZeroException(), "LostMessage"); // would be lost due overflow - logger.LogDebug(exception1, replayMessage1); - logger.LogDebug(exception2, replayMessage2); - activity.Stop(); - - eventSourceMock.Verify(s_logExpression, Times.Exactly(4)); - List info = activity.GetReplayableLogs().ToList(); - - Assert.AreEqual(2, info.Count); - StringAssert.Contains(info[0].Message, replayMessage1); - StringAssert.Contains(info[0].Message, exception1.ToString()); - StringAssert.Contains(info[1].Message, replayMessage2); - StringAssert.Contains(info[1].Message, exception2.ToString()); - } - - [TestMethod] - public void BeginScope_ScopeProperlyCreated() - { - (ILogger logger, Mock scopeProviderMock) = LogMessage(CreateEventSourceMock(), Array.Empty()); - - object obj = new(); - using IDisposable resultMock = new Mock().Object; - scopeProviderMock.Setup(p => p.Push(obj)).Returns(resultMock); - - using IDisposable? result = logger.BeginScope(obj); - - Assert.IsNotNull(result, "Failed to begin scope"); - - scopeProviderMock.Verify(p => p.Push(obj), Times.Once); - Assert.AreEqual(resultMock, result); - } - - private static Mock CreateEventSourceMock(bool isEnabled = true) - { - Mock eventSourceMock = new(); - eventSourceMock.Setup(e => e.IsEnabled(It.IsAny())).Returns(isEnabled); - return eventSourceMock; - } - - private static (ILogger, Mock) LogMessage( - IMock eventSourceMock, - IEnumerable textScrubbers, - ILogEventReplayer? logEventReplayer = null, - int eventId = 0, - [CallerMemberName] string suffix = "") - { - Mock scopeProviderMock = new(); - OmexLoggingOptions omexLoggingOptions = new OmexLoggingOptions() { OmexLoggerEnabled = true }; - ILogger logger = new OmexLogger(eventSourceMock.Object, scopeProviderMock.Object, textScrubbers, GetLogCategory(suffix), omexLoggingOptions, logEventReplayer); - - logger.LogError(CreateEventId(eventId, suffix), s_expectedPropagatedException, GetLogMessage(suffix)); - - return (logger, scopeProviderMock); - } - - private static ILogEventReplayer CreateLogReplayer(uint replayLimit) - { - Mock> mock = new(); - mock.Setup(m => m.CurrentValue).Returns(new OmexLoggingOptions - { - ReplayLogsInCaseOfError = true, - MaxReplayedEventsPerActivity = replayLimit - }); - - return new OmexLogEventReplayer(new Mock().Object, mock.Object); - } - - private static string GetLogMessage(string suffix) => - FormattableString.Invariant($"Message-{suffix}"); - - private static string GetLogCategory(string suffix) => - FormattableString.Invariant($"Category-{suffix}"); - - private static EventId CreateEventId(int id, string suffix) => - new(id, FormattableString.Invariant($"EventId-{suffix}")); - - private static Activity CreateActivity(string suffix) => - new(FormattableString.Invariant($"Activity-{suffix}")); - - private static readonly Expression> s_logExpression = e => - e.LogMessage( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()); - } -} diff --git a/tests/Logging.UnitTests/ReplayableActivityStopObserverTests.cs b/tests/Logging.UnitTests/ReplayableActivityStopObserverTests.cs deleted file mode 100644 index b163b5c4..00000000 --- a/tests/Logging.UnitTests/ReplayableActivityStopObserverTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System.Diagnostics; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Omex.Extensions.Abstractions.Activities; -using Microsoft.Omex.Extensions.Logging; -using Microsoft.Omex.Extensions.Logging.Replayable; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; - -namespace Hosting.Services.UnitTests -{ - [TestClass] - public class ReplayableActivityStopObserverTests - { - [DataTestMethod] - [DataRow(ActivityResult.SystemError, true, true)] - [DataRow(ActivityResult.SystemError, false, false)] - [DataRow(ActivityResult.ExpectedError, true, false)] - public void OnStop_UsingReplaySettingsAndResult_CallesLogReplayIfNeeded(ActivityResult result, bool replayLog, bool shouldBeCalled) - { - Activity activity = new Activity(nameof(OnStop_UsingReplaySettingsAndResult_CallesLogReplayIfNeeded)).SetResult(result); - - Mock> mockOptions = new(); - mockOptions.Setup(m => m.CurrentValue).Returns(new OmexLoggingOptions() - { - ReplayLogsInCaseOfError = shouldBeCalled, - }); - - IOptions options = Options.Create(new OmexLoggingOptions { ReplayLogsInCaseOfError = replayLog }); - LogEventReplayerMock replayerMock = new(); - ReplayableActivityStopObserver observer = new(replayerMock, mockOptions.Object); - observer.OnStop(activity, null); - - if (shouldBeCalled) - { - Assert.AreEqual(activity, replayerMock.Activity); - } - else - { - Assert.IsNull(replayerMock.Activity); - } - } - - private class LogEventReplayerMock : ILogEventReplayer - { - public Activity? Activity { get; private set; } - - public void AddReplayLog(Activity activity, LogMessageInformation logMessage) { } - - public bool IsReplayableMessage(LogLevel logLevel) => true; - - public void ReplayLogs(Activity activity) => Activity = activity; - } - } -} 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 deleted file mode 100644 index 9eca29b1..00000000 --- a/tests/Logging.UnitTests/ServiceCollectionTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - [TestClass] - public class ServiceCollectionTests - { - [TestMethod] - public void AddOmexServiceContext_RegisterServiceContext() - { - IServiceCollection collection = new ServiceCollection() - .AddOmexServiceContext(); - - ValidateTypeRegistration(collection); - } - - [TestMethod] - 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, - typeof(MockServiceContext), - "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, - ValidateScopes = true - }).GetRequiredService(); - - Assert.IsNotNull(obj); - - return obj; - } - - private class MockLoggingBuilder : ILoggingBuilder - { - public IServiceCollection Services { get; } = new ServiceCollection(); - } - - private class MockServiceContext : IServiceContext - { - public Guid PartitionId => Guid.Empty; - - public long ReplicaOrInstanceId => 0; - } - } -} diff --git a/tests/Logging.UnitTests/TagExtensionsTests.cs b/tests/Logging.UnitTests/TagExtensionsTests.cs deleted file mode 100644 index 01d1929d..00000000 --- a/tests/Logging.UnitTests/TagExtensionsTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.Omex.Extensions.Logging.UnitTests -{ - public class TagExtensionsTests - { - [DataTestMethod] - [DataRow(0, "0000")] - [DataRow(0xFFFE, "fffe")] - [DataRow(0xFFFF, "ffff")] - // following values provided to validate old behaviour since method ported as is - [DataRow(0x3FFFFFFE, "?????")] - [DataRow(0x3FFFFFFF, "?????")] - [DataRow(0x40000000, "@\0\0\0")] - [DataRow(int.MaxValue, "\u007f???")] - public void TagIdAsString_ConvertsProperly(int tagId, string expected) - { -# pragma warning disable 618 - Assert.AreEqual(expected, new EventId(tagId).ToTagId()); -#pragma warning restore 618 - } - } -}