1.主要代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace ZMAPI.Controllers
{
/// <summary>
/// 监控接口执行时间
/// </summary>
public class TimingActionFilter : ActionFilterAttribute
{
//private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private const string Key = "__action_duration__"; /// <summary>
/// 启用计时器
/// </summary>
/// <param name="actionContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
/*
await Trace.WriteAsync("Executing action named {0} for request {1}.",
actionContext.ActionDescriptor.ActionName,actionContext.Request.GetCorrelationId());
*/
if (SkipLogging(actionContext))
{
return base.OnActionExecutingAsync(actionContext, cancellationToken);
}
var stopWatch = new Stopwatch();
actionContext.Request.Properties[Key] = stopWatch;
stopWatch.Start();
return base.OnActionExecutingAsync(actionContext, cancellationToken);
} /// <summary>
/// 记录监控接口执行日志
/// </summary>
/// <param name="actionExecutedContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
{
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
}
var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
if (stopWatch != null)
{
stopWatch.Stop();
var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; string log = string.Format("方法名:【{0}】 - 请求类型:【{1}】 消耗时间(毫秒):【{2}】", controllerName, actionName, stopWatch.ElapsedMilliseconds);
#if DEBUG
Debug.Print(log);
#endif
//logger.Info(log);
Log(stopWatch.ElapsedMilliseconds.ToZMInt32(),log);
}
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
} private static bool SkipLogging(HttpActionContext actionContext)
{
return actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<NoLogAttribute>().Any();
} public void Log(int stopWatch, string log)
{
if (stopWatch >= )
{
Serious_log(log);
}
else if (stopWatch >= )
{
Ordinary_log(log);
}
} /// <summary>
/// 严重日志
/// </summary>
public void Serious_log(string log)
{
Tools.PublicConfig.log_Append("接口调用时间监控: " + log, "ApiLog/API_Warning", DateTime.Now.ToString("yyyyMMdd") + "_API_Warning.log");
} /// <summary>
/// 普通日志
/// </summary>
public void Ordinary_log(string log)
{
Tools.PublicConfig.log_Append("接口调用时间监控: " + log, "ApiLog/API_Time", DateTime.Now.ToString("yyyyMMdd") + "_API.log");
}
} /// <summary>
/// 不记录监控接口执行日志
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
public class NoLogAttribute : Attribute
{ } }

2.WebApiConfig中启用

public static void Register(HttpConfiguration config)
{
  //启用监控接口执行时间
  config.Filters.Add(new TimingActionFilter());   //默认路由
  config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
  );
}

API接口利用ActionFilterAttribute实现接口耗时检测的更多相关文章

  1. .NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式

    .Net Core 同 Asp.Net MVC一样有几种过滤器,这里不再赘述每个过滤器的执行顺序与作用. 在实际项目开发过程中,统一API返回值格式对前端或第三方调用将是非常必要的,在.NetCore ...

  2. 利用阿里大于接口发短信(Delphi版)

    阿里大于是阿里通信旗下产品,融合了三大运营商的通信能力,提供包括短信.语音.流量直充.私密专线.店铺手机号等个性化服务.每条四分五,价钱还算公道,经老农测试,响应速度非常快,基本上是秒到.官方文档提供 ...

  3. Delphi Android ActivityManager(提供了接口, 利用它可以方便的对Memory, Processes, Task, Service 等进行管)

    ActivityManager:   对Activity交互提供了接口, 利用它可以方便的对Memory, Processes, Task, Service 等进行管理,. 这里对Delphi接口进行 ...

  4. web api(基于NFine框架) 中接口跳转数据格式错误解决方案

    using NFine.Code; using NFine.Domain; using System.Web.Http; using Newtonsoft.Json; namespace Api.Co ...

  5. Java接口和抽象类以及接口的意义,instanceof的利用

    接口interface: 1. 在接口中没有变量,成员无论如何定义,都是公共常量,public static final即使不显式声明也如此. 2. 所有接口方法均隐含public abstract即 ...

  6. .NET Core WEB API使用Swagger生成在线接口文档

    1项目引用Swashbuckle.AspNetCore程序集和Microsoft.Extensions.PlatformAbstractions程序集 右击项目打开"管理NuGet程序包.. ...

  7. 利用jQuery扩展接口为jQuery框架定义了两个自定义函数,然后调用这两个函数

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. 第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码

    第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码 打码接口文件 # -*- coding: cp936 -*- import sys import os ...

  9. java实现利用httpclient访问接口

    HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...

随机推荐

  1. 工具类注入需要的service

    /** * 从redis获取信息 * @author yy * */ @Component//关键一:添加此注解才能被spring扫描到 public class CacheUtil { privat ...

  2. PyTorch中使用深度学习(CNN和LSTM)的自动图像标题

    介绍 深度学习现在是一个非常猖獗的领域 - 有如此多的应用程序日复一日地出现.深入了解深度学习的最佳方法是亲自动手.尽可能多地参与项目,并尝试自己完成.这将帮助您更深入地掌握主题,并帮助您成为更好的深 ...

  3. python安装appium模块

    (base) localhost:~ ligaijiang$ pip3 install Appium-Python-Client Collecting Appium-Python-Client Dow ...

  4. npm 权限

    将npm默认目录定向到其他你具有读写权限的目录 很多时候你可能并不想改变npm所用的默认目录(如/usr)的拥有者,因为这可能会导致一些问题,比如你在与其他用户共用此系统时. 这时,你可以设置npm整 ...

  5. LC 970. Powerful Integers

    Given two non-negative integers x and y, an integer is powerful if it is equal to x^i + y^j for some ...

  6. React Native布局详解

    Flexbox 布局 Flex有两个属性:Container  和 Item flex是Flexible Box的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性.采用fle ...

  7. WPF学习笔记 - 如何用WPF创建单实例应用程序

    使用一个已命名的(操作系统范围的)互斥量. bool mutexIsNew; using(System.Threading.Mutex m = new System.Threading.Mulex(t ...

  8. 原生vue实现表格的编辑,包括单元格合并,拆分,删除行/列, 添加行/列

    先看效果图如下:  代码看这里: https://github.com/YalongYan/vue-table-edit

  9. Latex新手学习

    1.Latex 套装下载安装 http://www.ctex.org/CTeXDownload 选择镜像稳定版 下载安装后 2.一个简单的例子 (1)打开WinEdt (2)新建一个文档 \docum ...

  10. NFS PersistentVolume(8)

    一.部署nfs服务端: k8s-master 节点上搭建了 NFS 服务器 (1)安装nfs服务: yum install -y nfs-utils rpcbind vim /etc/exports ...