@@ -8,11 +8,12 @@ namespace TestBuildingBlocks;
8
8
// Based on https://www.meziantou.net/how-to-get-asp-net-core-logs-in-the-output-of-xunit-tests.htm.
9
9
public sealed class XUnitLoggerProvider : ILoggerProvider
10
10
{
11
+ private const LogOutputFields DefaultLogOutputFields = LogOutputFields . All & ~ LogOutputFields . CategoryNamespace ;
11
12
private readonly ITestOutputHelper _testOutputHelper ;
12
13
private readonly LogOutputFields _outputFields ;
13
14
private readonly string ? _categoryPrefixFilter ;
14
15
15
- public XUnitLoggerProvider ( ITestOutputHelper testOutputHelper , string ? categoryPrefixFilter , LogOutputFields outputFields = LogOutputFields . All )
16
+ public XUnitLoggerProvider ( ITestOutputHelper testOutputHelper , string ? categoryPrefixFilter , LogOutputFields outputFields = DefaultLogOutputFields )
16
17
{
17
18
ArgumentNullException . ThrowIfNull ( testOutputHelper ) ;
18
19
@@ -41,7 +42,34 @@ private sealed class XUnitLogger(ITestOutputHelper testOutputHelper, LogOutputFi
41
42
{
42
43
private readonly ITestOutputHelper _testOutputHelper = testOutputHelper ;
43
44
private readonly LogOutputFields _outputFields = outputFields ;
44
- private readonly string _categoryName = categoryName ;
45
+ private readonly string ? _categoryText = GetCategoryText ( categoryName , outputFields ) ;
46
+
47
+ private static string ? GetCategoryText ( string categoryName , LogOutputFields outputFields )
48
+ {
49
+ if ( outputFields . HasFlag ( LogOutputFields . Category ) )
50
+ {
51
+ return categoryName ;
52
+ }
53
+
54
+ bool hasName = outputFields . HasFlag ( LogOutputFields . CategoryName ) ;
55
+ bool hasNamespace = outputFields . HasFlag ( LogOutputFields . CategoryNamespace ) ;
56
+
57
+ if ( hasName || hasNamespace )
58
+ {
59
+ // Microsoft.Extensions.Logging.LoggerFactory.CreateLogger(Type) removes generic type parameters
60
+ // and replaces '+' (nested class) with '.'.
61
+ int lastDotIndex = categoryName . LastIndexOf ( '.' ) ;
62
+
63
+ if ( lastDotIndex == - 1 )
64
+ {
65
+ return hasName ? categoryName : string . Empty ;
66
+ }
67
+
68
+ return hasName ? categoryName [ ( lastDotIndex + 1 ) ..] : categoryName [ ..lastDotIndex ] ;
69
+ }
70
+
71
+ return null ;
72
+ }
45
73
46
74
public bool IsEnabled ( LogLevel logLevel )
47
75
{
@@ -68,15 +96,15 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
68
96
builder . Append ( logLevelString ) ;
69
97
}
70
98
71
- if ( _outputFields . HasFlag ( LogOutputFields . Category ) )
99
+ if ( _categoryText != null )
72
100
{
73
101
if ( builder . Length > 0 )
74
102
{
75
103
builder . Append ( ' ' ) ;
76
104
}
77
105
78
106
builder . Append ( '[' ) ;
79
- builder . Append ( _categoryName ) ;
107
+ builder . Append ( _categoryText ) ;
80
108
builder . Append ( ']' ) ;
81
109
}
82
110
0 commit comments