|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +#nullable enable |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.IO; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Microsoft.Extensions.Logging.Abstractions; |
| 10 | +using Microsoft.Extensions.Logging.Console; |
| 11 | +using Microsoft.Extensions.Options; |
| 12 | + |
| 13 | +namespace Microsoft.WebAssembly.AppHost; |
| 14 | + |
| 15 | +internal sealed class PassThroughConsoleFormatter : ConsoleFormatter, IDisposable |
| 16 | +{ |
| 17 | + private readonly IDisposable? _optionsReloadToken; |
| 18 | + private PassThroughConsoleFormatterOptions? _formatterOptions; |
| 19 | + |
| 20 | + public PassThroughConsoleFormatter(IOptionsMonitor<PassThroughConsoleFormatterOptions> options) |
| 21 | + : base("PassThroughConsoleFormatter") => |
| 22 | + (_optionsReloadToken, _formatterOptions) = |
| 23 | + (options.OnChange((options, _) => ReloadLoggerOptions(options)), options.CurrentValue); |
| 24 | + |
| 25 | + private void ReloadLoggerOptions(PassThroughConsoleFormatterOptions options) => _formatterOptions = options; |
| 26 | + |
| 27 | + public override void Write<TState>( |
| 28 | + in LogEntry<TState> logEntry, |
| 29 | + IExternalScopeProvider? scopeProvider, |
| 30 | + TextWriter textWriter) |
| 31 | + { |
| 32 | + string? message = |
| 33 | + logEntry.Formatter?.Invoke( |
| 34 | + logEntry.State, logEntry.Exception); |
| 35 | + |
| 36 | + if (message is null) |
| 37 | + { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if (!string.IsNullOrEmpty(_formatterOptions!.Prefix)) |
| 42 | + textWriter.Write(_formatterOptions!.Prefix); |
| 43 | + textWriter.WriteLine(message); |
| 44 | + } |
| 45 | + |
| 46 | + public void Dispose() => _optionsReloadToken?.Dispose(); |
| 47 | +} |
0 commit comments