如何在MVC控制器的动作处理期间添加环境Serilog属性

问题描述 投票:0回答:1

我想向请求ASP.NET Core控制器范围内发生的所有日志添加Serilog属性。此属性的值由路由数据确定。

从概念上讲,这很容易,我只需要向控制器添加以下内容:

public override void OnActionExecuting(ActionExecutingContext context)
{
   var propValue = context.ActionArguments["myvalue"] as string;
   // BAD CODE DON'T COPY THIS
   LogContext.PushProperty("MyProperty", propValue);
   base.OnActionExecuting(context);
}

此“方法”有效,因为它将“ MyProperty”添加到每个记录的事件中,一直到该请求的其余调用为止。但是,这样做显然不是正确的方法,因为文档给出了严格的说明,以按推入它们的相反顺序仔细处理对LogContext.PushProperty的调用。没什么可说LogContext具有与HTTP请求相同的作用域。

我以为IDiagnosticContext是解决方案,但它仅影响Serilog的请求记录,而不是一般的环境。

该框架实际上实现了我想要的,用'ActionName'和'RequestId'这样的东西装饰了日志上下文,但是我想它会在请求范围更清晰的某个时候做到这一点。

是否有一种简单的方法可以“为当前请求的其余部分”添加环境Serilog属性,或者我需要编写中间件来做到这一点?

asp.net-core serilog
1个回答
0
投票

[确定,事实证明,有一个简单的解决方案,并且控制器具有比OnActionExecuting更合适的覆盖:

public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    var propValue = context.ActionArguments["myvalue"] as string;
    using (LogContext.PushProperty("MyProperty", propValue))
    {
        await base.OnActionExecutionAsync(context, next);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.