实现的原理比较直接,定义一个MessageHandler记录WebAPI的请求记录,然后将这些请求日志推送到客户端,客户端就是一个查看日志的页面,实时将请求日志展示在页面中。

这个例子的目的是演示如何在PersistentConnection类外部给Clients推送消息

实现过程

一、服务端

服务端同时具备SignalR和WebAPI的功能,通过定义一个记录日志的MessageHandler实现对WebAPI请求的拦截,并生成请求记录,然后推送到客户端

step 1

创建一个具备WebAPI功能的站点,为了简化起见,设置Authentication为No Authentication

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 > )
{
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

示例代码下载

用SignalR实现实时查看WebAPI请求日志的更多相关文章

  1. 实时查看docker容器日志

    实时查看docker容器日志 $ sudo docker logs -f -t --tail 行数 容器名 例:实时查看docker容器名为s12的最后10行日志 $ sudo docker logs ...

  2. linux下打开、关闭tomcat,实时查看tomcat执行日志

     启动:通常是运行sh tomcat/bin/startup.sh   停止:通常是运行sh tomcat/bin/shutdown.sh脚本命令   查看:运行ps -ef |grep tomc ...

  3. 查看 redis 请求日志

    转: 查看 redis 请求日志 2019-05-29 15:34:41 打卤 阅读数 1980更多 分类专栏: other   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转 ...

  4. 如何实时查看Linux下日志

    以下以Tomcat为例子,其他WEB服务器目录自己灵活修改即可: 1.先切换到:cd usr/local/tomcat5/logs2.tail -f catalina.out3.这样运行时就可以实时查 ...

  5. 【linux】linux重启tomcat + 实时查看tomcat启动日志

    linux重启tomcat命令: http://www.cnblogs.com/plus301/p/6237468.html linux查看toncat实时的启动日志: https://www.cnb ...

  6. nginx查看post请求日志

    在http段加上 log_format access '$remote_addr - $remote_user [$time_local] "$request" $status $ ...

  7. ASP.NET Web API 2系列(三):查看WebAPI接口的详细说明及测试接口

    引言 前边两篇博客介绍了Web API的基本框架以及路由配置,这篇博客主要解决在前后端分离项目中,为前端人员提供详细接口说明的问题,主要是通过修改WebApi HelpPage相关代码和添加WebAp ...

  8. linux下查看tomcat的日志

    工作期间有碰到服务器日志相关的,需要看tomcat运行日志,简单搜了下,摘为随笔,以供参考 一种是利用docker查看 1.使用dockerdocker logs -f -t --since=&quo ...

  9. SignalR实现实时日志监控

    .net SignalR实现实时日志监控   摘要 昨天吃饭的时候,突然想起来一个好玩的事,如果能有个页面可以实时的监控网站或者其他类型的程序的日志,其实也不错.当然,网上也有很多成熟的类似的监控系统 ...

随机推荐

  1. Django知识(二)

    上一部链接 django入门全套(第一部) 本章内容 Django model Model 基础配置 django默认支持sqlite,mysql, oracle,postgresql数据库. < ...

  2. C# 连接Oracle ,免安装客户端

    在.NET平台下开发Oracle应用的小伙伴们肯定都知道一方面做Oracle开发和实施相比SqlServer要安装Oracle客户端(XCopy.自己提取相关文件也有一定复杂性),另一方面相比JAVA ...

  3. Swift 写纯洁的TableviewCell

    let initIdentifier = "员工" var cell = tableView.dequeueReusableCell(withIdentifier: initIde ...

  4. 常用的yum命令

    linux各发行版有多种包管理机制,下面介绍基于RedHat系的yum包管理命令:   yum -y install xxx         无需询问,安装xxx包   yum list        ...

  5. SQL 还原数据库

    1. 查看 SQL Server 2000 中 Northwind 数据库文件的逻辑文件名(logical file name)和物理文件路径(operation system file name): ...

  6. ThinkPHP的异步搜索

    因为公司的后台框架采用了Ajax异步处理,控制器的方法,有时候会被多个连接所重复调用,虽然这个很符合OOP开发思想,但是为了维护这个框架,付出的汗水也是很大的. 说下正题了: 我在后台的搜索框调用了优 ...

  7. YbSoftwareFactory 代码生成插件【二十五】:Razor视图中以全局方式调用后台方法输出页面代码的三种方法

    上一篇介绍了 MVC中实现动态自定义路由 的实现,本篇将介绍Razor视图中以全局方式调用后台方法输出页面代码的三种方法. 框架最新的升级实现了一个页面部件功能,其实就是通过后台方法查询数据库内容,把 ...

  8. C语言 03 项目团队文件合并

    团体项目中 链接把项目中所有相关联的.O目标文件.C语言函数库合并在一起,生成可执行文件. 编写声明文件,用 .h文件封装起来,在其他代码中用include"xxx.h"引用声明 ...

  9. HTTP请求 GET与POST是怎么实现?

    1.HTTP请求格式: <request line> <headers> <blank line> [<request-body>] 在HTTP请求中, ...

  10. HDU 4292:Food(最大流)

    http://acm.hdu.edu.cn/showproblem.php?pid=4292 题意:和奶牛一题差不多,只不过每种食物可以有多种. 思路:因为食物多种,所以源点和汇点的容量要改下.还有D ...