| | 1 | | using System.Collections.Concurrent; |
| | 2 | | using Serilog; |
| | 3 | | using Serilog.Core; |
| | 4 | | using Serilog.Events; |
| | 5 | |
|
| | 6 | | namespace Kestrun.Logging; |
| | 7 | |
|
| | 8 | | /// <summary> |
| | 9 | | /// Convenience extensions for hooking Serilog loggers into <see cref="LoggerManager"/>. |
| | 10 | | /// </summary> |
| | 11 | | public static class LoggerConfigurationExtensions |
| | 12 | | { |
| 1 | 13 | | private static readonly ConcurrentDictionary<LoggerConfiguration, LoggingLevelSwitch> _switches = new(); |
| | 14 | |
|
| | 15 | | private static LoggingLevelSwitch NewEnsureSwitch(LoggerConfiguration config, LogEventLevel initial = LogEventLevel. |
| 0 | 16 | | => _switches.GetOrAdd(config, _ => new LoggingLevelSwitch(initial)); |
| | 17 | | /// <summary> |
| | 18 | | /// Create a logger from this configuration and register it by name. |
| | 19 | | /// </summary> |
| | 20 | | public static Serilog.ILogger Register(this LoggerConfiguration config, string name, bool setAsDefault = false) |
| | 21 | | { |
| 1 | 22 | | var logger = config.CreateLogger(); |
| 1 | 23 | | _ = _switches.TryRemove(config, out var levelSwitch); |
| | 24 | |
|
| 1 | 25 | | _ = LoggerManager.Register(name, logger, setAsDefault, levelSwitch); |
| | 26 | |
|
| 1 | 27 | | return logger; |
| | 28 | | } |
| | 29 | |
|
| | 30 | | /// <summary> |
| | 31 | | /// Ensure that the logger configuration has a logging level switch controlling its minimum level. |
| | 32 | | /// </summary> |
| | 33 | | /// <param name="config">The logger configuration to modify.</param> |
| | 34 | | /// <param name="initial">The initial minimum level for the switch.</param> |
| | 35 | | /// <returns>The modified logger configuration.</returns> |
| | 36 | | public static LoggerConfiguration EnsureSwitch(this LoggerConfiguration config, LogEventLevel initial = LogEventLeve |
| | 37 | | { |
| 0 | 38 | | var levelSwitch = NewEnsureSwitch(config, initial); |
| 0 | 39 | | _ = config.MinimumLevel.ControlledBy(levelSwitch); |
| 0 | 40 | | return config; |
| | 41 | | } |
| | 42 | | } |