1、API项目下创建MonitorApiAttribute

public class MonitorApiAttribute : ActionFilterAttribute
{
private static readonly string key = "enterTime"; public override void OnActionExecuted(HttpActionExecutedContext filterContext)
{
try
{
object beginTime = null;
if (filterContext.Request.Properties.TryGetValue(key, out beginTime))
{
var user = HttpContext.Current.User as UserInfo;//登录时储存的User
var indentify = user != null ? user.Id.ToString() : null; MonitorApiHelper.Monitor(beginTime, filterContext.Request, filterContext.Response, indentify);
}
}
catch (Exception)
{
} base.OnActionExecuted(filterContext);
} public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.Request.Properties[key] = DateTime.Now.ToBinary(); base.OnActionExecuting(actionContext);
}
}

2、Common项目下创建MonitorApiHelper帮助类

public class MonitorApiHelper
{ public static async void Monitor(object beginTime, HttpRequestMessage httpRequestMessage, HttpResponseMessage httpResponseMessage, string indentify = "", string moduleId = "")
{
DateTime time = DateTime.FromBinary(Convert.ToInt64(beginTime));
var responseTime = Convert.ToInt32((DateTime.Now - time).TotalMilliseconds); var appId = "myapp";
var clientType = 0;
var responseStatus = 0; var request = HttpContext.Current.Request;
var browerVersion = request.UserAgent;
var clientIP = request.UserHostAddress;
var serviceName = request.Url.AbsoluteUri;
var requestType = MethodConver(request.HttpMethod); var inputParams = ReadStream(await httpRequestMessage.Content.ReadAsStreamAsync());
var outputParams = ReadStream(await httpResponseMessage.Content.ReadAsStreamAsync()); //在这里使用以上变量记录日志操作
} private static int MethodConver(string method)
{
switch (method.ToUpper())
{
case "GET":
return 0;
case "POST":
return 1;
case "PUT":
return 2;
case "DELETE":
return 3;
default:
break;
}
return 0;
} public static string ReadStream(Stream stream)
{
var content = string.Empty;
if (stream != null)
{
stream.Seek(0, SeekOrigin.Begin);
int len = (int)stream.Length;
byte[] inputByts = new byte[len];
stream.Read(inputByts, 0, len);
stream.Position = 0;
content = Encoding.UTF8.GetString(inputByts);
} return content;
}
}

3、WebApiConfig下增加代码  config.Filters.Add(new MonitorApiAttribute());

  public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Filters.Add(new MonitorApiAttribute()); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

ActionFilterAttribute 全局记录API日志的更多相关文章

  1. 基于AOP和ThreadLocal实现的一个简单Http API日志记录模块

    Log4a 基于AOP和ThreadLocal实现的一个简单Http API日志记录模块 github地址 : https://github.com/EalenXie/log4a 在API每次被请求时 ...

  2. SLF4J - 一个允许你统一日志记录API的抽象层

    一.什么是SLF4J 我们在做Java开发时,如果需要记录日志,有很多日志API可供选择,如: java.util.logging Apache log4j logback SLF4J又是个什么东东呢 ...

  3. asp.net core全局异常过滤并监控系统BUG将异常信息记录到日志

    添加: using Dw.Util.Helper; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collect ...

  4. .NET CORE之API日志收集

    我们在构建WEBAPI项目时,通常需要构建一个全局的记录API 请求和返回 的功能,在WEBAPI框架下 我们通过自定义一个DelegateHandler来实现这个功能, 在.NET CORE框架下已 ...

  5. 基于.NetCore3.1系列 —— 日志记录之日志配置揭秘

    一.前言 在项目的开发维护阶段,有时候我们关注的问题不仅仅在于功能的实现,甚至需要关注系统发布上线后遇到的问题能否及时的查找并解决.所以我们需要有一个好的解决方案来及时的定位错误的根源并做出正确及时的 ...

  6. MVC 记录操作日志与过滤特殊字符

    最近进行的MVC系统需要用到记录操作日志和过滤特殊字符的功能,如果每个action中都调用记录日志的方法就太麻烦了,所以根据需要结合mvc的过滤机制 写了个特殊字符验证与记录操作日志的公用类: pub ...

  7. DB2不记录事务日志

    1. DB2大数据处理不记录事务日志步骤:  建表需要添加属性“NOT LOGGED INITIALLY”  在大批量更改操作的同一个事务开始时执行:“ALTER TABLE tabname ACTI ...

  8. MVC4.0 利用HandleErrorAttribute和log4net实现记录异常日志功能

    1.MVC4.0中HandleErrorAttribte已经帮我们处理了异常问题,当我们新建一个非空的MVC项目时候,在FilterConfig中会发现这样的代码 public class Filte ...

  9. Serilog记录MongoDB日志报错:requires the binary sub type to be UuidLegacy, not UuidStandard

    Serilog Serilog是.NET开源结构化日志类库 开源地址:https://github.com/serilog 官网:https://serilog.net/ Serilog能做什么: 记 ...

随机推荐

  1. PHP博大精深,入门容易,精通难,怎么才能真正学好PHP

    基础最重要  (1)熟悉HTML/CSS/JS等网页基本元素,完成阶段可自行制作完整的网页,对元素属性达到熟悉程度  (2)理解动态语言的概念,运做机制,熟悉PHP语法  (3)学习如何将PHP与HT ...

  2. 解决centos7上system tools - setting无法打开的问题

    今天在centos7上安装中文输入法时,遇到system tools - setting无法打开的问题. 最后定位时libwbclient这个包无法查找到的原因. 问题显示如下: 可以使用以下方式安装 ...

  3. MHA-Atlas-MySQL高可用集群2

    MHA脚本管理方式 (1)获取管理脚本master_ip_failover 提示:yum安装的manager是没有这个脚本的. 我们需要从manager的源码包里复制一个.   [root@mysql ...

  4. until和while 判断网段IP地址是否存在

    1.使用until和while分别实现192.168.0.0/24网段内,地址是否能够ping通,若ping通则输出"success!",若ping不通则输出"fail! ...

  5. 使用JenKins实现自动执行python脚本

    1.使用Jenkins创建一个工程,工程主要配置项参照下图,其他配置项恢复默认 2.工程配置完成之后,点击[立即构建],执行完成后进入到控制台查看是否执行成功.

  6. 1.使用脚本控制模型的移动 --《Unity 3D 游戏开发》笔记

    由于最新版的unity已经不支持javascript语言啦,本人又是个C#小白,所以记录一下自己写的脚本. first 创建一个模型,放在平面上,调整下角度,就像这样: 然后写一个脚本来控制模型移动: ...

  7. Oracle开启监听缓慢问题

    现象: Oracle数据库中,使用lsnrctl开启.关闭监听或查看监听状态时,非常慢,可以通过断网的方式使动作马上完成. 在客户端使用plsql等方式连接数据库时,也是非常慢,同样也可以通过切换网络 ...

  8. JS制作图片切换

    <!DOCTYPE html> <html> <head> <title>纯JS制作简单的图片切换</title> <meta cha ...

  9. [R] Lexical & Dynamic Scoping / Execution & Calling environments / Closures

    Lexical Scoping :有Java繼承中呼叫子類時先生成父類的概念,呼叫函數後,系統會轉至其定義處,將其 environment 中所具有的東西(有些可能定義在外層)形成 Closure [ ...

  10. rust

    books--------------Rust 中文教程 RustPrimer http://wiki.jikexueyuan.com/project/rust-primer/any/any.html ...