API接口利用ActionFilterAttribute实现接口耗时检测
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实现接口耗时检测的更多相关文章
- .NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式
.Net Core 同 Asp.Net MVC一样有几种过滤器,这里不再赘述每个过滤器的执行顺序与作用. 在实际项目开发过程中,统一API返回值格式对前端或第三方调用将是非常必要的,在.NetCore ...
- 利用阿里大于接口发短信(Delphi版)
阿里大于是阿里通信旗下产品,融合了三大运营商的通信能力,提供包括短信.语音.流量直充.私密专线.店铺手机号等个性化服务.每条四分五,价钱还算公道,经老农测试,响应速度非常快,基本上是秒到.官方文档提供 ...
- Delphi Android ActivityManager(提供了接口, 利用它可以方便的对Memory, Processes, Task, Service 等进行管)
ActivityManager: 对Activity交互提供了接口, 利用它可以方便的对Memory, Processes, Task, Service 等进行管理,. 这里对Delphi接口进行 ...
- web api(基于NFine框架) 中接口跳转数据格式错误解决方案
using NFine.Code; using NFine.Domain; using System.Web.Http; using Newtonsoft.Json; namespace Api.Co ...
- Java接口和抽象类以及接口的意义,instanceof的利用
接口interface: 1. 在接口中没有变量,成员无论如何定义,都是公共常量,public static final即使不显式声明也如此. 2. 所有接口方法均隐含public abstract即 ...
- .NET Core WEB API使用Swagger生成在线接口文档
1项目引用Swashbuckle.AspNetCore程序集和Microsoft.Extensions.PlatformAbstractions程序集 右击项目打开"管理NuGet程序包.. ...
- 利用jQuery扩展接口为jQuery框架定义了两个自定义函数,然后调用这两个函数
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码
第三百三十五节,web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码 打码接口文件 # -*- coding: cp936 -*- import sys import os ...
- java实现利用httpclient访问接口
HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...
随机推荐
- 使用create-react-app创建项目(二)——引入ant方法(一)
扩展项目(需要创建git默认文件) 具体步骤如下: a.git init b.git add . c.git commit -m "..." n ...
- Nginx之configure选项
1. 通用配置项 --prefix=<path>:Nginx 安装的根路径,所有其他的路径都要依赖于该选项. --sbin-path=<path>:指定 Nginx 二进制文件 ...
- tp5 模型关联,多表联查实用方法
1.模型中建立关联关系 public function goods(){ return $this->belongsTo('app\common\model\goods\Goods', 'goo ...
- easyUI之表单
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...
- 008-ICMP协议(网络控制文协议)
一.概述 ICMP是(Internet Control Message Protocol)Internet控制报文协议.它是TCP/IP协议簇的一个子协议,用于在IP主机.路由器之间传递控制消息.控制 ...
- 一百一十六:CMS系统之使用阿里大于sdk发送短信验证码
阿里大于短信平台:https://dysms.console.aliyun.com/dysms.htm#/overview 使用教程:https://blog.csdn.net/qq103189393 ...
- python 实例方法、类方法和静态方法
#!/usr/bin/env python3.6 #-*- coding:utf-8 -*- # class Person(object): city = 'Beijing' def __init__ ...
- [转]Android使用WebView定位问题
文章转自:https://www.jianshu.com/p/d32d3641741f 最近遇到了一个问题,有一个需求是使用 WebView 来加载一个网页url,H5通过js来获取位置定位信息.以前 ...
- tomcat中的server.xml元素详解
附:Tomcat加载顺序 加载类和资源的顺序为: 1./Web-INF/classes 2./Web-INF/lib/*.jar 3.Bootstrap 4.System 5.$CATALINA_HO ...
- Pytorch-拼接与拆分
引言 本篇介绍tensor的拼接与拆分. 拼接与拆分 cat stack split chunk cat numpy中使用concat,在pytorch中使用更加简写的 cat 完成一个拼接 两个向量 ...