Add WireMockNullLogger as valid commandline logger option (#845)

* Add WireMockNullLogger as valid commandline logger option

* .
This commit is contained in:
Stef Heyenrath
2022-11-06 13:25:26 +01:00
committed by GitHub
parent 49b29d74dc
commit 7fd1d30d0e
7 changed files with 190 additions and 189 deletions

View File

@@ -2,73 +2,72 @@ using Newtonsoft.Json;
using System; using System;
using WireMock.Admin.Requests; using WireMock.Admin.Requests;
namespace WireMock.Logging namespace WireMock.Logging;
/// <summary>
/// WireMockConsoleLogger which logs to Console
/// </summary>
/// <seealso cref="IWireMockLogger" />
public class WireMockConsoleLogger : IWireMockLogger
{ {
/// <summary> /// <summary>
/// WireMockConsoleLogger which logs to Console /// Initializes a new instance of the <see cref="WireMockConsoleLogger"/> class.
/// </summary> /// </summary>
/// <seealso cref="IWireMockLogger" /> public WireMockConsoleLogger()
public class WireMockConsoleLogger : IWireMockLogger
{ {
/// <summary> Console.OutputEncoding = System.Text.Encoding.UTF8;
/// Initializes a new instance of the <see cref="WireMockConsoleLogger"/> class. }
/// </summary>
public WireMockConsoleLogger()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
}
/// <see cref="IWireMockLogger.Debug"/> /// <see cref="IWireMockLogger.Debug"/>
public void Debug(string formatString, params object[] args) public void Debug(string formatString, params object[] args)
{ {
Console.WriteLine(Format("Debug", formatString, args)); Console.WriteLine(Format("Debug", formatString, args));
} }
/// <see cref="IWireMockLogger.Info"/> /// <see cref="IWireMockLogger.Info"/>
public void Info(string formatString, params object[] args) public void Info(string formatString, params object[] args)
{ {
Console.WriteLine(Format("Info", formatString, args)); Console.WriteLine(Format("Info", formatString, args));
} }
/// <see cref="IWireMockLogger.Warn"/> /// <see cref="IWireMockLogger.Warn"/>
public void Warn(string formatString, params object[] args) public void Warn(string formatString, params object[] args)
{ {
Console.WriteLine(Format("Warn", formatString, args)); Console.WriteLine(Format("Warn", formatString, args));
} }
/// <see cref="IWireMockLogger.Error(string, object[])"/> /// <see cref="IWireMockLogger.Error(string, object[])"/>
public void Error(string formatString, params object[] args) public void Error(string formatString, params object[] args)
{ {
Console.WriteLine(Format("Error", formatString, args)); Console.WriteLine(Format("Error", formatString, args));
} }
/// <see cref="IWireMockLogger.Error(string, Exception)"/> /// <see cref="IWireMockLogger.Error(string, Exception)"/>
public void Error(string formatString, Exception exception) public void Error(string formatString, Exception exception)
{ {
Console.WriteLine(Format("Error", formatString, exception.Message)); Console.WriteLine(Format("Error", formatString, exception.Message));
if (exception is AggregateException ae) if (exception is AggregateException ae)
{
ae.Handle(ex =>
{ {
ae.Handle(ex => Console.WriteLine(Format("Error", "Exception {0}", ex.Message));
{ return true;
Console.WriteLine(Format("Error", "Exception {0}", ex.Message)); });
return true;
});
}
}
/// <see cref="IWireMockLogger.DebugRequestResponse"/>
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented);
Console.WriteLine(Format("DebugRequestResponse", "Admin[{0}] {1}", isAdminRequest, message));
}
private static string Format(string level, string formatString, params object[] args)
{
var message = args.Length > 0 ? string.Format(formatString, args) : formatString;
return $"{DateTime.UtcNow} [{level}] : {message}";
} }
} }
/// <see cref="IWireMockLogger.DebugRequestResponse"/>
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented);
Console.WriteLine(Format("DebugRequestResponse", "Admin[{0}] {1}", isAdminRequest, message));
}
private static string Format(string level, string formatString, params object[] args)
{
var message = args.Length > 0 ? string.Format(formatString, args) : formatString;
return $"{DateTime.UtcNow} [{level}] : {message}";
}
} }

View File

@@ -1,48 +1,47 @@
using System; using System;
using WireMock.Admin.Requests; using WireMock.Admin.Requests;
namespace WireMock.Logging namespace WireMock.Logging;
/// <summary>
/// WireMockNullLogger which does not log.
/// </summary>
/// <seealso cref="IWireMockLogger" />
public class WireMockNullLogger : IWireMockLogger
{ {
/// <summary> /// <see cref="IWireMockLogger.Debug"/>
/// WireMockNullLogger which does not log. public void Debug(string formatString, params object[] args)
/// </summary>
/// <seealso cref="IWireMockLogger" />
public class WireMockNullLogger : IWireMockLogger
{ {
/// <see cref="IWireMockLogger.Debug"/> // Log nothing
public void Debug(string formatString, params object[] args) }
{
// Log nothing
}
/// <see cref="IWireMockLogger.Info"/> /// <see cref="IWireMockLogger.Info"/>
public void Info(string formatString, params object[] args) public void Info(string formatString, params object[] args)
{ {
// Log nothing // Log nothing
} }
/// <see cref="IWireMockLogger.Warn"/> /// <see cref="IWireMockLogger.Warn"/>
public void Warn(string formatString, params object[] args) public void Warn(string formatString, params object[] args)
{ {
// Log nothing // Log nothing
} }
/// <see cref="IWireMockLogger.Error(string, object[])"/> /// <see cref="IWireMockLogger.Error(string, object[])"/>
public void Error(string formatString, params object[] args) public void Error(string formatString, params object[] args)
{ {
// Log nothing // Log nothing
} }
/// <see cref="IWireMockLogger.Error(string, Exception)"/> /// <see cref="IWireMockLogger.Error(string, Exception)"/>
public void Error(string formatString, Exception exception) public void Error(string formatString, Exception exception)
{ {
// Log nothing // Log nothing
} }
/// <see cref="IWireMockLogger.DebugRequestResponse"/> /// <see cref="IWireMockLogger.DebugRequestResponse"/>
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{ {
// Log nothing // Log nothing
}
} }
} }

View File

@@ -62,13 +62,23 @@ public static class WireMockServerSettingsParser
settings.CorsPolicyOptions = parser.GetEnumValue(nameof(WireMockServerSettings.CorsPolicyOptions), CorsPolicyOptions.None); settings.CorsPolicyOptions = parser.GetEnumValue(nameof(WireMockServerSettings.CorsPolicyOptions), CorsPolicyOptions.None);
#endif #endif
if (logger != null) var loggerType = parser.GetStringValue("WireMockLogger");
switch (loggerType)
{ {
settings.Logger = logger; case nameof(WireMockConsoleLogger):
} settings.Logger = new WireMockConsoleLogger();
else if (parser.GetStringValue("WireMockLogger") == "WireMockConsoleLogger") break;
{
settings.Logger = new WireMockConsoleLogger(); case nameof(WireMockNullLogger):
settings.Logger = new WireMockNullLogger();
break;
default:
if (logger != null)
{
settings.Logger = logger;
}
break;
} }
if (parser.Contains(nameof(WireMockServerSettings.Port))) if (parser.Contains(nameof(WireMockServerSettings.Port)))

View File

@@ -21,10 +21,6 @@
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
</PropertyGroup> </PropertyGroup>
<!--<ItemGroup>
<None Include="WireMock.Net-Logo.png" Pack="true" PackagePath="../../"/>
</ItemGroup>-->
<!-- https://github.com/aspnet/RoslynCodeDomProvider/issues/51 --> <!-- https://github.com/aspnet/RoslynCodeDomProvider/issues/51 -->
<!-- This is needed else we cannot build net452 in Azure DevOps Pipeline --> <!-- This is needed else we cannot build net452 in Azure DevOps Pipeline -->
<!--<Target Name="CheckIfShouldKillVBCSCompiler" />--> <!--<Target Name="CheckIfShouldKillVBCSCompiler" />-->
@@ -145,7 +141,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' "> <ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<!--<PackageReference Include="System.Diagnostics.CodeAnalysis" Version="4.3.0" />-->
<PackageReference Include="Nullable" Version="1.3.0" /> <PackageReference Include="Nullable" Version="1.3.0" />
</ItemGroup> </ItemGroup>

View File

@@ -5,56 +5,55 @@ using WireMock.Logging;
using WireMock.Net.StandAlone; using WireMock.Net.StandAlone;
using WireMock.Server; using WireMock.Server;
namespace WireMock.Net namespace WireMock.Net;
public class Program
{ {
public class Program private static readonly int SleepTime = 30000;
private static readonly ILogger XLogger = LoggerFactory.Create(o =>
{ {
private static readonly int SleepTime = 30000; o.SetMinimumLevel(LogLevel.Debug);
private static readonly ILogger xLogger = LoggerFactory.Create(o => o.AddSimpleConsole(options =>
{ {
o.SetMinimumLevel(LogLevel.Debug); options.IncludeScopes = true;
o.AddSimpleConsole(options => options.SingleLine = false;
{ options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss ";
options.IncludeScopes = true; });
options.SingleLine = false; }).CreateLogger("WireMock.Net");
options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss "; private static readonly IWireMockLogger Logger = new WireMockLogger(XLogger);
});
}).CreateLogger("WireMock.Net");
private static readonly IWireMockLogger Logger = new WireMockLogger(xLogger);
private static WireMockServer Server; private static WireMockServer _server = null!;
static async Task Main(string[] args) static async Task Main(string[] args)
{
if (!StandAloneApp.TryStart(args, out _server!, Logger))
{ {
if (!StandAloneApp.TryStart(args, out Server, Logger)) return;
{
return;
}
Logger.Info("Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};
while (true)
{
Logger.Info("Server running : {IsStarted}", Server.IsStarted);
await Task.Delay(SleepTime).ConfigureAwait(false);
}
} }
private static void Stop(string why) Logger.Info("Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) =>
{ {
Logger.Info("Server stopping because '{why}'", why); Stop("CancelKeyPress");
Server.Stop(); };
Logger.Info("Server stopped");
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};
while (true)
{
Logger.Info("Server running : {0}", _server.IsStarted);
await Task.Delay(SleepTime).ConfigureAwait(false);
} }
} }
private static void Stop(string why)
{
Logger.Info("Server stopping because '{0}'", why);
_server.Stop();
Logger.Info("Server stopped");
}
} }

View File

@@ -1,8 +1,8 @@
{ {
"profiles": { "profiles": {
"dotnet-WireMock.Net": { "dotnet-WireMock.Net": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "" "commandLineArgs": "--WireMockLogger s"
} }
} }
} }

View File

@@ -4,58 +4,57 @@ using Microsoft.Extensions.Logging;
using WireMock.Admin.Requests; using WireMock.Admin.Requests;
using WireMock.Logging; using WireMock.Logging;
namespace WireMock.Net namespace WireMock.Net;
public class WireMockLogger : IWireMockLogger
{ {
public class WireMockLogger : IWireMockLogger private readonly JsonSerializerOptions _options = new()
{ {
private readonly JsonSerializerOptions options = new JsonSerializerOptions WriteIndented = true
{ };
WriteIndented = true
};
private readonly ILogger _logger; private readonly ILogger _logger;
public WireMockLogger(ILogger logger) public WireMockLogger(ILogger logger)
{ {
_logger = logger; _logger = logger;
} }
/// <see cref="IWireMockLogger.Debug"/> /// <see cref="IWireMockLogger.Debug"/>
public void Debug(string formatString, params object[] args) public void Debug(string formatString, params object[] args)
{ {
_logger.LogDebug(formatString, args); _logger.LogDebug(formatString, args);
} }
/// <see cref="IWireMockLogger.Info"/> /// <see cref="IWireMockLogger.Info"/>
public void Info(string formatString, params object[] args) public void Info(string formatString, params object[] args)
{ {
_logger.LogInformation(formatString, args); _logger.LogInformation(formatString, args);
} }
/// <see cref="IWireMockLogger.Warn"/> /// <see cref="IWireMockLogger.Warn"/>
public void Warn(string formatString, params object[] args) public void Warn(string formatString, params object[] args)
{ {
_logger.LogWarning(formatString, args); _logger.LogWarning(formatString, args);
} }
/// <see cref="IWireMockLogger.Error(string, object[])"/> /// <see cref="IWireMockLogger.Error(string, object[])"/>
public void Error(string formatString, params object[] args) public void Error(string formatString, params object[] args)
{ {
_logger.LogError(formatString, args); _logger.LogError(formatString, args);
} }
/// <see cref="IWireMockLogger.Error(string, Exception)"/> /// <see cref="IWireMockLogger.Error(string, Exception)"/>
public void Error(string formatString, Exception exception) public void Error(string formatString, Exception exception)
{ {
_logger.LogError(formatString, exception); _logger.LogError(formatString, exception);
} }
/// <see cref="IWireMockLogger.DebugRequestResponse"/> /// <see cref="IWireMockLogger.DebugRequestResponse"/>
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{ {
string message = JsonSerializer.Serialize(logEntryModel, options); string message = JsonSerializer.Serialize(logEntryModel, _options);
_logger.LogDebug("Admin[{IsAdmin}] {Message}", isAdminRequest, message); _logger.LogDebug("Admin[{IsAdmin}] {Message}", isAdminRequest, message);
}
} }
} }