{
return;
}
+
string message = string.Empty;
+
if (formatter != null)
{
message = formatter(state, exception);
}
- else
+ else if (state != null)
+ {
+ message += state;
+ }
+
+ if (exception != null)
{
- if (state != null)
- {
- message += state;
- }
- if (exception != null)
- {
- message += Environment.NewLine + exception;
- }
+ string exceptionDelimiter = string.IsNullOrEmpty(message) ? string.Empty : " " ;
+ message += exceptionDelimiter + exception;
}
+
if (!string.IsNullOrEmpty(message))
{
_traceSource.TraceEvent(GetEventType(logLevel), eventId.Id, message);
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System;
using System.Diagnostics;
+using Moq;
+
using Xunit;
namespace Microsoft.Extensions.Logging.Test
secondSwitch.Level = second;
// Act
-
var factory = TestLoggerBuilder.Create(builder => builder
.AddTraceSource(firstSwitch)
.AddTraceSource(secondSwitch));
// Assert
Assert.Equal(expected, logger.IsEnabled(LogLevel.Information));
}
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public static void Log_Shoud_Add_Exception_To_Message_Whether_Formatter_Is_Null_Or_Not(bool shouldFormatterBeNull)
+ {
+ // Arrange
+ Mock<TraceListener> traceListener = new Mock<TraceListener>();
+ SourceSwitch sourceSwitch = new SourceSwitch("TestSwitch") {Level = SourceLevels.All};
+
+ ILoggerFactory factory = TestLoggerBuilder.Create(builder => builder.AddTraceSource(sourceSwitch, traceListener.Object));
+ ILogger logger = factory.CreateLogger("Test");
+
+ const LogLevel logLevel = LogLevel.Information;
+ EventId eventId = new EventId(1);
+ const string message = "some log message";
+ Exception exception = new Exception("Some error occurred");
+ Func<string, Exception, string> formatter = shouldFormatterBeNull ? (Func<string, Exception, string>)null : (value, passedException) => value;
+
+ string expectedMessage = $"{message} {exception}";
+
+ // Act
+ logger.Log(logLevel, eventId, message, exception, formatter);
+
+ // Assert
+ traceListener.Verify(listener => listener.TraceEvent(It.IsAny<TraceEventCache>(), It.IsAny<string>(), It.IsAny<TraceEventType>(), It.IsAny<int>(), expectedMessage), Times.Once);
+ }
}
}