C# 用ActionFilter給WebAPI增加請求日誌

 編寫 ActionFilterAttribute

using System;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Provider.WebFilters
{
    /// <summary>
    /// WebAPI Action監控
    /// </summary>
    public class ActionMonitorAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 全局請求ID號
        /// </summary>
        private static Int64 ActionId { get; set; }
        /// <summary>
        /// 客戶端IP地址
        /// </summary>
        private String ClientIp { get; set; }
        /// <summary>
        /// 請求ID號
        /// </summary>
        private Int64 RequestId { get; set; }

        /// <summary>
        /// 請求的接口
        /// </summary>
        private String controllername { get; set; }


        /// <summary>
        /// 請求處理前
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            RequestId = ActionId++;
            var strary = actionContext.Request.RequestUri.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            controllername = strary[1];
            dynamic RemoteEndpoint = null;
            if (actionContext.Request.Properties.TryGetValue("System.ServiceModel.Channels.RemoteEndpointMessageProperty", out RemoteEndpoint))
            {
                ClientIp = RemoteEndpoint.Address;
                if (ClientIp == "::1")
                {
                    ClientIp = "localhost";
                }
            }
            String Message = String.Format("[Requestd].[{1}].[{4}].[{0}].[{2}]=>{3}", RequestId, ClientIp, actionContext.Request.Method, actionContext.Request.RequestUri, controllername);
            LogHelper.WebRequest.Info(Message);
            base.OnActionExecuting(actionContext);
        }

        /// <summary>
        /// 請求返回前
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception == null)
            {
                LogHelper.WebRequest.Info(String.Format("[Response].[{0}].[{3}].[{1}].[{2}]", ClientIp, RequestId, actionExecutedContext.Response.ReasonPhrase, controllername));
                if (LogHelper.WebRequest.IsDebugEnabled)
                {
                    LogHelper.WebRequest.Debug(String.Format("    [Data]\t{0}\t{1}", RequestId, actionExecutedContext.Response.Content.ReadAsStringAsync().Result));
                }
            }
            else
            {
                LogHelper.WebRequest.Info(String.Format("[Response].[{0}].[{3}].[{1}].[{2}]", ClientIp, RequestId, "Exception", controllername));
                LogHelper.Default.Info(String.Format("[WebApiRequest].[Exception].[{0}].[{1}]\r\n{2}", RequestId, actionExecutedContext.Request.RequestUri, actionExecutedContext.Exception.StackTrace));
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}

 

 

實際使用 

在 WEBAPI的 Controller類加上  [ActionMonitor] 屬性即可

using System.Net;
using System.Net.Http;
using System.Web.Http;
using Provider.WebFilters;

namespace Provider.WebController
{
    [ActionMonitor]
    public class TestController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage Get()
        {
            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章