Skip to content

Commit

Permalink
Lazy logger initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
cyanfish committed Aug 21, 2024
1 parent d64b88e commit 8319033
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
28 changes: 28 additions & 0 deletions NAPS2.Lib/Logging/LazyLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.Extensions.Logging;

namespace NAPS2.Logging;

public class LazyLogger : ILogger
{
private readonly Lazy<ILogger> _inner;

public LazyLogger(Func<ILogger> inner)
{
_inner = new Lazy<ILogger>(inner);
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
_inner.Value.Log(logLevel, eventId, state, exception, formatter);
}

public bool IsEnabled(LogLevel logLevel)
{
return _inner.Value.IsEnabled(logLevel);
}

public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return _inner.Value.BeginScope(state);
}
}
13 changes: 6 additions & 7 deletions NAPS2.Lib/Modules/CommonModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IWorkerFactory>(_ => WorkerFactory.CreateDefault()).SingleInstance();
Expand All @@ -50,11 +51,9 @@ protected override void Load(ContainerBuilder builder)
builder.RegisterInstance(ProcessCoordinator.CreateDefault());

// Logging
builder.Register<ILogger>(ctx =>
{
var config = ctx.Resolve<Naps2Config>();
return NLogConfig.CreateLogger(() => config.Get(c => c.EnableDebugLogging));
}).SingleInstance();
var lazyLogger = new LazyLogger(() =>
NLogConfig.CreateLogger(() => config.Get(c => c.EnableDebugLogging)));
builder.RegisterInstance<ILogger>(lazyLogger);

// Misc
builder.RegisterType<AutofacFormFactory>().As<IFormFactory>();
Expand Down

0 comments on commit 8319033

Please sign in to comment.