using System.Text;
|
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Http;
|
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.Hosting;
|
using StackExchange.Profiling;
|
using StackExchange.Profiling.Storage;
|
|
namespace KH.WMS.Core.Monitoring.MiniProfiler;
|
|
/// <summary>
|
/// MiniProfiler 配置
|
/// </summary>
|
public static class MiniProfilerSetup
|
{
|
/// <summary>
|
/// 添加 MiniProfiler 服务
|
/// </summary>
|
public static IServiceCollection AddMiniProfilerCustom(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
|
{
|
var miniProfilerSettings = configuration.GetSection("MiniProfiler").Get<MiniProfilerSettings>();
|
miniProfilerSettings ??= new MiniProfilerSettings();
|
|
// 调用官方 MiniProfiler 的扩展方法
|
services.AddMiniProfiler(options =>
|
{
|
options.RouteBasePath = miniProfilerSettings.RouteBasePath;
|
options.PopupRenderPosition = RenderPosition.BottomLeft;
|
options.PopupShowTimeWithChildren = true;
|
|
// 生产环境配置
|
if (!miniProfilerSettings.EnableInProduction && !environment.IsDevelopment())
|
{
|
options.ShouldProfile = _ => false;
|
}
|
else
|
{
|
// 开发环境或配置为启用时,分析所有请求
|
options.ShouldProfile = _ => true;
|
}
|
|
// 数据库优化
|
options.TrackConnectionOpenClose = miniProfilerSettings.TrackConnectionOpenClose;
|
|
});
|
|
return services;
|
}
|
|
/// <summary>
|
/// 使用 MiniProfiler 中间件
|
/// </summary>
|
public static IApplicationBuilder UseMiniProfilerCustom(this IApplicationBuilder app)
|
{
|
app.UseMiniProfiler();
|
return app;
|
}
|
}
|
|
/// <summary>
|
/// MiniProfiler 配置选项
|
/// </summary>
|
public class MiniProfilerSettings
|
{
|
/// <summary>
|
/// 路由基础路径
|
/// </summary>
|
public string RouteBasePath { get; set; } = "/profiler";
|
|
/// <summary>
|
/// 是否在生产环境启用
|
/// </summary>
|
public bool EnableInProduction { get; set; } = false;
|
|
/// <summary>
|
/// 是否跟踪数据库连接
|
/// </summary>
|
public bool TrackConnectionOpenClose { get; set; } = true;
|
|
/// <summary>
|
/// 堆栈跟踪长度
|
/// </summary>
|
public int StackTraceLength { get; set; } = 5;
|
}
|