Skip to content

Commit 2ca0b93

Browse files
Validate input string passed to LogValuesFormatter (#43238)
Add validation of a format string passed to LogValuesFormatter to throw `ArgumentNullException` if the string is `null` so that all the methods of the `LogMessage.Define` group depending on that class doesn't throw `NullReferenceException` when configuring a logger. Fix #36565
1 parent 7ca6d85 commit 2ca0b93

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ internal class LogValuesFormatter
2222

2323
public LogValuesFormatter(string format)
2424
{
25+
if (format == null)
26+
{
27+
throw new ArgumentNullException(nameof(format));
28+
}
29+
2530
OriginalFormat = format;
2631

2732
var sb = new StringBuilder();

src/libraries/Microsoft.Extensions.Logging/tests/Common/LoggerMessageTest.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,26 @@ public void DefineScope_ThrowsException_WhenExpectedFormatStringParameterCount_N
322322
Assert.Equal(expectedMessage, exception.Message);
323323
}
324324

325+
[Theory]
326+
[MemberData(nameof(DefineMethodsData))]
327+
public void DefineMessage_ThrowsException_WhenFormatString_IsNull(Func<LogLevel, EventId, string, Delegate> define)
328+
{
329+
// Act
330+
var exception = Assert.Throws<ArgumentNullException>(
331+
() => define.Invoke(LogLevel.Error, 0, null));
332+
}
333+
334+
public static IEnumerable<object[]> DefineMethodsData => new[]
335+
{
336+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define },
337+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string> },
338+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string, string> },
339+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string, string, string> },
340+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string, string, string, string> },
341+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string, string, string, string, string> },
342+
new object[] { (Func<LogLevel, EventId, string, Delegate>)LoggerMessage.Define<string, string, string, string, string, string> }
343+
};
344+
325345
public static IEnumerable<object[]> LogMessagesData => new[]
326346
{
327347
new object[] { LoggerMessage.Define(LogLevel.Error, 0, "Log "), 0 },

0 commit comments

Comments
 (0)