forked from postsharp/PostSharp.Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoggingActionFilter.cs
More file actions
83 lines (72 loc) · 2.57 KB
/
Copy pathLoggingActionFilter.cs
File metadata and controls
83 lines (72 loc) · 2.57 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using Microsoft.AspNetCore.Mvc.Filters;
using PostSharp.Patterns.Diagnostics;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using static PostSharp.Patterns.Diagnostics.SemanticMessageBuilder;
namespace MicroserviceExample
{
[Log(AttributeExclude = true)]
public class LoggingActionFilter : IAsyncActionFilter
{
private static readonly LogSource logger = LogSource.Get();
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Read the Request-Id header so we can assign it to the activity.
string parentOperationId = context.HttpContext.Request.Headers["Request-Id"];
OpenActivityOptions options = default;
// Set the parent id.
if (!string.IsNullOrEmpty(parentOperationId))
{
options.SyntheticParentId = parentOperationId;
}
else
{
options.IsSyntheticRootId = true;
}
// Process cross-context properties (aka baggage).
string correlationContext = context.HttpContext.Request.Headers["Correlation-Context"];
if (!string.IsNullOrEmpty(correlationContext))
{
var properties = new List<LoggingProperty>();
foreach (var pair in correlationContext.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
var posOfEqual = pair.IndexOf('=');
if (posOfEqual <= 0)
{
continue;
}
var propertyName = pair.Substring(0, posOfEqual);
var propertyValue = pair.Substring(posOfEqual + 1);
properties.Add(new LoggingProperty(propertyName, propertyValue) { IsBaggage = true });
}
options.Properties = properties.ToArray();
}
var request = context.HttpContext.Request;
using (var activity = logger.Default.OpenActivity(Semantic("Request", ("Path", request.Path),
("Query", request.QueryString), ("Method", request.Method)), options))
{
try
{
await next();
var response = context.HttpContext.Response;
if (response.StatusCode >= (int) HttpStatusCode.OK && response.StatusCode <= 299)
{
// Success.
activity.SetOutcome(LogLevel.Info, Semantic("Success", ("StatusCode", response.StatusCode)));
}
else
{
// Failure.
activity.SetOutcome(LogLevel.Warning, Semantic("Failure", ("StatusCode", response.StatusCode)));
}
}
catch (Exception e)
{
activity.SetException(e);
}
}
}
}
}