-
Notifications
You must be signed in to change notification settings - Fork 5
/
RequestTrackingMiddleware.cs
68 lines (60 loc) · 2.41 KB
/
RequestTrackingMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Fabric;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ServiceFabric.Logging.Extensions;
using ServiceFabric.Logging.PropertyMap;
using ServiceFabric.Remoting.CustomHeaders;
namespace ServiceFabric.Logging.Middleware
{
public class RequestTrackingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestTrackingMiddleware(RequestDelegate next, ILogger logger)
{
this._next = next;
this._logger = logger;
}
public async Task Invoke(HttpContext context, StatelessServiceContext serviceContext)
{
using (_logger.BeginScope(new Dictionary<string, object>
{
[SharedProperties.TraceId] = context.Request.HttpContext.TraceIdentifier
}))
{
RemotingContext.SetData(HeaderIdentifiers.TraceId, context.Request.HttpContext.TraceIdentifier);
AddTracingDetailsOnRequest(context, serviceContext);
var stopwatch = Stopwatch.StartNew();
var started = DateTime.Now;
var success = false;
try
{
await _next(context);
success = true;
}
catch (Exception exception)
{
_logger.LogCritical((int)ServiceFabricEvent.Exception, exception, exception.Message);
throw;
}
finally
{
stopwatch.Stop();
_logger.LogRequest(context, started, stopwatch.Elapsed, success);
}
}
}
private static void AddTracingDetailsOnRequest(HttpContext context, ServiceContext serviceContext)
{
if (!context.Request.Headers.ContainsKey("X-Fabric-AddTracingDetails")) return;
context.Response.Headers.Add("X-Fabric-NodeName", serviceContext.NodeContext.NodeName);
context.Response.Headers.Add("X-Fabric-InstanceId", serviceContext.ReplicaOrInstanceId.ToString(CultureInfo.InvariantCulture));
context.Response.Headers.Add("X-Fabric-TraceId", context.Request.HttpContext.TraceIdentifier);
}
}
}