在日志中显示实际方法名称
Display Actual Method Name In Log
我一直在 .net 核心 webapi 项目中使用 Serilog,并且能够愉快地使用它。但是,我想在信息日志中包含方法名称的示例 - 使用 SourceContext 可以访问 class 名称。
然而,根据各种在线建议/指南,我添加了一个 enricher,但每次的结果都是实际的 Enrich 方法。
总结一下我的知识,我的背景主要是 .net 3.5 及以下,因此目前除此之外的所有内容都是非常陡峭的学习曲线。请温柔一点:-)
我都试过了:
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(System.Reflection.MethodBase.GetCurrentMethod().Name)));
和
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(GetActualAsyncMethodName())));
尝试使用下面的代码:
var methodname = ControllerContext.ActionDescriptor.ActionName;
最后,我通过添加操作过滤器并向 Serilog 的 LogContext 添加 属性 解决了这个问题,如下所示:
public class LoggingPropertiesFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
ControllerBase controllerBase = context.Controller as ControllerBase;
if(controllerBase != null)
{
var routeAction = controllerBase.RouteData.Values["action"];
LogContext.PushProperty("method", routeAction);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
到目前为止,我遇到的唯一问题是我必须手动为每个操作附加一个属性才能使其正常工作,但这确实解决了我最初遇到的问题,如果它对任何人都有用的话。
我一直在 .net 核心 webapi 项目中使用 Serilog,并且能够愉快地使用它。但是,我想在信息日志中包含方法名称的示例 - 使用 SourceContext 可以访问 class 名称。
然而,根据各种在线建议/指南,我添加了一个 enricher,但每次的结果都是实际的 Enrich 方法。
总结一下我的知识,我的背景主要是 .net 3.5 及以下,因此目前除此之外的所有内容都是非常陡峭的学习曲线。请温柔一点:-)
我都试过了:
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(System.Reflection.MethodBase.GetCurrentMethod().Name)));
和
logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(GetActualAsyncMethodName())));
尝试使用下面的代码:
var methodname = ControllerContext.ActionDescriptor.ActionName;
最后,我通过添加操作过滤器并向 Serilog 的 LogContext 添加 属性 解决了这个问题,如下所示:
public class LoggingPropertiesFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
ControllerBase controllerBase = context.Controller as ControllerBase;
if(controllerBase != null)
{
var routeAction = controllerBase.RouteData.Values["action"];
LogContext.PushProperty("method", routeAction);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
到目前为止,我遇到的唯一问题是我必须手动为每个操作附加一个属性才能使其正常工作,但这确实解决了我最初遇到的问题,如果它对任何人都有用的话。