using System; using Newtonsoft.Json; using WireMock.Admin.Requests; namespace WireMock.Logging; /// /// WireMockConsoleLogger which logs to Console /// /// public class WireMockConsoleLogger : IWireMockLogger { private const string NewlineWindows = "\r\n"; private const string NewlineUnix = "\n"; private readonly bool _removeNewLines; /// /// Initializes a new instance of the class. /// public WireMockConsoleLogger(bool removeNewLines = false) { _removeNewLines = removeNewLines; Console.OutputEncoding = System.Text.Encoding.UTF8; } /// public void Debug(string formatString, params object[] args) { WriteLine(Format("Debug", formatString, args)); } /// public void Info(string formatString, params object[] args) { WriteLine(Format("Info", formatString, args)); } /// public void Warn(string formatString, params object[] args) { WriteLine(Format("Warn", formatString, args)); } /// public void Error(string formatString, params object[] args) { WriteLine(Format("Error", formatString, args)); } /// public void Error(string formatString, Exception exception) { WriteLine(Format("Error", formatString, exception.Message)); if (exception is AggregateException ae) { ae.Handle(ex => { WriteLine(Format("Error", "Exception {0}", ex.Message)); return true; }); } } /// public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) { string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented); 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}"; } /// /// Writes the specified string value, followed by the current line terminator, to the console. /// /// The value to write. private void WriteLine(string value) { Console.WriteLine(!_removeNewLines ? value : value.Replace(NewlineWindows, string.Empty).Replace(NewlineUnix, string.Empty)); } }