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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何添加日志到MVC4 WebApi前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图为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地址的详细信息。

干杯,院长

原文链接:https://www.f2er.com/aspnet/252850.html

猜你在找的asp.Net相关文章