Skip to content

Commit

Permalink
Replace log4net with Serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
dfederm committed Aug 8, 2024
1 parent 7c0f1c3 commit a3b4f69
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 186 deletions.
7 changes: 6 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="log4net" Version="2.0.17" />
<PackageVersion Include="Microsoft.Build" Version="17.10.4" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageVersion Include="NuGet.Commands" Version="6.10.1" />
<PackageVersion Include="Serilog" Version="4.0.1" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.Async" Version="2.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageVersion Include="Shouldly" Version="4.2.1" />
<PackageVersion Include="xunit" Version="2.9.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
Expand Down
108 changes: 1 addition & 107 deletions src/PackagesConfigConverter.UnitTests/E2ETests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
//
// Licensed under the MIT license.

using log4net;
using log4net.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -108,7 +106,7 @@ public void E2ETest(string testCase)
var converterSettings = new ProjectConverterSettings()
{
Include = ConverterInclude,
Log = new TestLog(TestOutputHelper),
Log = new XUnitLogger(TestOutputHelper),
RepositoryRoot = workingDir,
};
var converter = new ProjectConverter(converterSettings);
Expand All @@ -121,109 +119,5 @@ public void E2ETest(string testCase)
string actualProjectContent = File.ReadAllText(Path.Combine(workingDir, BeforeProjectName));
Assert.Equal(expectedProjectContent, actualProjectContent);
}

private sealed class TestLog : ILog
{
private const string DebugLevel = "Debug";
private const string ErrorLevel = "Error";
private const string FatalLevel = "Fatal";
private const string InfoLevel = "Info";
private const string WarnLevel = "Warn";

private readonly ITestOutputHelper _testOutputHelper;

public TestLog(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}

public bool IsDebugEnabled => true;

public bool IsInfoEnabled => true;

public bool IsWarnEnabled => true;

public bool IsErrorEnabled => true;

public bool IsFatalEnabled => true;

public ILogger Logger => throw new NotImplementedException();

public void Debug(object message) => Log(DebugLevel, message);

public void Debug(object message, Exception exception) => Log(DebugLevel, message, exception);

public void DebugFormat(string format, params object[] args) => Log(DebugLevel, format, args);

public void DebugFormat(string format, object arg0) => Log(DebugLevel, string.Format(format, arg0));

public void DebugFormat(string format, object arg0, object arg1) => Log(DebugLevel, string.Format(format, arg0, arg1));

public void DebugFormat(string format, object arg0, object arg1, object arg2) => Log(DebugLevel, string.Format(format, arg0, arg2));

public void DebugFormat(IFormatProvider provider, string format, params object[] args) => Log(DebugLevel, string.Format(provider, format, args));

public void Error(object message) => Log(ErrorLevel, message);

public void Error(object message, Exception exception) => Log(ErrorLevel, message, exception);

public void ErrorFormat(string format, params object[] args) => Log(ErrorLevel, format, args);

public void ErrorFormat(string format, object arg0) => Log(ErrorLevel, string.Format(format, arg0));

public void ErrorFormat(string format, object arg0, object arg1) => Log(ErrorLevel, string.Format(format, arg0, arg1));

public void ErrorFormat(string format, object arg0, object arg1, object arg2) => Log(ErrorLevel, string.Format(format, arg0, arg2));

public void ErrorFormat(IFormatProvider provider, string format, params object[] args) => Log(ErrorLevel, string.Format(provider, format, args));

public void Fatal(object message) => Log(FatalLevel, message);

public void Fatal(object message, Exception exception) => Log(FatalLevel, message, exception);

public void FatalFormat(string format, params object[] args) => Log(FatalLevel, format, args);

public void FatalFormat(string format, object arg0) => Log(FatalLevel, string.Format(format, arg0));

public void FatalFormat(string format, object arg0, object arg1) => Log(FatalLevel, string.Format(format, arg0, arg1));

public void FatalFormat(string format, object arg0, object arg1, object arg2) => Log(FatalLevel, string.Format(format, arg0, arg2));

public void FatalFormat(IFormatProvider provider, string format, params object[] args) => Log(FatalLevel, string.Format(provider, format, args));

public void Info(object message) => Log(InfoLevel, message);

public void Info(object message, Exception exception) => Log(InfoLevel, message, exception);

public void InfoFormat(string format, params object[] args) => Log(InfoLevel, format, args);

public void InfoFormat(string format, object arg0) => Log(InfoLevel, string.Format(format, arg0));

public void InfoFormat(string format, object arg0, object arg1) => Log(InfoLevel, string.Format(format, arg0, arg1));

public void InfoFormat(string format, object arg0, object arg1, object arg2) => Log(InfoLevel, string.Format(format, arg0, arg2));

public void InfoFormat(IFormatProvider provider, string format, params object[] args) => Log(InfoLevel, string.Format(provider, format, args));

public void Warn(object message) => Log(WarnLevel, message);

public void Warn(object message, Exception exception) => Log(WarnLevel, message, exception);

public void WarnFormat(string format, params object[] args) => Log(WarnLevel, format, args);

public void WarnFormat(string format, object arg0) => Log(WarnLevel, string.Format(format, arg0));

public void WarnFormat(string format, object arg0, object arg1) => Log(WarnLevel, string.Format(format, arg0, arg1));

public void WarnFormat(string format, object arg0, object arg1, object arg2) => Log(WarnLevel, string.Format(format, arg0, arg2));

public void WarnFormat(IFormatProvider provider, string format, params object[] args) => Log(WarnLevel, string.Format(provider, format, args));

private void Log(string level, object message) => _testOutputHelper.WriteLine($"[{level}] {message}");

private void Log(string level, object message, Exception exception) => _testOutputHelper.WriteLine($"[{level}] {message}. Exception: {exception}");

private void Log(string level, string format, params object[] args) => _testOutputHelper.WriteLine($"[{level}] {format}", args);
}
}
}
28 changes: 28 additions & 0 deletions src/PackagesConfigConverter.UnitTests/XUnitLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Jeff Kluge. All rights reserved.
//
// Licensed under the MIT license.

using Microsoft.Extensions.Logging;
using System;
using Xunit.Abstractions;

namespace PackagesConfigConverter.UnitTests
{
internal sealed class XUnitLogger : ILogger
{
private readonly ITestOutputHelper _testOutputHelper;

public XUnitLogger(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}

public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;

public IDisposable BeginScope<TState>(TState state)
where TState : notnull => null;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
=> _testOutputHelper.WriteLine(formatter(state, exception));
}
}
7 changes: 6 additions & 1 deletion src/PackagesConfigConverter/PackagesConfigConverter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" />
<PackageReference Include="log4net" />
<PackageReference Include="Microsoft.Build" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="NuGet.Commands" />
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Logging" />
<PackageReference Include="Serilog.Sinks.Async" />
<PackageReference Include="Serilog.Sinks.Console" />
<PackageReference Include="Serilog.Sinks.File" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="PackagesConfigConverter.UnitTests" />
Expand Down
84 changes: 40 additions & 44 deletions src/PackagesConfigConverter/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,26 @@
// Licensed under the MIT license.

using CommandLine;
using log4net;
using log4net.Appender;
using log4net.Core;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;

using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace PackagesConfigConverter
{
internal class Program
{
private static readonly CancellationTokenSource CancellationTokenSource = new ();

private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

public static int Main(string[] args)
{
int ret = 0;

try
{
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = false;
Log.Info("Cancelling...");
CancellationTokenSource.Cancel();
};

new Parser(parserSettings =>
{
parserSettings.CaseInsensitiveEnumValues = true;
Expand Down Expand Up @@ -71,19 +59,22 @@ public static void Run(ProgramArguments arguments)

ConfigureLogger(arguments);

using ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddSerilog());
ILogger logger = factory.CreateLogger("PackagesConfigConverter");

ProjectConverterSettings settings = new ProjectConverterSettings
{
RepositoryRoot = arguments.RepoRoot,
Include = arguments.Include.ToRegex(),
Exclude = arguments.Exclude.ToRegex(),
Log = Log,
Log = logger,
TrimPackages = arguments.Trim,
};

Log.Info($" RepositoryRoot: '{settings.RepositoryRoot}'");
Log.Info($" Include regex: '{settings.Include}'");
Log.Info($" Exclude regex: '{settings.Exclude}'");
Log.Info(string.Empty);
logger.LogInformation($" RepositoryRoot: '{settings.RepositoryRoot}'");
logger.LogInformation($" Include regex: '{settings.Include}'");
logger.LogInformation($" Exclude regex: '{settings.Exclude}'");
logger.LogInformation(string.Empty);

if (!arguments.Yes)
{
Expand All @@ -94,39 +85,44 @@ public static void Run(ProgramArguments arguments)
}
}

var cancellationTokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = false;
logger.LogInformation("Cancelling...");
cancellationTokenSource.Cancel();
};

using IProjectConverter projectConverter = ProjectConverterFactory.Create(settings);

projectConverter.ConvertRepository(CancellationTokenSource.Token);
projectConverter.ConvertRepository(cancellationTokenSource.Token);
}

private static void ConfigureLogger(ProgramArguments arguments)
{
foreach (AppenderSkeleton appender in Log.Logger.Repository.GetAppenders().OfType<AppenderSkeleton>())
var loggingConfiguration = new LoggerConfiguration();

loggingConfiguration.MinimumLevel.Is(arguments.Verbose ? LogEventLevel.Verbose : LogEventLevel.Debug);

// Always write to the console.
LogEventLevel consoleLogLevel = arguments.Verbose ? LogEventLevel.Verbose : LogEventLevel.Information;
loggingConfiguration.WriteTo.Console(consoleLogLevel);

if (arguments.LogFile != null)
{
switch (appender)
string logFile = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(arguments.LogFile));
if (File.Exists(logFile))
{
case FileAppender fileAppender:
if (arguments.LogFile != null)
{
fileAppender.File = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(arguments.LogFile));
}
else
{
fileAppender.Threshold = Level.Off;
}

fileAppender.ActivateOptions();

break;
File.Delete(logFile);
}

if (arguments.Verbose)
{
appender.Threshold = Level.Verbose;

appender.ActivateOptions();
}
LogEventLevel fileLogLevel = arguments.Verbose ? LogEventLevel.Verbose : LogEventLevel.Debug;
loggingConfiguration.WriteTo.Async(a => a.File(logFile, fileLogLevel));
}

Log.Logger = loggingConfiguration.CreateLogger();
}
}
}
Loading

0 comments on commit a3b4f69

Please sign in to comment.