亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在日志中顯示實際方法名稱

在日志中顯示實際方法名稱

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條經驗 獲得超8個贊

嘗試在操作中使用以下代碼:


var methodname = ControllerContext.ActionDescriptor.ActionName;


查看完整回答
反對 回復 2023-07-22
  • 2 回答
  • 0 關注
  • 148 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號