refactor: Factory class for logging creation

Mainly for getting implementation details out of the composition root.
pull/76/head
Robert Dailey 3 years ago
parent 5fa23367a3
commit 1c63121c4e

@ -1,6 +1,7 @@
using System.IO.Abstractions; using System.IO.Abstractions;
using NSubstitute; using NSubstitute;
using NUnit.Framework; using NUnit.Framework;
using Recyclarr.Logging;
namespace Recyclarr.Tests; namespace Recyclarr.Tests;

@ -1,4 +1,6 @@
namespace Recyclarr.Command.Initialization; using Recyclarr.Logging;
namespace Recyclarr.Command.Initialization;
internal class OldLogFileCleaner : IServiceCleaner internal class OldLogFileCleaner : IServiceCleaner
{ {

@ -10,6 +10,7 @@ using Recyclarr.Command.Helpers;
using Recyclarr.Command.Initialization; using Recyclarr.Command.Initialization;
using Recyclarr.Command.Services; using Recyclarr.Command.Services;
using Recyclarr.Config; using Recyclarr.Config;
using Recyclarr.Logging;
using Recyclarr.Migration; using Recyclarr.Migration;
using Serilog; using Serilog;
using Serilog.Core; using Serilog.Core;
@ -31,19 +32,8 @@ public static class CompositionRoot
{ {
builder.RegisterType<LogJanitor>().As<ILogJanitor>(); builder.RegisterType<LogJanitor>().As<ILogJanitor>();
builder.RegisterType<LoggingLevelSwitch>().SingleInstance(); builder.RegisterType<LoggingLevelSwitch>().SingleInstance();
builder.Register(c => builder.RegisterType<LoggerFactory>();
{ builder.Register(c => c.Resolve<LoggerFactory>().Create())
var logPath = Path.Combine(AppPaths.LogDirectory,
$"trash_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.log");
const string consoleTemplate = "[{Level:u3}] {Message:lj}{NewLine}{Exception}";
return new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: consoleTemplate, levelSwitch: c.Resolve<LoggingLevelSwitch>())
.WriteTo.File(logPath)
.CreateLogger();
})
.As<ILogger>() .As<ILogger>()
.SingleInstance(); .SingleInstance();
} }

@ -1,4 +1,4 @@
namespace Recyclarr; namespace Recyclarr.Logging;
public interface ILogJanitor public interface ILogJanitor
{ {

@ -1,6 +1,6 @@
using System.IO.Abstractions; using System.IO.Abstractions;
namespace Recyclarr; namespace Recyclarr.Logging;
public class LogJanitor : ILogJanitor public class LogJanitor : ILogJanitor
{ {

@ -0,0 +1,30 @@
using System.IO.Abstractions;
using Serilog;
using Serilog.Core;
namespace Recyclarr.Logging;
public class LoggerFactory
{
private readonly IFileSystem _fs;
private readonly LoggingLevelSwitch _logLevel;
public LoggerFactory(IFileSystem fs, LoggingLevelSwitch logLevel)
{
_fs = fs;
_logLevel = logLevel;
}
public ILogger Create()
{
var logPath = _fs.Path.Combine(AppPaths.LogDirectory, $"trash_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.log");
const string consoleTemplate = "[{Level:u3}] {Message:lj}{NewLine}{Exception}";
return new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: consoleTemplate, levelSwitch: _logLevel)
.WriteTo.File(logPath)
.CreateLogger();
}
}
Loading…
Cancel
Save