Replace log4net by custom logger (#94) (#96)

* Replace log4net by custom logger

* WireMockNullLogger
This commit is contained in:
Stef Heyenrath
2018-02-28 07:01:03 +00:00
committed by GitHub
parent e850126184
commit 938d3fb095
22 changed files with 236 additions and 52 deletions

View File

@@ -3,7 +3,7 @@ using WireMock.Server;
using WireMock.Settings;
using WireMock.Validation;
using JetBrains.Annotations;
using log4net;
using WireMock.Logging;
namespace WireMock.Net.StandAlone
{
@@ -12,8 +12,6 @@ namespace WireMock.Net.StandAlone
/// </summary>
public static class StandAloneApp
{
private static readonly ILog Log = LogManager.GetLogger(typeof(StandAloneApp));
/// <summary>
/// Start WireMock.Net standalone Server based on the FluentMockServerSettings.
/// </summary>
@@ -30,13 +28,12 @@ namespace WireMock.Net.StandAlone
/// Start WireMock.Net standalone Server based on the commandline arguments.
/// </summary>
/// <param name="args">The commandline arguments</param>
/// <param name="logger">The logger</param>
[PublicAPI]
public static FluentMockServer Start([NotNull] string[] args)
public static FluentMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null)
{
Check.NotNull(args, nameof(args));
Log.DebugFormat("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
var parser = new SimpleCommandLineParser();
parser.Parse(args);
@@ -52,6 +49,11 @@ namespace WireMock.Net.StandAlone
RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"),
};
if (logger != null)
{
settings.Logger = logger;
}
if (parser.Contains("Port"))
{
settings.Port = parser.GetIntValue("Port");
@@ -74,9 +76,11 @@ namespace WireMock.Net.StandAlone
};
}
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
FluentMockServer server = Start(settings);
Log.InfoFormat("WireMock.Net server listening at {0}", string.Join(",", server.Urls));
settings.Logger.Info("WireMock.Net server listening at {0}", string.Join(",", server.Urls));
return server;
}

View File

@@ -36,7 +36,6 @@
<PackageReference Include="JetBrains.Annotations" Version="10.4.0">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="log4net" Version="2.0.8" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,47 @@
using JetBrains.Annotations;
namespace WireMock.Logging
{
/// <summary>
/// IWireMockLogger interface
/// </summary>
[PublicAPI]
public interface IWireMockLogger
{
/// <summary>
/// Writes the message at the Debug level using the specified parameters.
/// </summary>
/// <param name="formatString">The format string.</param>
/// <param name="args">The arguments.</param>
[PublicAPI]
[StringFormatMethod("formatString")]
void Debug([NotNull] string formatString, [NotNull] params object[] args);
/// <summary>
/// Writes the message at the Info level using the specified parameters.
/// </summary>
/// <param name="formatString">The format string.</param>
/// <param name="args">The arguments.</param>
[PublicAPI]
[StringFormatMethod("formatString")]
void Info([NotNull] string formatString, [NotNull] params object[] args);
/// <summary>
/// Writes the message at the Warning level using the specified parameters.
/// </summary>
/// <param name="formatString">The format string.</param>
/// <param name="args">The arguments.</param>
[PublicAPI]
[StringFormatMethod("formatString")]
void Warn([NotNull] string formatString, [NotNull] params object[] args);
/// <summary>
/// Writes the message at the Error level using the specified parameters.
/// </summary>
/// <param name="formatString">The format string.</param>
/// <param name="args">The arguments.</param>
[PublicAPI]
[StringFormatMethod("formatString")]
void Error([NotNull] string formatString, [NotNull] params object[] args);
}
}

View File

@@ -0,0 +1,42 @@
using System;
namespace WireMock.Logging
{
/// <summary>
/// WireMockConsoleLogger which logs to Console
/// </summary>
/// <seealso cref="IWireMockLogger" />
public class WireMockConsoleLogger : IWireMockLogger
{
/// <see cref="IWireMockLogger.Debug"/>
public void Debug(string formatString, params object[] args)
{
Console.WriteLine(Format("Debug", formatString, args));
}
/// <see cref="IWireMockLogger.Info"/>
public void Info(string formatString, params object[] args)
{
Console.WriteLine(Format("Info", formatString, args));
}
/// <see cref="IWireMockLogger.Warn"/>
public void Warn(string formatString, params object[] args)
{
Console.WriteLine(Format("Warn", formatString, args));
}
/// <see cref="IWireMockLogger.Error"/>
public void Error(string formatString, params object[] args)
{
Console.WriteLine(Format("Error", formatString, args));
}
private static string Format(string level, string formatString, params object[] args)
{
string message = string.Format(formatString, args);
return $"{DateTime.UtcNow} [{level}] : {message}";
}
}
}

View File

@@ -0,0 +1,29 @@
namespace WireMock.Logging
{
/// <summary>
/// WireMockNullLogger which does not log.
/// </summary>
/// <seealso cref="IWireMockLogger" />
public class WireMockNullLogger : IWireMockLogger
{
/// <see cref="IWireMockLogger.Debug"/>
public void Debug(string formatString, params object[] args)
{
}
/// <see cref="IWireMockLogger.Info"/>
public void Info(string formatString, params object[] args)
{
}
/// <see cref="IWireMockLogger.Warn"/>
public void Warn(string formatString, params object[] args)
{
}
/// <see cref="IWireMockLogger.Error"/>
public void Error(string formatString, params object[] args)
{
}
}
}

View File

@@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
@@ -50,7 +49,7 @@ namespace WireMock.Owin
_host = new WebHostBuilder()
.Configure(appBuilder =>
{
appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
appBuilder.UseMiddleware<GlobalExceptionMiddleware>(_options);
_options.PreWireMockMiddlewareInit?.Invoke(appBuilder);
@@ -70,13 +69,13 @@ namespace WireMock.Owin
foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase)))
{
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port);
options.Listen(IPAddress.Loopback, port);
options.Listen(System.Net.IPAddress.Loopback, port);
}
foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
{
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port);
options.Listen(IPAddress.Loopback, port, listenOptions =>
options.Listen(System.Net.IPAddress.Loopback, port, listenOptions =>
{
listenOptions.UseHttps(PublicCertificateHelper.GetX509Certificate2());
});

View File

@@ -1,6 +1,5 @@
using System;
using System.Threading.Tasks;
using log4net;
using Newtonsoft.Json;
#if !NETSTANDARD
using Microsoft.Owin;
@@ -16,13 +15,18 @@ namespace WireMock.Owin
internal class GlobalExceptionMiddleware
#endif
{
private static readonly ILog Log = LogManager.GetLogger(typeof(GlobalExceptionMiddleware));
private readonly WireMockMiddlewareOptions _options;
#if !NETSTANDARD
public GlobalExceptionMiddleware(OwinMiddleware next) : base(next) { }
public GlobalExceptionMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
{
_options = options;
}
#else
public GlobalExceptionMiddleware(RequestDelegate next)
public GlobalExceptionMiddleware(RequestDelegate next, WireMockMiddlewareOptions options)
{
Next = next;
_options = options;
}
#endif
@@ -44,7 +48,7 @@ namespace WireMock.Owin
}
catch (Exception ex)
{
Log.Error("HttpStatusCode set to 500", ex);
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) }, ctx.Response);
}
}

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
// using System.IO;
using System.Linq;
using System.Text;
// using System.Text;
using System.Threading.Tasks;
using WireMock.Util;
#if !NETSTANDARD

View File

@@ -61,7 +61,7 @@ namespace WireMock.Owin
Action<IAppBuilder> startup = app =>
{
app.Use<GlobalExceptionMiddleware>();
app.Use<GlobalExceptionMiddleware>(_options);
_options.PreWireMockMiddlewareInit?.Invoke(app);
app.Use<WireMockMiddleware>(_options);
_options.PostWireMockMiddlewareInit?.Invoke(app);

View File

@@ -3,7 +3,6 @@ using System.Threading.Tasks;
using WireMock.Logging;
using WireMock.Matchers.Request;
using System.Linq;
using log4net;
using WireMock.Matchers;
using WireMock.Util;
using Newtonsoft.Json;
@@ -22,7 +21,6 @@ namespace WireMock.Owin
internal class WireMockMiddleware
#endif
{
private static readonly ILog Log = LogManager.GetLogger(typeof(WireMockMiddleware));
private static readonly Task CompletedTask = Task.FromResult(false);
private readonly WireMockMiddlewareOptions _options;
@@ -98,7 +96,7 @@ namespace WireMock.Owin
if (targetMapping == null)
{
logRequest = true;
Log.Warn("HttpStatusCode set to 404 : No matching mapping found");
_options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
return;
}
@@ -110,7 +108,7 @@ namespace WireMock.Owin
bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<string> authorization);
if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
{
Log.Error("HttpStatusCode set to 401");
_options.Logger.Error("HttpStatusCode set to 401");
response = new ResponseMessage { StatusCode = 401 };
return;
}
@@ -130,7 +128,7 @@ namespace WireMock.Owin
}
catch (Exception ex)
{
Log.Error("HttpStatusCode set to 500", ex);
_options.Logger.Error("HttpStatusCode set to 500");
response = new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) };
}
finally

View File

@@ -15,13 +15,15 @@ namespace WireMock.Owin
{
internal class WireMockMiddlewareOptions
{
public IWireMockLogger Logger { get; set; }
public TimeSpan? RequestProcessingDelay { get; set; }
public IStringMatcher AuthorizationMatcher { get; set; }
public bool AllowPartialMapping { get; set; }
public IDictionary<Guid, Mapping> Mappings { get; set; } = new ConcurrentDictionary<Guid, Mapping>();
public IDictionary<Guid, Mapping> Mappings { get; } = new ConcurrentDictionary<Guid, Mapping>();
public ObservableCollection<LogEntry> LogEntries { get; } = new ConcurentObservableCollection<LogEntry>();

View File

@@ -7,7 +7,6 @@ using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Http;
using WireMock.Settings;
using WireMock.Transformers;

View File

@@ -113,7 +113,7 @@ namespace WireMock.Server
foreach (string filename in Directory.EnumerateFiles(folder).OrderBy(f => f))
{
Log.InfoFormat("Reading Static MappingFile : '{0}'", filename);
_logger.Info("Reading Static MappingFile : '{0}'", filename);
ReadStaticMappingAndAddOrUpdate(filename);
}
}
@@ -135,22 +135,22 @@ namespace WireMock.Server
return;
}
Log.InfoFormat("Watching folder '{0}' for new, updated and deleted MappingFiles.", folder);
_logger.Info("Watching folder '{0}' for new, updated and deleted MappingFiles.", folder);
var watcher = new EnhancedFileSystemWatcher(folder, "*.json", 1000);
watcher.Created += (sender, args) =>
{
Log.InfoFormat("New MappingFile created : '{0}'", args.FullPath);
_logger.Info("New MappingFile created : '{0}'", args.FullPath);
ReadStaticMappingAndAddOrUpdate(args.FullPath);
};
watcher.Changed += (sender, args) =>
{
Log.InfoFormat("New MappingFile updated : '{0}'", args.FullPath);
_logger.Info("New MappingFile updated : '{0}'", args.FullPath);
ReadStaticMappingAndAddOrUpdate(args.FullPath);
};
watcher.Deleted += (sender, args) =>
{
Log.InfoFormat("New MappingFile deleted : '{0}'", args.FullPath);
_logger.Info("New MappingFile deleted : '{0}'", args.FullPath);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(args.FullPath);
if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
@@ -288,7 +288,7 @@ namespace WireMock.Server
if (mapping == null)
{
Log.Warn("HttpStatusCode set to 404 : Mapping not found");
_logger.Warn("HttpStatusCode set to 404 : Mapping not found");
return new ResponseMessage { StatusCode = 404, Body = "Mapping not found" };
}
@@ -343,7 +343,7 @@ namespace WireMock.Server
string filename = !string.IsNullOrEmpty(mapping.Title) ? SanitizeFileName(mapping.Title) : mapping.Guid.ToString();
string filePath = Path.Combine(folder, filename + ".json");
Log.InfoFormat("Saving Mapping to file {0}", filePath);
_logger.Info("Saving Mapping to file {0}", filePath);
File.WriteAllText(filePath, JsonConvert.SerializeObject(model, _settings));
}
@@ -374,12 +374,12 @@ namespace WireMock.Server
}
catch (ArgumentException a)
{
Log.Error("HttpStatusCode set to 400", a);
_logger.Error("HttpStatusCode set to 400 {0}", a);
return new ResponseMessage { StatusCode = 400, Body = a.Message };
}
catch (Exception e)
{
Log.Error("HttpStatusCode set to 500", e);
_logger.Error("HttpStatusCode set to 500 {0}", e);
return new ResponseMessage { StatusCode = 500, Body = e.ToString() };
}
@@ -449,8 +449,8 @@ namespace WireMock.Server
if (entry == null)
{
Log.Warn("HttpStatusCode set to 404 : Request not found");
return new ResponseMessage {StatusCode = 404, Body = "Request not found"};
_logger.Warn("HttpStatusCode set to 404 : Request not found");
return new ResponseMessage { StatusCode = 404, Body = "Request not found" };
}
var model = ToLogEntryModel(entry);

View File

@@ -1,14 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using log4net;
using Newtonsoft.Json;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
@@ -23,7 +22,7 @@ namespace WireMock.Server
/// </summary>
public partial class FluentMockServer : IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(FluentMockServer));
private readonly IWireMockLogger _logger;
private const int ServerStartDelay = 100;
private readonly IOwinSelfHost _httpServer;
private readonly WireMockMiddlewareOptions _options = new WireMockMiddlewareOptions();
@@ -158,7 +157,10 @@ namespace WireMock.Server
private FluentMockServer(IFluentMockServerSettings settings)
{
Log.DebugFormat("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented));
settings.Logger = settings.Logger ?? new WireMockConsoleLogger();
_logger = settings.Logger;
_logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented));
if (settings.Urls != null)
{
@@ -172,6 +174,7 @@ namespace WireMock.Server
_options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
_options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
_options.Logger = _logger;
#if NETSTANDARD
_httpServer = new AspNetCoreSelfHost(_options, Urls);
@@ -318,7 +321,7 @@ namespace WireMock.Server
[PublicAPI]
public void AllowPartialMapping(bool allow = true)
{
Log.InfoFormat("AllowPartialMapping is set to {0}", allow);
_logger.Info("AllowPartialMapping is set to {0}", allow);
_options.AllowPartialMapping = allow;
}

View File

@@ -1,6 +1,7 @@
using System;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Logging;
namespace WireMock.Settings
{
@@ -71,5 +72,10 @@ namespace WireMock.Settings
[PublicAPI]
[JsonIgnore]
public Action<object> PostWireMockMiddlewareInit { get; set; }
/// <inheritdoc cref="IFluentMockServerSettings.Logger"/>
[PublicAPI]
[JsonIgnore]
public IWireMockLogger Logger { get; set; } = new WireMockNullLogger();
}
}

View File

@@ -1,4 +1,6 @@
using System;
using JetBrains.Annotations;
using WireMock.Logging;
namespace WireMock.Settings
{
@@ -10,77 +12,98 @@ namespace WireMock.Settings
/// <summary>
/// Gets or sets the port.
/// </summary>
[PublicAPI]
int? Port { get; set; }
/// <summary>
/// Gets or sets the use SSL.
/// </summary>
// ReSharper disable once InconsistentNaming
[PublicAPI]
bool? UseSSL { get; set; }
/// <summary>
/// Gets or sets wether to start admin interface.
/// </summary>
[PublicAPI]
bool? StartAdminInterface { get; set; }
/// <summary>
/// Gets or sets if the static mappings should be read at startup.
/// </summary>
[PublicAPI]
bool? ReadStaticMappings { get; set; }
/// <summary>
/// Watch the static mapping files + folder for changes when running.
/// </summary>
[PublicAPI]
bool? WatchStaticMappings { get; set; }
/// <summary>
/// Gets or sets if the proxy and record settings.
/// </summary>
[PublicAPI]
IProxyAndRecordSettings ProxyAndRecordSettings { get; set; }
/// <summary>
/// Gets or sets the urls.
/// </summary>
[PublicAPI]
string[] Urls { get; set; }
/// <summary>
/// StartTimeout
/// </summary>
[PublicAPI]
int StartTimeout { get; set; }
/// <summary>
/// Allow Partial Mapping (default set to false).
/// </summary>
[PublicAPI]
bool? AllowPartialMapping { get; set; }
/// <summary>
/// The username needed for __admin access.
/// </summary>
[PublicAPI]
string AdminUsername { get; set; }
/// <summary>
/// The password needed for __admin access.
/// </summary>
[PublicAPI]
string AdminPassword { get; set; }
/// <summary>
/// The RequestLog expiration in hours (optional).
/// </summary>
[PublicAPI]
int? RequestLogExpirationDuration { get; set; }
/// <summary>
/// The MaxRequestLog count (optional).
/// </summary>
[PublicAPI]
int? MaxRequestLogCount { get; set; }
/// <summary>
/// Action which is called (with the IAppBuilder or IApplicationBuilder) before the internal WireMockMiddleware is initialized. [Optional]
/// </summary>
[PublicAPI]
Action<object> PreWireMockMiddlewareInit { get; set; }
/// <summary>
/// Action which is called (with the IAppBuilder or IApplicationBuilder) after the internal WireMockMiddleware is initialized. [Optional]
/// </summary>
[PublicAPI]
Action<object> PostWireMockMiddlewareInit { get; set; }
/// <summary>
/// The IWireMockLogger which logs Debug, Info, Warning or Error
/// </summary>
[PublicAPI]
IWireMockLogger Logger { get; set; }
}
}

View File

@@ -45,7 +45,6 @@
<PackageReference Include="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="System.Net.Http" Version="4.3.3" />
<PackageReference Include="RestEase" Version="1.4.4" />
<PackageReference Include="log4net" Version="2.0.8" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">