|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +using Microsoft.Extensions.DependencyInjection.Extensions; |
| 5 | +using OpenTelemetry.Logs; |
| 6 | + |
| 7 | +namespace DedicatedLogging; |
| 8 | + |
| 9 | +public static class DedicatedLoggingServiceCollectionExtensions |
| 10 | +{ |
| 11 | + public static IServiceCollection AddDedicatedLogging( |
| 12 | + this IServiceCollection services, |
| 13 | + IConfiguration configuration, |
| 14 | + Action<OpenTelemetryLoggerOptions> configureOpenTelemetry) |
| 15 | + { |
| 16 | + ArgumentNullException.ThrowIfNull(configureOpenTelemetry); |
| 17 | + |
| 18 | + services.TryAddSingleton(sp => |
| 19 | + { |
| 20 | + var loggerFactory = LoggerFactory.Create(builder => |
| 21 | + { |
| 22 | + builder.AddConfiguration(configuration); |
| 23 | + |
| 24 | + builder.AddOpenTelemetry(configureOpenTelemetry); |
| 25 | + }); |
| 26 | + |
| 27 | + return new DedicatedLoggerFactory(loggerFactory); |
| 28 | + }); |
| 29 | + |
| 30 | + services.TryAdd(ServiceDescriptor.Singleton(typeof(IDedicatedLogger<>), typeof(DedicatedLogger<>))); |
| 31 | + |
| 32 | + return services; |
| 33 | + } |
| 34 | + |
| 35 | + private sealed class DedicatedLogger<T> : IDedicatedLogger<T> |
| 36 | + { |
| 37 | + private readonly ILogger innerLogger; |
| 38 | + |
| 39 | + public DedicatedLogger(DedicatedLoggerFactory loggerFactory) |
| 40 | + { |
| 41 | + this.innerLogger = loggerFactory.CreateLogger(typeof(T).FullName!); |
| 42 | + } |
| 43 | + |
| 44 | + public IDisposable? BeginScope<TState>(TState state) |
| 45 | + where TState : notnull |
| 46 | + => this.innerLogger.BeginScope(state); |
| 47 | + |
| 48 | + public bool IsEnabled(LogLevel logLevel) |
| 49 | + => this.innerLogger.IsEnabled(logLevel); |
| 50 | + |
| 51 | + public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) |
| 52 | + => this.innerLogger.Log(logLevel, eventId, state, exception, formatter); |
| 53 | + } |
| 54 | + |
| 55 | + private sealed class DedicatedLoggerFactory : ILoggerFactory |
| 56 | + { |
| 57 | + private readonly ILoggerFactory innerLoggerFactory; |
| 58 | + |
| 59 | + public DedicatedLoggerFactory(ILoggerFactory loggerFactory) |
| 60 | + { |
| 61 | + this.innerLoggerFactory = loggerFactory; |
| 62 | + } |
| 63 | + |
| 64 | + public void AddProvider(ILoggerProvider provider) |
| 65 | + => this.innerLoggerFactory.AddProvider(provider); |
| 66 | + |
| 67 | + public ILogger CreateLogger(string categoryName) |
| 68 | + => this.innerLoggerFactory.CreateLogger(categoryName); |
| 69 | + |
| 70 | + public void Dispose() |
| 71 | + => this.innerLoggerFactory.Dispose(); |
| 72 | + } |
| 73 | +} |
0 commit comments