1
- // Copyright (c) .NET Foundation. All rights reserved.
1
+ // Copyright (c) .NET Foundation. All rights reserved.
2
2
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
3
4
4
using System ;
5
5
using System . Collections . Concurrent ;
6
6
using System . Collections . Generic ;
7
7
using System . Linq ;
8
+ using System . Threading . Tasks ;
8
9
using Microsoft . AspNetCore . Server . Kestrel . Core . Internal ;
9
10
using Microsoft . AspNetCore . Server . Kestrel . Core . Internal . Infrastructure ;
10
11
using Microsoft . Extensions . Logging ;
@@ -16,6 +17,9 @@ public class TestApplicationErrorLogger : ILogger
16
17
// Application errors are logged using 13 as the eventId.
17
18
private const int ApplicationErrorEventId = 13 ;
18
19
20
+ private Func < LogMessage , bool > _messageFilter ;
21
+ private TaskCompletionSource < LogMessage > _messageFilterTcs ;
22
+
19
23
public List < Type > IgnoredExceptions { get ; } = new List < Type > ( ) ;
20
24
21
25
public bool ThrowOnCriticalErrors { get ; set ; } = true ;
@@ -32,6 +36,19 @@ public class TestApplicationErrorLogger : ILogger
32
36
33
37
public int ApplicationErrorsLogged => Messages . Count ( message => message . EventId . Id == ApplicationErrorEventId ) ;
34
38
39
+ public Task < LogMessage > WaitForMessage ( Func < LogMessage , bool > messageFilter )
40
+ {
41
+ if ( _messageFilterTcs != null )
42
+ {
43
+ throw new InvalidOperationException ( $ "{ nameof ( WaitForMessage ) } cannot be called concurrently.") ;
44
+ }
45
+
46
+ _messageFilterTcs = new TaskCompletionSource < LogMessage > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
47
+ _messageFilter = messageFilter ;
48
+
49
+ return _messageFilterTcs . Task ;
50
+ }
51
+
35
52
public IDisposable BeginScope < TState > ( TState state )
36
53
{
37
54
Scopes . Enqueue ( state ) ;
@@ -77,13 +94,21 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
77
94
throw new Exception ( $ "Unexpected connection error. { log } ") ;
78
95
}
79
96
80
- Messages . Enqueue ( new LogMessage
97
+ var logMessage = new LogMessage
81
98
{
82
99
LogLevel = logLevel ,
83
100
EventId = eventId ,
84
101
Exception = exception ,
85
102
Message = formatter ( state , exception )
86
- } ) ;
103
+ } ;
104
+
105
+ Messages . Enqueue ( logMessage ) ;
106
+
107
+ if ( _messageFilter ? . Invoke ( logMessage ) == true )
108
+ {
109
+ _messageFilterTcs . TrySetResult ( logMessage ) ;
110
+ _messageFilterTcs = null ;
111
+ }
87
112
}
88
113
89
114
public class LogMessage
0 commit comments