用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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...