在日志中显示实际方法名称

我一直在 .net core webapi 项目中使用 Serilog,并且能够愉快地使用它。但是,我想在信息日志中包含方法名称的示例 - 使用 SourceContext 访问类名称是可以的。

然而,根据网上的各种建议/指南,我添加了一个丰富器,但每次的结果都是实际的丰富方法。

总结一下我的知识,我主要来自 .net 3.5 及以下背景,因此目前除此之外的所有内容都是非常陡峭的学习曲线。请温柔点:-)

我都尝试过:

logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(System.Reflection.MethodBase.GetCurrentMethod().Name)));

logEvent.AddOrUpdateProperty(new LogEventProperty("MethodName", new ScalarValue(GetActualAsyncMethodName())));


GCT1015
浏览 96回答 2
2回答

蓝山帝景

最后,我通过添加操作过滤器并向 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.        }    }到目前为止,我遇到的唯一问题是我必须手动为每个操作附加一个属性才能使其工作,但这确实解决了我遇到的最初问题(如果它对任何人都有用的话)。

弑天下

尝试在操作中使用以下代码:var methodname = ControllerContext.ActionDescriptor.ActionName;
打开App,查看更多内容
随时随地看视频慕课网APP