Skip to content

Instantly share code, notes, and snippets.

@SebastianStehle
Created April 8, 2017 20:47
Show Gist options
  • Save SebastianStehle/ede7943322c53fb14eb3d3c7f7361663 to your computer and use it in GitHub Desktop.
Save SebastianStehle/ede7943322c53fb14eb3d3c7f7361663 to your computer and use it in GitHub Desktop.
public class ActionContextLogAppender : ILogAppender
{
private readonly IActionContextAccessor actionContextAccessor;
public ActionContextLogAppender(IActionContextAccessor actionContextAccessor)
{
this.actionContextAccessor = actionContextAccessor;
}
public void Append(IObjectWriter writer)
{
var actionContext = actionContextAccessor.ActionContext;
var httpContext = actionContext.HttpContext;
Guid requestId;
if (httpContext.Items.TryGetValue(nameof(requestId), out var value) && value is Guid requestIdValue)
{
requestId = requestIdValue;
}
else
{
httpContext.Items[nameof(requestId)] = requestId = Guid.NewGuid();
}
writer.WriteObject("web", w => w
.WriteProperty("requestId", requestId.ToString())
.WriteProperty("requestPath", httpContext.Request.Path)
.WriteProperty("requestMethod", httpContext.Request.Method)
.WriteObject("routeValues", r =>
{
foreach (var kvp in actionContext.ActionDescriptor.RouteValues)
{
r.WriteProperty(kvp.Key, kvp.Value);
}
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment