miniprofiler的对数据库的监测使用。以nancy,petapoco为例

miniprofiler的使用


miniprofiler的详细介绍请看这里http://miniprofiler.com/。(可以对数据库和页面等监控如 ado ef mvc mongodb)

本文以nancy和petapoco为示例


安装

Install-Package MiniProfiler

你也可以使用其他的类库,如MiniProfiler.EF6 MiniProfiler.WCF MiniProfiler.MongoDb MiniProfiler.MongoDb之类的。我用的是petapoco,所以用Install-Package MiniProfiler就可以了

数据库部分

在petapoco.cs的类中修改如下

 public void OpenSharedConnection()
    {
        if (_sharedConnectionDepth == 0)
        {
            _sharedConnection = _factory.CreateConnection();
            _sharedConnection.ConnectionString = _connectionString;
            //MiniProfiler  加入MiniProfiler
            _sharedConnection=   new StackExchange.Profiling.Data.ProfiledDbConnection(  (DbConnection)  _sharedConnection      , MiniProfiler.Current);
            
            if (_sharedConnection.State == ConnectionState.Broken)
            { _sharedConnection.Close(); }
            
            if (_sharedConnection.State == ConnectionState.Closed)
            { _sharedConnection.Open(); }
            
            _sharedConnection = OnConnectionOpened(_sharedConnection);
            
            if (KeepConnectionAlive)
            { _sharedConnectionDepth++; } // Make sure you call Dispose
        }
        
        _sharedConnectionDepth++;
    }

其实就是替换_sharedConnection= new StackExchange.Profiling.Data.ProfiledDbConnection( (DbConnection) _sharedConnection , MiniProfiler.Current);
官方的文档

public static DbConnection GetOpenConnection()
{
    var cnn = CreateRealConnection(); // A SqlConnection, SqliteConnection ... or whatever

    // wrap the connection with a profiling connection that tracks timings 
    return new StackExchange.Profiling.Data.ProfiledDbConnection(cnn, MiniProfiler.Current);
}

Bootstrapper部分 RequestStartup的方法中如下:

  protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
    {
       
        //MiniProfiler
        MiniProfiler.Start();
        //请求结束后,停止miniprofiler
        pipelines.AfterRequest.AddItemToEndOfPipeline(
            (ctx) =>
        {
            MiniProfiler.Stop();
        });
    }
    

module部分

假设你的module叫MiniProfiler。
主要字符串的编码。

  Get["/MiniProfiler"] = _ =>
        {
            var renderStr = StackExchange.Profiling.MiniProfiler.RenderIncludes().ToString();
            return View["MiniProfiler", renderStr];
        };
        

视图部分

主要字符串的编码。Html.Raw是htmldecode的作用

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@{
    Layout = null;
}
<!doctype html>
<html lang="zh-cn">
<head>
</head>
<body>
 @Html.Raw(Model)
</body>
</html>

查看 http://localhost:9777/miniprofiler

结果类似如下

30.0 ms
6.6 ms
1.1 ms
17.5 ms
14114.3 ms
537.0 ms

点击进去可以查看加载时间。以及调用的sql语句等。

原文地址:https://www.cnblogs.com/wang2650/p/5735836.html