用SignalR實現實時查看WebAPI請求日誌

来源:http://www.cnblogs.com/shenba/archive/2016/04/25/5430190.html
-Advertisement-
Play Games

實現的原理比較直接,定義一個MessageHandler記錄WebAPI的請求記錄,然後將這些請求日誌推送到客戶端,客戶端就是一個查看日誌的頁面,實時將請求日誌展示在頁面中。 這個例子的目的是演示如何在PersistentConnection類外部給Clients推送消息 實現過程 一、服務端 服務 ...


實現的原理比較直接,定義一個MessageHandler記錄WebAPI的請求記錄,然後將這些請求日誌推送到客戶端,客戶端就是一個查看日誌的頁面,實時將請求日誌展示在頁面中。

這個例子的目的是演示如何在PersistentConnection類外部給Clients推送消息

image

實現過程

一、服務端

服務端同時具備SignalR和WebAPI的功能,通過定義一個記錄日誌的MessageHandler實現對WebAPI請求的攔截,並生成請求記錄,然後推送到客戶端

step 1

創建一個具備WebAPI功能的站點,為了簡化起見,設置Authentication為No Authentication

image

step 2

創建一個DelegatingHandler,用於記錄WebAPI日誌,代碼如下

下麵代碼沒有涉及到SignalR的功能,日誌展示是通過ILoggingDisplay介面傳入

public class LoggingHandler : DelegatingHandler 
    { 
        private static readonly string _loggingInfoKey = "loggingInfo";

        private ILoggingDisplay _loggingDisplay;

        public LoggingHandler(ILoggingDisplay loggingDisplay) 
        { 
            _loggingDisplay = loggingDisplay; 
        }

        public LoggingHandler(HttpMessageHandler innerHandler, ILoggingDisplay loggingDisplay) 
            : base(innerHandler) 
        { 
            _loggingDisplay = loggingDisplay; 
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
        { 
            LogRequestLoggingInfo(request); 
            return base.SendAsync(request, cancellationToken).ContinueWith(task => 
            { 
                var response = task.Result; 
                LogResponseLoggingInfo(response); 
                return response; 
            }); 
        }

        private void LogRequestLoggingInfo(HttpRequestMessage request) 
        { 
            var info = new ApiLoggingInfo(); 
            info.HttpMethod = request.Method.Method; 
            info.UriAccessed = request.RequestUri.AbsoluteUri; 
            info.IpAddress = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "0.0.0.0"; 
            info.StartTime = DateTime.Now; 
            ExtractMessageHeadersIntoLoggingInfo(info, request.Headers.ToList()); 
            request.Properties.Add(_loggingInfoKey, info); 
        }

        private void LogResponseLoggingInfo(HttpResponseMessage response) 
        { 
            object loggingInfoObject = null; 
            if (!response.RequestMessage.Properties.TryGetValue(_loggingInfoKey, out loggingInfoObject)) 
            { 
                return; 
            } 
            var info = loggingInfoObject as ApiLoggingInfo; 
            if (info == null) 
            { 
                return; 
            } 
            info.HttpMethod = response.RequestMessage.Method.ToString(); 
            info.ResponseStatusCode = response.StatusCode; 
            info.ResponseStatusMessage = response.ReasonPhrase; 
            info.UriAccessed = response.RequestMessage.RequestUri.AbsoluteUri; 
            info.IpAddress = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "0.0.0.0"; 
            info.EndTime = DateTime.Now; 
            info.TotalTime = (info.EndTime - info.StartTime).TotalMilliseconds; 
            _loggingDisplay.Display(info); 
        }

        private void ExtractMessageHeadersIntoLoggingInfo(ApiLoggingInfo info, List<KeyValuePair<string, IEnumerable<string>>> headers) 
        { 
            headers.ForEach(h => 
            { 
                var headerValues = new StringBuilder();

                if (h.Value != null) 
                { 
                    foreach (var hv in h.Value) 
                    { 
                        if (headerValues.Length > 0) 
                        { 
                            headerValues.Append(", "); 
                        } 
                        headerValues.Append(hv); 
                    } 
                } 
                info.Headers.Add(string.Format("{0}: {1}", h.Key, headerValues.ToString())); 
            }); 
        } 
    }
LoggingHandler

step 3

引入SignalR相關packages

Install-Package Microsoft.AspNet.SignalR

新建一個PersistentConnection,代碼為空即可(因為不涉及到客戶端調用,推送也是在類的外部執行)

public class RequestMonitor : PersistentConnection
{
}

添加一個Startup類

public void Configuration(IAppBuilder app)
{
       app.MapSignalR<RequestMonitor>("/monitor");
}

step 4

創建一個類實現ILoggingDisplay介面,用SignalR推送的方式實現這個介面

代碼比較關鍵的部分就是通過GlobalHost.ConnectionManager獲取當前應用程式的connectionContext,得到這個context就可以類似在PersistentConnection內部給clients推送消息

public class SignalRLoggingDisplay : ILoggingDisplay 
    { 
        /// <summary> 
        /// PersistentConnection上下文 
        /// </summary> 
        private static IPersistentConnectionContext connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<RequestMonitor>();

        public void Display(ApiLoggingInfo loggingInfo) 
        { 
            var message = new StringBuilder(); 
             message.AppendFormat("StartTime:{0},Method:{1},Url:{2},ReponseStatus:{3},TotalTime:{4}" 
                , loggingInfo.StartTime, loggingInfo.HttpMethod, loggingInfo.UriAccessed, loggingInfo.ResponseStatusCode, loggingInfo.TotalTime); 
            message.AppendLine(); 
            message.AppendFormat("Headers:{0},Body:{1}", string.Join(",", loggingInfo.Headers), loggingInfo.BodyContent); 
            connectionContext.Connection.Broadcast(message.ToString()); 
        }
SignalRLoggingDisplay

step 5

在WebApiConfig的Register方法中添加自定義的handler

public static void Register(HttpConfiguration config) 
       { 
           config.MapHttpAttributeRoutes();

           config.Routes.MapHttpRoute( 
               name: "DefaultApi", 
               routeTemplate: "api/{controller}/{id}", 
               defaults: new { id = RouteParameter.Optional } 
           );

           config.MessageHandlers.Add(new LoggingHandler(new SignalRLoggingDisplay())); 
       }
RegisterHandler

到此完成服務端的功能實現

 

二、客戶端

客戶端只需要一個監控頁面,html頁面足矣,其主要功能是提供開始監控、停止監控功能,其他都是接收服務端的推送並展示功能代碼。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Web API頁面實時請求監控</title> 
    <meta charset="utf-8" /> 
</head> 
<body> 
    <h1>Web API Request Logs</h1> 
    <div> 
        <input type="button" value="start" id="btnStart"/> 
        <input type="button" value="stop" id="btnStop"/> 
        <input type="button" value="clear" id="btnClear"/> 
    </div> 
    <ul id="requests"></ul> 
    <script src="/Scripts/jquery-1.10.2.min.js"></script> 
    <script src="/Scripts/jquery.signalR-2.2.0.min.js"></script> 
    <script> 
        $(function () { 
            var requests = $("#requests"); 
            var startButton = $("#btnStart"); 
            var stopButton = $("#btnStop"); 
            var connection = null;

            enable(stopButton, false); 
            enable(startButton, true);

            startButton.click(function () { 
                startConnection(); 
                enable(stopButton, true); 
                enable(startButton, false); 
            });

            $("#btnClear").click(function () { 
                $("#requests").children().remove(); 
            });

            stopButton.click(function () { 
                stopConnection(); 
                enable(stopButton, false); 
                enable(startButton, true); 
            });

            function startConnection() { 
                stopConnection(); 
                connection = $.connection("/monitor"); 
                connection.start() 
                    .fail(function () { 
                        console.log("connect failed"); 
                    }); 
                connection.received(function (data) { 
                    data = data.replace(/\r\n/g, "<br/>") 
                    data = data.replace(/\n/g, "<br/>"); 
                    requests.append("<li>" + data + "</li>"); 
                }); 
            }

            function stopConnection() { 
                if (connection != null){ 
                    connection.stop(); 
                } 
            }

            function enable(button, enabled) { 
                if (enabled) { 
                    button.removeAttr("disabled"); 
                } 
                else { 
                    button.attr("disabled", "disabled"); 
                } 
            } 
        }); 
    </script> 
</body> 
</html>
Monitor

示例代碼下載


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ...
  • 因為休眠功能在部分電腦無法正常工作,所以Ubuntu預設是不開啟休眠功能。 要想開啟休眠功能先進行如下測試: 1、先檢查是否有交換分區(swap),如果有確認交換分區至少和實際可用記憶體一樣大。 2、按Ctrl+Alt+T開啟終端或者Dash搜索開啟終端 3、運行sudo pm-hibernate, ...
  • 1、當我想要使用sudo時,提示 一開始以為是PATH不對,就各種百度各種試 都不好使,最後發現是我裝的debian 8.4.0 amd64 1並不是全功能,sudo沒有裝 2、apt源總是連接到cdrom,使用apt-get install時總是提示出錯,因為我是通過u盤ios鏡像安裝的 可以把c ...
  • HAProxy: 實現了一種事件驅動,單一進程模型,支持數萬計的併發連接,用於為tcp和http應用程式提供高可用,負載均衡和代理服務的解決方案,尤其適用於高負載且需要持久連接或7層處理機制的web站點 代理(http): 正向代理: 反向代理: 代理作用:web緩存(加速)、反向代理、內容路由(根 ...
  • 1、sl 奔跑吧,火車! nick-suo@ubuntu:~$ sudo apt-get install sl 2、telnet 星球大戰 nick-suo@ubuntu:~$ telnet towel.blinkenlights.nl 3、cmatrix 代碼屏保 nick-suo@ubuntu: ...
  • 最近看了一些Android驅動開發前需要知道的資料,收穫很多,接下來就談談我自己的一些心得體會。 Android在近幾年時間發展迅速,已經成為智能手機操作系統的老大。不過,因為Android原生的代碼支持的設備並不多,所以我們要想在自己的設備上完美地運行Android就需要另外地開發一些程式,從而可 ...
  • 我在上篇隨筆《C#開發微信門戶及應用(32)--微信支付接入和API封裝使用》介紹為微信支付的API封裝及使用,其中介紹瞭如何配置好支付環境,並對掃碼支付的兩種方式如何在C#開發中使用進行了介紹,本隨筆繼續介紹微信支付的相關內容,介紹其中的微信現金紅包和裂變紅包的封裝和使用。 在上篇隨筆後,經過對整 ...
  • 1.C#中的類型一共分兩類,一類是值類型,一類是引用類型。2.結構類型變數本身就相當於一個實例。3.調用結構上的方法前,需要對其所有的欄位進行賦值。4.所有元素使用前都必須初始化。5.(結構類型)new操作符不會分配記憶體,僅僅調用此結構的預設構造函數去初始化其所有欄位。 6.(引用類型)變數保存了位 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...