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. centos7 安装mysql出现Could NOT find Curses (missing CURSES_LIBRARY CURSES_INCLUDE_PATH)

    今天安装mysql 5.7 编译时出现一下问题: [root@localhost software]# cd mysql-5.7.21 [root@localhost mysql-5.7.21]# c ...

  2. Oracle12c的安装

    直接下一步不多说高级安装可以选择设置,嫌麻烦可以直接典型安装(少些设置步骤)这里随便命用户名,口令即密码此处可以改安装路径可以根据电脑自身配置更改,但建议高于20%(给的越少,Oracle运行速度越慢 ...

  3. temporal credit assignment in reinforcement learning 【强化学习 经典论文】

    Sutton 出版论文的主页: http://incompleteideas.net/publications.html Phd  论文:   temporal credit assignment i ...

  4. Centos7.5系统 SSH升级到7.9

    SSH7.9安装 #!/bin/bash#删除旧版ssh包 危险操作,不删除也可以安装,建议跳过此操作.#rpm -e `rpm -qa | grep openssh` #安装zlib依赖包wget ...

  5. mysql免安装版的下载与安装

    下载 打开:https://www.mysql.com/downloads/ 1.点击该项:

  6. 并发编程心得--synchronized

    根据业务需求解决并完善并发问题-- IWMS仓库系统不考虑并发那么大的情况下,我想到的有2种并发解决方案. 1.在同时请求时,给需要操作的保存接口添加synchronized 同步方式,同步保存方法, ...

  7. Python:从入门到实践--第十一章--测试代码--练习

    #1.城市和国家:编写一个函数,它接受两个形参:一个城市名和一个国家名. #这个函数返回一个格式为City,Country的字符串,如Santiago,Chile.将这个函数 #存储在一个名为city ...

  8. JPA、Hibernate框架、通用mapper之间的关系及通用mapper的具体实现

    JPA是描述对象-关系表的映射关系,将运行期实体对象持久化到数据库中,提出以面向对象方式操作数据库的思想. Hibernate框架核心思想是ORM-实现自动的关系映射.缺点:由于关联操作提出Hql语法 ...

  9. 设计简单的VB程序

    1.模拟对话程序 [程序源码] Option Explicit Private Sub Command1_Click() Text2.Text = "" Text1.Text = ...

  10. Java线程池不错的总结博客

    ImportNew线程池总结 Java多线程之Executor.ExecutorService.Executors.Callable.Future与FutureTask 线程池,这一篇或许就够了