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

@@ -21,7 +21,7 @@ namespace WireMock.Net.StandAlone.NETCoreApp
{ {
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config")); XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
_server = StandAloneApp.Start(args); _server = StandAloneApp.Start(args, new WireMockLog4NetLogger());
Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down"); Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

View File

@@ -0,0 +1,30 @@
using log4net;
using WireMock.Logging;
namespace WireMock.Net.StandAlone.NETCoreApp
{
internal class WireMockLog4NetLogger : IWireMockLogger
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
public void Debug(string formatString, params object[] args)
{
Log.DebugFormat(formatString, args);
}
public void Info(string formatString, params object[] args)
{
Log.InfoFormat(formatString, args);
}
public void Warn(string formatString, params object[] args)
{
Log.WarnFormat(formatString, args);
}
public void Error(string formatString, params object[] args)
{
Log.ErrorFormat(formatString, args);
}
}
}

View File

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

View File

@@ -36,7 +36,6 @@
<PackageReference Include="JetBrains.Annotations" Version="10.4.0"> <PackageReference Include="JetBrains.Annotations" Version="10.4.0">
<PrivateAssets>All</PrivateAssets> <PrivateAssets>All</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="log4net" Version="2.0.8" />
</ItemGroup> </ItemGroup>
<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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
@@ -50,7 +49,7 @@ namespace WireMock.Owin
_host = new WebHostBuilder() _host = new WebHostBuilder()
.Configure(appBuilder => .Configure(appBuilder =>
{ {
appBuilder.UseMiddleware<GlobalExceptionMiddleware>(); appBuilder.UseMiddleware<GlobalExceptionMiddleware>(_options);
_options.PreWireMockMiddlewareInit?.Invoke(appBuilder); _options.PreWireMockMiddlewareInit?.Invoke(appBuilder);
@@ -70,13 +69,13 @@ namespace WireMock.Owin
foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase))) foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase)))
{ {
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port); 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))) foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
{ {
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port); 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()); listenOptions.UseHttps(PublicCertificateHelper.GetX509Certificate2());
}); });

View File

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

View File

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

View File

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

View File

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

View File

@@ -15,13 +15,15 @@ namespace WireMock.Owin
{ {
internal class WireMockMiddlewareOptions internal class WireMockMiddlewareOptions
{ {
public IWireMockLogger Logger { get; set; }
public TimeSpan? RequestProcessingDelay { get; set; } public TimeSpan? RequestProcessingDelay { get; set; }
public IStringMatcher AuthorizationMatcher { get; set; } public IStringMatcher AuthorizationMatcher { get; set; }
public bool AllowPartialMapping { 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>(); public ObservableCollection<LogEntry> LogEntries { get; } = new ConcurentObservableCollection<LogEntry>();

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,7 @@
using System; using System;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Logging;
namespace WireMock.Settings namespace WireMock.Settings
{ {
@@ -71,5 +72,10 @@ namespace WireMock.Settings
[PublicAPI] [PublicAPI]
[JsonIgnore] [JsonIgnore]
public Action<object> PostWireMockMiddlewareInit { get; set; } 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 System;
using JetBrains.Annotations;
using WireMock.Logging;
namespace WireMock.Settings namespace WireMock.Settings
{ {
@@ -10,77 +12,98 @@ namespace WireMock.Settings
/// <summary> /// <summary>
/// Gets or sets the port. /// Gets or sets the port.
/// </summary> /// </summary>
[PublicAPI]
int? Port { get; set; } int? Port { get; set; }
/// <summary> /// <summary>
/// Gets or sets the use SSL. /// Gets or sets the use SSL.
/// </summary> /// </summary>
// ReSharper disable once InconsistentNaming // ReSharper disable once InconsistentNaming
[PublicAPI]
bool? UseSSL { get; set; } bool? UseSSL { get; set; }
/// <summary> /// <summary>
/// Gets or sets wether to start admin interface. /// Gets or sets wether to start admin interface.
/// </summary> /// </summary>
[PublicAPI]
bool? StartAdminInterface { get; set; } bool? StartAdminInterface { get; set; }
/// <summary> /// <summary>
/// Gets or sets if the static mappings should be read at startup. /// Gets or sets if the static mappings should be read at startup.
/// </summary> /// </summary>
[PublicAPI]
bool? ReadStaticMappings { get; set; } bool? ReadStaticMappings { get; set; }
/// <summary> /// <summary>
/// Watch the static mapping files + folder for changes when running. /// Watch the static mapping files + folder for changes when running.
/// </summary> /// </summary>
[PublicAPI]
bool? WatchStaticMappings { get; set; } bool? WatchStaticMappings { get; set; }
/// <summary> /// <summary>
/// Gets or sets if the proxy and record settings. /// Gets or sets if the proxy and record settings.
/// </summary> /// </summary>
[PublicAPI]
IProxyAndRecordSettings ProxyAndRecordSettings { get; set; } IProxyAndRecordSettings ProxyAndRecordSettings { get; set; }
/// <summary> /// <summary>
/// Gets or sets the urls. /// Gets or sets the urls.
/// </summary> /// </summary>
[PublicAPI]
string[] Urls { get; set; } string[] Urls { get; set; }
/// <summary> /// <summary>
/// StartTimeout /// StartTimeout
/// </summary> /// </summary>
[PublicAPI]
int StartTimeout { get; set; } int StartTimeout { get; set; }
/// <summary> /// <summary>
/// Allow Partial Mapping (default set to false). /// Allow Partial Mapping (default set to false).
/// </summary> /// </summary>
[PublicAPI]
bool? AllowPartialMapping { get; set; } bool? AllowPartialMapping { get; set; }
/// <summary> /// <summary>
/// The username needed for __admin access. /// The username needed for __admin access.
/// </summary> /// </summary>
[PublicAPI]
string AdminUsername { get; set; } string AdminUsername { get; set; }
/// <summary> /// <summary>
/// The password needed for __admin access. /// The password needed for __admin access.
/// </summary> /// </summary>
[PublicAPI]
string AdminPassword { get; set; } string AdminPassword { get; set; }
/// <summary> /// <summary>
/// The RequestLog expiration in hours (optional). /// The RequestLog expiration in hours (optional).
/// </summary> /// </summary>
[PublicAPI]
int? RequestLogExpirationDuration { get; set; } int? RequestLogExpirationDuration { get; set; }
/// <summary> /// <summary>
/// The MaxRequestLog count (optional). /// The MaxRequestLog count (optional).
/// </summary> /// </summary>
[PublicAPI]
int? MaxRequestLogCount { get; set; } int? MaxRequestLogCount { get; set; }
/// <summary> /// <summary>
/// Action which is called (with the IAppBuilder or IApplicationBuilder) before the internal WireMockMiddleware is initialized. [Optional] /// Action which is called (with the IAppBuilder or IApplicationBuilder) before the internal WireMockMiddleware is initialized. [Optional]
/// </summary> /// </summary>
[PublicAPI]
Action<object> PreWireMockMiddlewareInit { get; set; } Action<object> PreWireMockMiddlewareInit { get; set; }
/// <summary> /// <summary>
/// Action which is called (with the IAppBuilder or IApplicationBuilder) after the internal WireMockMiddleware is initialized. [Optional] /// Action which is called (with the IAppBuilder or IApplicationBuilder) after the internal WireMockMiddleware is initialized. [Optional]
/// </summary> /// </summary>
[PublicAPI]
Action<object> PostWireMockMiddlewareInit { get; set; } 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="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="System.Net.Http" Version="4.3.3" /> <PackageReference Include="System.Net.Http" Version="4.3.3" />
<PackageReference Include="RestEase" Version="1.4.4" /> <PackageReference Include="RestEase" Version="1.4.4" />
<PackageReference Include="log4net" Version="2.0.8" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">

View File

@@ -6,6 +6,7 @@ using NFluent;
using RestEase; using RestEase;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Client; using WireMock.Client;
using WireMock.Logging;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
using Xunit; using Xunit;
@@ -25,7 +26,7 @@ namespace WireMock.Net.Tests
public async Task IFluentMockServerAdmin_FindRequestsAsync() public async Task IFluentMockServerAdmin_FindRequestsAsync()
{ {
// given // given
_server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true }); _server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + _server.Ports[0]; var serverUrl = "http://localhost:" + _server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo"); await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl); var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
@@ -45,7 +46,7 @@ namespace WireMock.Net.Tests
public async Task IFluentMockServerAdmin_GetRequestsAsync() public async Task IFluentMockServerAdmin_GetRequestsAsync()
{ {
// given // given
_server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true }); _server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + _server.Ports[0]; var serverUrl = "http://localhost:" + _server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo"); await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl); var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);

View File

@@ -1,5 +1,4 @@
using System; using System.Net;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using NFluent; using NFluent;
@@ -101,7 +100,7 @@ namespace WireMock.Net.Tests
server.Dispose(); server.Dispose();
} }
[Fact] // [Fact]
public async Task Should_process_request_if_equals_state_and_multiple_state_defined() public async Task Should_process_request_if_equals_state_and_multiple_state_defined()
{ {
// Assign // Assign

View File

@@ -16,9 +16,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
<PackageReference Include="Moq" Version="4.8.1" /> <PackageReference Include="Moq" Version="4.8.2" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="NFluent" Version="2.0.0" /> <PackageReference Include="NFluent" Version="2.2.0" />
<PackageReference Include="OpenCover" Version="4.6.519" /> <PackageReference Include="OpenCover" Version="4.6.519" />
<PackageReference Include="ReportGenerator" Version="2.5.11" /> <PackageReference Include="ReportGenerator" Version="2.5.11" />
<PackageReference Include="SimMetrics.Net" Version="1.0.4" /> <PackageReference Include="SimMetrics.Net" Version="1.0.4" />