|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using Microsoft.Extensions.Options; |
| 7 | + |
| 8 | +namespace Microsoft.PowerShell.EditorServices.Logging; |
| 9 | +internal class DynamicLogLevelOptions( |
| 10 | + LogLevel initialLevel, |
| 11 | + IOptionsMonitor<LoggerFilterOptions> optionsMonitor) : IConfigureOptions<LoggerFilterOptions> |
| 12 | +{ |
| 13 | + private LogLevel _currentLevel = initialLevel; |
| 14 | + private readonly IOptionsMonitor<LoggerFilterOptions> _optionsMonitor = optionsMonitor; |
| 15 | + |
| 16 | + public void Configure(LoggerFilterOptions options) => options.MinLevel = _currentLevel; |
| 17 | + |
| 18 | + public void SetLogLevel(LogLevel level) |
| 19 | + { |
| 20 | + _currentLevel = level; |
| 21 | + // Trigger reload of options to apply new log level |
| 22 | + _optionsMonitor.CurrentValue.MinLevel = level; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +public static class LoggingBuilderExtensions |
| 27 | +{ |
| 28 | + public static ILoggingBuilder AddLspClientConfigurableMinimumLevel( |
| 29 | + this ILoggingBuilder builder, |
| 30 | + LogLevel initialLevel = LogLevel.Trace |
| 31 | + ) |
| 32 | + { |
| 33 | + builder.Services.AddOptions<LoggerFilterOptions>(); |
| 34 | + builder.Services.AddSingleton<DynamicLogLevelOptions>(sp => |
| 35 | + { |
| 36 | + IOptionsMonitor<LoggerFilterOptions> optionsMonitor = sp.GetRequiredService<IOptionsMonitor<LoggerFilterOptions>>(); |
| 37 | + return new(initialLevel, optionsMonitor); |
| 38 | + }); |
| 39 | + builder.Services.AddSingleton<IConfigureOptions<LoggerFilterOptions>>(sp => |
| 40 | + sp.GetRequiredService<DynamicLogLevelOptions>()); |
| 41 | + return builder; |
| 42 | + } |
| 43 | +} |
| 44 | + |
0 commit comments