1+ // Copyright © WireMock.Net
2+
3+ using System ;
4+ using Newtonsoft . Json ;
5+ using Stef . Validation ;
6+ using WireMock . Admin . Requests ;
7+ using WireMock . Logging ;
8+ using Xunit ;
9+
10+ namespace WireMock . Net . Xunit ;
11+
12+ /// <summary>
13+ /// When using xUnit, this class enables to log the output from WireMock.Net to the <see cref="ITestOutputHelper"/>.
14+ /// </summary>
15+ public sealed class TestOutputHelperWireMockLogger : IWireMockLogger
16+ {
17+ private readonly ITestOutputHelper _testOutputHelper ;
18+
19+ /// <summary>
20+ /// Create a new instance on the <see cref="TestOutputHelperWireMockLogger"/>.
21+ /// </summary>
22+ /// <param name="testOutputHelper">Represents a class which can be used to provide test output.</param>
23+ public TestOutputHelperWireMockLogger ( ITestOutputHelper testOutputHelper )
24+ {
25+ _testOutputHelper = Guard . NotNull ( testOutputHelper ) ;
26+ }
27+
28+ /// <inheritdoc />
29+ public void Debug ( string formatString , params object [ ] args )
30+ {
31+ _testOutputHelper . WriteLine ( Format ( "Debug" , formatString , args ) ) ;
32+ }
33+
34+ /// <inheritdoc />
35+ public void Info ( string formatString , params object [ ] args )
36+ {
37+ _testOutputHelper . WriteLine ( Format ( "Info" , formatString , args ) ) ;
38+ }
39+
40+ /// <inheritdoc />
41+ public void Warn ( string formatString , params object [ ] args )
42+ {
43+ _testOutputHelper . WriteLine ( Format ( "Warning" , formatString , args ) ) ;
44+ }
45+
46+ /// <inheritdoc />
47+ public void Error ( string formatString , params object [ ] args )
48+ {
49+ _testOutputHelper . WriteLine ( Format ( "Error" , formatString , args ) ) ;
50+ }
51+
52+ /// <inheritdoc />
53+ public void Error ( string message , Exception exception )
54+ {
55+ _testOutputHelper . WriteLine ( Format ( "Error" , $ "{ message } {{0}}", exception ) ) ;
56+
57+ if ( exception is AggregateException ae )
58+ {
59+ ae . Handle ( ex =>
60+ {
61+ _testOutputHelper . WriteLine ( Format ( "Error" , "Exception {0}" , ex ) ) ;
62+ return true ;
63+ } ) ;
64+ }
65+ }
66+
67+ /// <inheritdoc />
68+ public void DebugRequestResponse ( LogEntryModel logEntryModel , bool isAdminRequest )
69+ {
70+ var message = JsonConvert . SerializeObject ( logEntryModel , Formatting . Indented ) ;
71+ _testOutputHelper . WriteLine ( Format ( "DebugRequestResponse" , "Admin[{0}] {1}" , isAdminRequest , message ) ) ;
72+ }
73+
74+ private static string Format ( string level , string formatString , params object [ ] args )
75+ {
76+ var message = args . Length > 0 ? string . Format ( formatString , args ) : formatString ;
77+ return $ "{ DateTime . UtcNow } [{ level } ] : { message } ";
78+ }
79+ }
0 commit comments