11using System ;
2- using System . Diagnostics ;
32using System . Net ;
43using System . Threading . Tasks ;
54using Serilog ;
65using Serilog . Context ;
76using Serilog . Events ;
7+ using SerilogTracing ;
8+ using SerilogTracing . Instrumentation ;
89
910namespace Roastery . Web ;
1011
@@ -22,15 +23,16 @@ public RequestLoggingMiddleware(ILogger logger, HttpServer next)
2223 public override async Task < HttpResponse > InvokeAsync ( HttpRequest request )
2324 {
2425 using var _ = LogContext . PushProperty ( "RequestId" , request . RequestId ) ;
25-
26- var sw = Stopwatch . StartNew ( ) ;
26+
27+ using var activity = _logger . StartActivity ( "HTTP {RequestMethod} {RequestPath}" , request . Method , request . Path ) ;
28+
2729 try
2830 {
2931 var response = await _next . InvokeAsync ( request ) ;
30- LogCompletion ( null , request , sw , response . StatusCode ) ;
32+ LogCompletion ( activity , null , response . StatusCode ) ;
3133 return response ;
3234 }
33- catch ( Exception ex1 ) when ( LogCompletion ( ex1 , request , sw , HttpStatusCode . InternalServerError ) )
35+ catch ( Exception ex1 ) when ( LogCompletion ( activity , ex1 , HttpStatusCode . InternalServerError ) )
3436 {
3537 // We never hit this, because the exception filter always returns false.
3638 throw ;
@@ -41,12 +43,25 @@ public override async Task<HttpResponse> InvokeAsync(HttpRequest request)
4143 }
4244 }
4345
44- bool LogCompletion ( Exception ? exception , HttpRequest request , Stopwatch sw , HttpStatusCode statusCode )
46+ bool LogCompletion ( LoggerActivity ? activity , Exception ? exception , HttpStatusCode statusCode )
4547 {
4648 var level = ( int ) statusCode >= 500 ? LogEventLevel . Error : LogEventLevel . Information ;
47- _logger . Write ( level , exception ,
48- "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.000} ms" ,
49- request . Method , request . Path , ( int ) statusCode , sw . Elapsed . TotalMilliseconds ) ;
49+ if ( activity ? . Activity != null )
50+ {
51+ if ( _logger . BindProperty ( "StatusCode" , ( int ) statusCode , false , out var statusCodeProperty ) )
52+ {
53+ ActivityInstrumentation . SetLogEventProperty ( activity . Activity ,
54+ statusCodeProperty ) ;
55+ }
56+
57+ if ( exception != null )
58+ {
59+ ActivityInstrumentation . TrySetException ( activity . Activity , exception ) ;
60+ }
61+ }
62+
63+ activity ? . Complete ( level ) ;
64+
5065 return false ;
5166 }
5267}
0 commit comments