.NET Core 中性能分析工具 MiniProfiler
介绍
作为一个开发人员,你知道如何分析自己开发的Api性能么?
在Visual Studio和Azure中, 我们可以使用Application Insight来监控项目。除此之外我们还可以使用一个免费工具Stackify Prefix,它允许追踪所有的Http请求, 这里有一篇博客讲解了如何使用Stackify Prefix(Scalable and Performant ASP.NET Core Web APIs: Profiling and Monitoring)。
本文我将引入另外一个工具MiniProfiler, 我将讲解如何将MiniProfiler集成到ASP.NET Core WebAPI中。
与Stackify Prefix相似,MiniProfiler也是一款免费的工具(官网地址:https://miniprofiler.com/dotnet/),你可以使用它精确的分析ASP.NET和ASP.NET Core应用程序的任何代码。
Tips: MiniProfiler在ASP.NET和控制台程序中也可以使用哦。
安装
我们可以使用Nuget来下载这个包。
PM> Install-Package MiniProfiler.AspNetCore.Mvc
配置Startup.cs
MiniProfiler配置起来很简单,只需要以下几步
在ConfigureServices方法中添加MiniProfiler服务#
public void ConfigureServices(IServiceCollection services)
{
services.AddMiniProfiler(options =>
options.RouteBasePath = "/profiler"
);
}
1、这里是配置了MiniProfiler的路由基础路径,默认的路径是/mini-profiler-resources
2、按照当前配置,你可以使用"/profiler/results"来访问分析报告
激活中间件,启用MiniProfiler服务#
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiniProfiler();
}
配置需要监控分析的代码
public class ValueController : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
string url1 = string.Empty;
string url2 = string.Empty;
using (MiniProfiler.Current.Step("Get方法"))
{
using (MiniProfiler.Current.Step("准备数据"))
{
using (MiniProfiler.Current.CustomTiming("SQL", "SELECT * FROM Config"))
{
// 模拟一个SQL查询
Thread.Sleep(500);
url1 = "https://www.baidu.com";
url2 = "https://www.sina.com.cn/";
}
}
using (MiniProfiler.Current.Step("使用从数据库中查询的数据,进行Http请求"))
{
using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url1))
{
var client = new WebClient();
var reply = client.DownloadString(url1);
}
using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url2))
{
var client = new WebClient();
var reply = client.DownloadString(url2);
}
}
}
return new string[] { "value1", "value2" };
}
}
代码解释:
MiniProfiler.Current.Step方法定义了分析的步骤,这个方法可以接受一个String类型的参数,它会显示在最终的报告中MiniProfiler.Current.CustomTiming方法是更细粒度的对报告内容进行分类,以上代码中定义了2种分类,一种是SQL, 一种是Http- 上述程序的功能: 模拟从数据库拉取2个网站的Url, 并使用
WebClient来分别请求网站的Url
查看效果#
下面我们启动项目, 项目默认打开/api/values
然后我们来访问以下/profiler/results, 就会出现如下页面
如上图所示,我们可以很清楚的看到代码中每一部分的耗时,由于我们添加了2种分类SQL和Http,所以列表中会对2种分类进行汇总。
重点: 当前页面只会显示最近的一次请求
从当前报告中可以得到以下结论
- 当前请求总响应时间 1723.6ms
- SQL语句查询耗时517.ms
- 2次Http请求共耗时868.3ms, 其中访问百度耗时424.6ms, 访问新浪耗时443.7ms
如何让MiniProfiler与Swagger集成
这里我们就不再讲如何在ASP.NET Core中整合Swagger。
MiniProfiler和Swagger是可以集成在一起的,为了完成这个功能,我们需要进行以下几步
下载Swagger自定义页面#
默认的index.html页面可以从如下链接下载
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>%(DocumentTitle)</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css">
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
</style>
%(HeadContent)
</head>
<body>
<div id="swagger-ui"></div>
<!-- Workaround for https://github.com/swagger-api/swagger-editor/issues/1371 -->
<script>
if (window.navigator.userAgent.indexOf("Edge") > -1) {
console.log("Removing native Edge fetch in favor of swagger-ui's polyfill")
window.fetch = undefined;
}
</script>
<script src="./swagger-ui-bundle.js"></script>
<script src="./swagger-ui-standalone-preset.js"></script>
<script>
/* Source: https://gist.github.com/lamberta/3768814
* Parse a string function definition and return a function object. Does not use eval.
* @param {string} str
* @return {function}
*
* Example:
* var f = function (x, y) { return x * y; };
* var g = parseFunction(f.toString());
* g(33, 3); //=> 99
*/
function parseFunction(str) {
if (!str) return void (0);
var fn_body_idx = str.indexOf('{'),
fn_body = str.substring(fn_body_idx + 1, str.lastIndexOf('}')),
fn_declare = str.substring(0, fn_body_idx),
fn_params = fn_declare.substring(fn_declare.indexOf('(') + 1, fn_declare.lastIndexOf(')')),
args = fn_params.split(',');
args.push(fn_body);
function Fn() {
return Function.apply(this, args);
}
Fn.prototype = Function.prototype;
return new Fn();
}
window.onload = function () {
var configObject = JSON.parse('%(ConfigObject)');
var oauthConfigObject = JSON.parse('%(OAuthConfigObject)');
// Workaround for https://github.com/swagger-api/swagger-ui/issues/5945
configObject.urls.forEach(function (item) {
if (item.url.startsWith("http") || item.url.startsWith("/")) return;
item.url = window.location.href.replace("index.html", item.url).split('#')[0];
});
// If validatorUrl is not explicitly provided, disable the feature by setting to null
if (!configObject.hasOwnProperty("validatorUrl"))
configObject.validatorUrl = null
// If oauth2RedirectUrl isn't specified, use the built-in default
if (!configObject.hasOwnProperty("oauth2RedirectUrl"))
configObject.oauth2RedirectUrl = (new URL("oauth2-redirect.html", window.location.href)).href;
// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";
// Parse and add interceptor functions
var interceptors = JSON.parse('%(Interceptors)');
if (interceptors.RequestInterceptorFunction)
configObject.requestInterceptor = parseFunction(interceptors.RequestInterceptorFunction);
if (interceptors.ResponseInterceptorFunction)
configObject.responseInterceptor = parseFunction(interceptors.ResponseInterceptorFunction);
// Begin Swagger UI call region
const ui = SwaggerUIBundle(configObject);
ui.initOAuth(oauthConfigObject);
// End Swagger UI call region
window.ui = ui
}
</script>
</body>
</html>
下载之后将这个文件放置到项目根目录下。
接下来我们需要在这个文件的头部加入如下脚本代码:
<script async="async" id="mini-profiler" src="/profiler/includes.min.js?v=4.0.138+gcc91adf599"
data-version="4.0.138+gcc91adf599" data-path="/profiler/"
data-current-id="4ec7c742-49d4-4eaf-8281-3c1e0efa748a" data-ids="" data-position="Left"
data-authorized="true" data-max-traces="15" data-toggle-shortcut="Alt+P"
data-trivial-milliseconds="2.0" data-ignored-duplicate-execute-types="Open,OpenAsync,Close,CloseAsync">
</script>
最后我们需要配置这个index.html文件的Bulid Action为Embedded resource
安装自定义页面#
在Startup.cs文件中,我们需要修改UseSwaggerUI中间件的配置,这里我们需要添加一个InputStream配置。
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("MiniProfilerSample.index.html");
});
注意:这里
MiniProfilerSample是项目的命名空间名
最终效果#
重新启动项目,Swagger文档页面的左上角就出现了一个小的面板,当模拟请求一个连接之后,它就会显示出当前请求的分析数据,看起来是不是很酷炫。
总结
本篇博客描述了如何使用MiniProfiler来监控分析你的Api。 MiniProfiler除了提供网页显示报告,还支持将报告结果存储在数据库中,后面我会补充一篇文章来说明如何将报告保存到数据库中。
本篇源代码: https://github.com/lamondlu/Sample_MiniProfiler
原文地址 :https://www.cnblogs.com/lwqlun/p/10222505.html#配置需要监控分析的代码




浙公网安备 33010602011771号