如何将日志添加到MVC4 WebApi

时间:2012-07-10 19:46:56

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api

我正在尝试为[LoggedApiCall]上的Get()创建ApiController过滤器 根据这个:ASP.NET Web API ActionFilter example

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

我似乎找不到从HttpActionExecutedContext

获取来电者IP的方法

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

1 个答案:

答案 0 :(得分:13)

我们使用以下过滤器添加到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}", logEntry, 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地址。

干杯, 迪安