@@ -8,11 +8,12 @@ namespace TestBuildingBlocks;
88// Based on https://www.meziantou.net/how-to-get-asp-net-core-logs-in-the-output-of-xunit-tests.htm.
99public sealed class XUnitLoggerProvider : ILoggerProvider
1010{
11+ private const LogOutputFields DefaultLogOutputFields = LogOutputFields . All & ~ LogOutputFields . CategoryNamespace ;
1112 private readonly ITestOutputHelper _testOutputHelper ;
1213 private readonly LogOutputFields _outputFields ;
1314 private readonly string ? _categoryPrefixFilter ;
1415
15- public XUnitLoggerProvider ( ITestOutputHelper testOutputHelper , string ? categoryPrefixFilter , LogOutputFields outputFields = LogOutputFields . All )
16+ public XUnitLoggerProvider ( ITestOutputHelper testOutputHelper , string ? categoryPrefixFilter , LogOutputFields outputFields = DefaultLogOutputFields )
1617 {
1718 ArgumentNullException . ThrowIfNull ( testOutputHelper ) ;
1819
@@ -41,7 +42,34 @@ private sealed class XUnitLogger(ITestOutputHelper testOutputHelper, LogOutputFi
4142 {
4243 private readonly ITestOutputHelper _testOutputHelper = testOutputHelper ;
4344 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+ }
4573
4674 public bool IsEnabled ( LogLevel logLevel )
4775 {
@@ -68,15 +96,15 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
6896 builder . Append ( logLevelString ) ;
6997 }
7098
71- if ( _outputFields . HasFlag ( LogOutputFields . Category ) )
99+ if ( _categoryText != null )
72100 {
73101 if ( builder . Length > 0 )
74102 {
75103 builder . Append ( ' ' ) ;
76104 }
77105
78106 builder . Append ( '[' ) ;
79- builder . Append ( _categoryName ) ;
107+ builder . Append ( _categoryText ) ;
80108 builder . Append ( ']' ) ;
81109 }
82110
0 commit comments