Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Issue-849 Add ability to provide method to override WriteMessage #850

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/Shared/XUnitLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ public partial class XUnitLogger : ILogger
/// </summary>
private readonly string _timestampFormat;

/// <summary>
/// Gets or sets an optional method to override the writing of log messages.
/// </summary>
private readonly Action<XUnitLogger, ITestOutputHelper?, IMessageSink?, LogLevel, int, string?, Exception?>? _writeMessageOverride;

/// <summary>
/// Gets or sets the filter to use.
/// </summary>
Expand All @@ -57,6 +62,7 @@ private XUnitLogger(string name, XUnitLoggerOptions? options)
_messageSinkMessageFactory = options?.MessageSinkMessageFactory ?? (static (message) => new DiagnosticMessage(message));
_timestampFormat = options?.TimestampFormat ?? "u";
IncludeScopes = options?.IncludeScopes ?? false;
_writeMessageOverride = options?.WriteMessageOverride;
}

/// <summary>
Expand Down Expand Up @@ -134,7 +140,21 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except

if (!string.IsNullOrEmpty(message) || exception != null)
{
WriteMessage(logLevel, eventId.Id, message, exception);
if (_writeMessageOverride != null)
{
_writeMessageOverride(
this,
_outputHelperAccessor?.OutputHelper,
_messageSinkAccessor?.MessageSink,
logLevel,
eventId.Id,
message,
exception);
}
else
{
WriteMessage(logLevel, eventId.Id, message, exception);
}
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/Shared/XUnitLoggerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,9 @@ public XUnitLoggerOptions()
/// </summary>
[StringSyntax(StringSyntaxAttribute.DateTimeFormat)]
public string? TimestampFormat { get; set; }

/// <summary>
/// Gets or sets an optional method to override the writing of log messages.
/// </summary>
public Action<XUnitLogger, ITestOutputHelper?, IMessageSink?, LogLevel, int, string?, Exception?>? WriteMessageOverride { get; set; }
}
121 changes: 121 additions & 0 deletions tests/Shared/XUnitLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ public static void XUnitLogger_Log_Does_Nothing_If_No_OutputHelper()
// Arrange
string name = "MyName";
var accessor = Substitute.For<ITestOutputHelperAccessor>();
accessor.OutputHelper.Returns(default(ITestOutputHelper));

var options = new XUnitLoggerOptions()
{
Expand Down Expand Up @@ -659,6 +660,122 @@ public static void XUnitLogger_Log_Logs_Message_If_Scopes_Included_And_There_Is_
outputHelper.Received(1).WriteLine(expected);
}

[Fact]
public static void XUnitLogger_Log_Emits_Output_Helper_Message_If_Override_Method_Provided()
{
// Arrange
var outputHelper = Substitute.For<ITestOutputHelper>();
string name = "MyName";
LogLevel inputLogLevel = LogLevel.Information;
int inputEventId = 1;
string? inputMessage = "log message";

string expectedOutput = $"[{inputLogLevel}] {name} {inputEventId} {inputMessage}";

static void WriteMessageOverride(XUnitLogger xUnitLogger, ITestOutputHelper? helper, IMessageSink? sink, LogLevel level, int eventId, string? message, Exception? exception)
{
string formattedMessage = $"[{level}] {xUnitLogger.Name} {eventId} {message}";
helper?.WriteLine(formattedMessage);
}

var options = new XUnitLoggerOptions()
{
Filter = FilterTrue,
WriteMessageOverride = WriteMessageOverride,
};

var logger = new XUnitLogger(name, outputHelper, options);

logger.Log(inputLogLevel, inputEventId, inputMessage, null, FormatterStateAsString);

// Assert
outputHelper.Received(1).WriteLine(expectedOutput);
}

[Fact]
public static void XUnitLogger_Log_Emits_Message_Sink_Message_If_Override_Method_Provided()
{
// Arrange
var messageSink = Substitute.For<IMessageSink>();
string name = "MyName";
LogLevel inputLogLevel = LogLevel.Information;
int inputEventId = 1;
string? inputMessage = "message";

string expectedOutput = $"[{inputLogLevel}] {name} {inputEventId} {inputMessage}";

static void WriteMessageOverride(XUnitLogger xUnitLogger, ITestOutputHelper? helper, IMessageSink? sink, LogLevel level, int eventId, string? message, Exception? exception)
{
string formattedMessage = $"[{level}] {xUnitLogger.Name} {eventId} {message}";
sink?.OnMessage(new DiagnosticMessage(formattedMessage));
}

var options = new XUnitLoggerOptions()
{
Filter = FilterTrue,
WriteMessageOverride = WriteMessageOverride,
};

var logger = new XUnitLogger(name, messageSink, options);

logger.Log(inputLogLevel, inputEventId, inputMessage, null, FormatterStateAsString);

// Assert
messageSink.Received(1).OnMessage(Arg.Is<IDiagnosticMessage>(message => string.Equals(message.Message, expectedOutput, StringComparison.Ordinal)));
}

[Fact]
public static void XUnitLogger_Does_Nothing_If_Noop_Override_Method_Provided()
{
// Arrange
var outputHelper = Substitute.For<ITestOutputHelper>();

static void WriteMessageOverride(XUnitLogger xUnitLogger, ITestOutputHelper? helper, IMessageSink? sink, LogLevel level, int eventId, string? message, Exception? exception)
{
}

var options = new XUnitLoggerOptions()
{
WriteMessageOverride = WriteMessageOverride,
};

var logger = new XUnitLogger("MyName", outputHelper, options);

logger.Log(LogLevel.Information, 1, string.Empty, null, FormatterStateAsString);

// Assert
outputHelper.DidNotReceiveWithAnyArgs().WriteLine(string.Empty);
}

[Fact]
public static void XUnitLogger_Logs_Message_If_Null_Override_Message_Provided()
{
// Arrange
var outputHelper = Substitute.For<ITestOutputHelper>();
string name = "MyName";

var options = new XUnitLoggerOptions()
{
WriteMessageOverride = null,
};

string expected = string.Join(
Environment.NewLine,
$"[2018-08-19 16:12:16Z] info: MyName[1]",
" state");

var logger = new XUnitLogger(name, outputHelper, options)
{
Clock = StaticClock,
};

// Act
logger.Log(LogLevel.Information, 1, "state", null, FormatterStateAsString);

// Assert
outputHelper.Received(1).WriteLine(Arg.Is<string>(expected));
}

private static DateTimeOffset StaticClock() => new(2018, 08, 19, 17, 12, 16, TimeSpan.FromHours(1));

private static DiagnosticMessage DiagnosticMessageFactory(string message) => new(message);
Expand All @@ -678,4 +795,8 @@ private static string Formatter<TState>(TState? state, Exception? exception)
private static string FormatterLong<TState>(TState? state, Exception? exception) => new('a', 2048);

private static string FormatterNull<TState>(TState? state, Exception? exception) => null!;

#pragma warning disable IDE0060 // Remove unused parameter
private static string FormatterStateAsString<TState>(TState? state, Exception? exception) => state?.ToString() ?? string.Empty;
#pragma warning restore IDE0060 // Remove unused parameter
}