为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
GCT1015 2023-07-22 16:22:18
我一直在 .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())));
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

最后,我通过添加操作过滤器并向 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.

        }

    }

到目前为止,我遇到的唯一问题是我必须手动为每个操作附加一个属性才能使其工作,但这确实解决了我遇到的最初问题(如果它对任何人都有用的话)。


查看完整回答
反对 回复 2023-07-22
?
弑天下

TA贡献1818条经验 获得超7个赞

尝试在操作中使用以下代码:


var methodname = ControllerContext.ActionDescriptor.ActionName;


查看完整回答
反对 回复 2023-07-22
  • 2 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信