加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何添加日志到MVC4 WebApi

发布时间:2020-12-16 00:39:25 所属栏目:asp.Net 来源:网络整理
导读:我试图为ApiController上的Get()创建一个[LoggedApiCall]过滤器 据此: ASP.NET Web API ActionFilter example 我创建了一个System.Web.HttpFilters.ActionFilterAttribute。 覆盖允许OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 我
我试图为ApiController上的Get()创建一个[LoggedApiCall]过滤器
据此: ASP.NET Web API ActionFilter example

我创建了一个System.Web.HttpFilters.ActionFilterAttribute。
覆盖允许OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

我似乎找不到从HttpActionExecutedContext获取调用者的IP的方法

也许我打算记录每个API调用错误的方式?

解决方法

我们使用我们添加到HttpConfiguration.Filters的以下过滤器。一些代码:
internal class LoggingFilter : IExceptionFilter,IActionFilter
{
    private readonly ILog log;

    public LoggingFilter(ILog log)
    {
        if (log == null)
        {
            throw new ArgumentNullException("log");
        }

        this.log = log;
    }

    public bool AllowMultiple
    {
        get { return false; }
    }

    Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionContext,CancellationToken cancellationToken)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        this.log.Error(string.Format("Unexpected error while executing {0}",this.BuildLogEntry(actionContext.ActionContext)),actionContext.Exception);
        return TaskHelpers.Completed();
    }

    Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext,CancellationToken cancellationToken,Func<Task<HttpResponseMessage>> continuation)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        if (continuation == null)
        {
            throw new ArgumentNullException("continuation");
        }

        if (!this.log.IsDebugEnabled)
        {
            // no point running at all if logging isn't currently enabled
            return continuation();
        }

        string logEntry = this.BuildLogEntry(actionContext);
        IDisposable logContext = this.log.DebugTiming("Executing {0}",logEntry);

        Task<string> requestContent;
        if (actionContext.Request.Content != null)
        {
            requestContent = actionContext.Request.Content.ReadAsStringAsync().ContinueWith(requestResult => string.IsNullOrEmpty(requestResult.Result) ? "N/A" : requestResult.Result);
        }
        else
        {
            requestContent = TaskHelpers.FromResult("N/A");
        }

        return requestContent.ContinueWith(
            requestResult =>
                {
                    this.log.DebugFormat("{0},Request = {1}",logEntry,requestResult.Result);

                    return continuation()
                        .ContinueWith(t =>
                            {
                                Task<string> responseContent;
                                if (t.IsCompleted && t.Result.Content != null)
                                {
                                    responseContent = t.Result.Content.ReadAsStringAsync().ContinueWith(responseResult => string.IsNullOrEmpty(responseResult.Result) ? "N/A" : responseResult.Result);
                                }
                                else
                                {
                                    responseContent = TaskHelpers.FromResult("N/A");
                                }

                                return responseContent.ContinueWith(
                                    responseResult =>
                                        {
                                            using (logContext)
                                            {
                                                this.log.DebugFormat("{0},Status Code: {1},Response = {2}",t.Result.StatusCode,responseResult.Result);
                                            }

                                            return t.Result;
                                        });
                            }).Unwrap();
                }).Unwrap();
    }

    /// <summary>
    /// Builds log data about the request.
    /// </summary>
    /// <param name="actionContext">Data associated with the call</param>
    private string BuildLogEntry(HttpActionContext actionContext)
    {
        string route = actionContext.Request.GetRouteData().Route.RouteTemplate;
        string method = actionContext.Request.Method.Method;
        string url = actionContext.Request.RequestUri.AbsoluteUri;
        string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        string actionName = actionContext.ActionDescriptor.ActionName;

        return string.Format("{0} {1},route: {2},controller:{3},action:{4}",method,url,route,controllerName,actionName);
    }
}

我们使用log4net,您可以用任何您认为合适的替换ILog实现。 ILog.DebugTiming只是一种扩展方法,它使用秒表来获取每次调用的时间。

编辑:
这篇文章Get the IP address of the remote host具有如何获取远程调用者的IP地址的详细信息。

干杯,院长

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读