From 8319033beaef616a96b47c61421d9d434935f932 Mon Sep 17 00:00:00 2001 From: Ben Olden-Cooligan Date: Tue, 20 Aug 2024 18:11:37 -0700 Subject: [PATCH] Lazy logger initialization --- NAPS2.Lib/Logging/LazyLogger.cs | 28 ++++++++++++++++++++++++++++ NAPS2.Lib/Modules/CommonModule.cs | 13 ++++++------- 2 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 NAPS2.Lib/Logging/LazyLogger.cs diff --git a/NAPS2.Lib/Logging/LazyLogger.cs b/NAPS2.Lib/Logging/LazyLogger.cs new file mode 100644 index 0000000000..020bbba770 --- /dev/null +++ b/NAPS2.Lib/Logging/LazyLogger.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Logging; + +namespace NAPS2.Logging; + +public class LazyLogger : ILogger +{ + private readonly Lazy _inner; + + public LazyLogger(Func inner) + { + _inner = new Lazy(inner); + } + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + _inner.Value.Log(logLevel, eventId, state, exception, formatter); + } + + public bool IsEnabled(LogLevel logLevel) + { + return _inner.Value.IsEnabled(logLevel); + } + + public IDisposable? BeginScope(TState state) where TState : notnull + { + return _inner.Value.BeginScope(state); + } +} \ No newline at end of file diff --git a/NAPS2.Lib/Modules/CommonModule.cs b/NAPS2.Lib/Modules/CommonModule.cs index 2989f02617..c3260f4041 100644 --- a/NAPS2.Lib/Modules/CommonModule.cs +++ b/NAPS2.Lib/Modules/CommonModule.cs @@ -37,8 +37,9 @@ protected override void Load(ContainerBuilder builder) // Config // TODO: Make this a usable path on Mac/Linux - builder.Register(_ => new Naps2Config(Path.Combine(Paths.Executable, "appsettings.xml"), - Path.Combine(Paths.AppData, "config.xml"))).SingleInstance(); + var config = new Naps2Config(Path.Combine(Paths.Executable, "appsettings.xml"), + Path.Combine(Paths.AppData, "config.xml")); + builder.RegisterInstance(config); // Remoting builder.Register(_ => WorkerFactory.CreateDefault()).SingleInstance(); @@ -50,11 +51,9 @@ protected override void Load(ContainerBuilder builder) builder.RegisterInstance(ProcessCoordinator.CreateDefault()); // Logging - builder.Register(ctx => - { - var config = ctx.Resolve(); - return NLogConfig.CreateLogger(() => config.Get(c => c.EnableDebugLogging)); - }).SingleInstance(); + var lazyLogger = new LazyLogger(() => + NLogConfig.CreateLogger(() => config.Get(c => c.EnableDebugLogging))); + builder.RegisterInstance(lazyLogger); // Misc builder.RegisterType().As();