原文:.net core 下监控Sql的执行语句

最近在编写.net core程序,因为数据库从Sql Server 切换到 MySql的原因,无法直接查看sql的具体语句,随着业务量的剧增,痛苦也与日俱增,为了彻底解决该问题,我在github、stackoverflow等站点不断搜索,试图找到一个好的办法。

搜索的结果大都是这样的:

 SHOW VARIABLES LIKE "general_log%";
SET GLOBAL general_log = 'ON';

好嘞,试过以后发现果然灵验,BUT,我没有权限操作mysql的计算机,my god,此路不通~~~~

最近搜索时再次发现MiniProfiler库有更新~~

dotnet core支持不错,终于看到希望了~~~

那就开始集成吧,如果你是asp.net core工程,就参考文档吧,

如果是控制台程序,那就按照步骤开始吧:

step 1:安装nuget包 MiniProfiler.EntityFrameworkCore ,目前仍是alpha版本。

【step 2】: 开启EF core的监控初始化 ,如果你使用EF Core的话

 var initializer = new DiagnosticInitializer(new[] { new RelationalDiagnosticListener() });
initializer.Start();

【step 2】:开启Dapper的链接监控初始化,如果你使用Dapper的话

 

  

private DbConnection GetConnection()
{
    DbConnection conn = new MySqlConnection(MySqlDBContextOptionBuilder.GetDbConnectionString(DbInfo));
     if (MiniProfiler.Current != null)
     {
      conn = new StackExchange.Profiling.Data.ProfiledDbConnection(conn, MiniProfiler.Current);
     }
      conn.Open();
      return conn;
}

step 3:启动监控,在你的执行代码上增加如下代码

var profiler = MiniProfiler.StartNew(m);
using (profiler.Step("SqlProfile"))
{
   // 你的代码
}
// 输出日志
if (profiler?.Root != null)
{
  var p = profiler.Root;
  Trace.WriteLine($"{p.Name}:{p.Id},{p.DurationMilliseconds} ms");
  if (p.HasChildren)
  {
    p.Children.ForEach(x =>
    {
      Trace.WriteLine($"{p.Name}:{x.Name},st:{x.StartMilliseconds} ms,exec:{x.DurationMilliseconds} ms");
      if (x.CustomTimings?.Count > 0)
      {
        foreach (var ct in x.CustomTimings)
        {
          Trace.WriteLine($"{p.Name}:Start {ct.Key} ---  ");
          ct.Value?.ForEach(y =>
          {
            Trace.WriteLine($"{p.Name}:{y.CommandString}");
            Trace.WriteLine($"{p.Name}:Execute time :{y.DurationMilliseconds} ms,Start offset :{y.StartMilliseconds} ms,Errored :{y.Errored}");
          });
          Trace.WriteLine($"{p.Name}:End {ct.Key} ---  ");
        }
      }
    });
  }
} profiler?.StopAsync(true).ConfigureAwait(false);
var profiler = MiniProfiler.StartNew(m);
using (profiler.Step("SqlProfile"))
{
   // 你的代码
}
// 输出日志
if (profiler?.Root != null)
{
  var p = profiler.Root;
  Trace.WriteLine($"{p.Name}:{p.Id},{p.DurationMilliseconds} ms");
  if (p.HasChildren)
  {
    p.Children.ForEach(x =>
    {
      Trace.WriteLine($"{p.Name}:{x.Name},st:{x.StartMilliseconds} ms,exec:{x.DurationMilliseconds} ms");
      if (x.CustomTimings?.Count > 0)
      {
        foreach (var ct in x.CustomTimings)
        {
          Trace.WriteLine($"{p.Name}:Start {ct.Key} ---  ");
          ct.Value?.ForEach(y =>
          {
            Trace.WriteLine($"{p.Name}:{y.CommandString}");
            Trace.WriteLine($"{p.Name}:Execute time :{y.DurationMilliseconds} ms,Start offset :{y.StartMilliseconds} ms,Errored :{y.Errored}");
          });
          Trace.WriteLine($"{p.Name}:End {ct.Key} ---  ");
        }
      }
    });
  }
} profiler?.StopAsync(true).ConfigureAwait(false);

****

在此我向大家推荐一个微服务架构学习交流群。交流学习群号:864759589  里面会分享一些资深架构师录制的视频录像:高并发、高性能、分布式、微服务架构的原理,分布式架构等这些成为架构师必备的知识体系。


**** 

### 引用链接

1. [口袋代码仓库](http://codeex.cn)

2. [在线计算器](http://jisuanqi.codeex.cn)

3. 本节源码:[github](https://github.com/webmote-org/)

.net core 下监控Sql的执行语句的更多相关文章

  1. 监控SQL:执行表中所有sql语句、记录每个语句运行时间(3)

    原文:监控SQL:执行表中所有sql语句.记录每个语句运行时间(3) 通过执行一个 带参数的存储过程  exec  OpreateTB('OpreateUser','IsRun')  更新表的数据 表 ...

  2. SQL 2008执行语句遇到内存不足(1)——error 701

    原文:SQL 2008执行语句遇到内存不足(1)--error 701 转自:http://blogs.msdn.com/b/apgcdsd/archive/2011/01/17/sql-2008-e ...

  3. robot framework ——关键字run keyword if 如何在一个条件下接多个执行语句,以及如何写复杂条件句

    曾一度疯狂搜索run keyword if 的用法,帖子是挺多的,可惜,没有一个我想要的.现在我终于把我想要的用法,收集好了,在此总结下. 1.曾经天真的以为  run keyword if +条件 ...

  4. 拼接SQL执行语句时,对单引号的处理

    例: declare @SQL nvarchar(1000); declare @str nvarchar(100); set @str='Joe''s NB'; // 打印出来的应该是这样:Joe' ...

  5. SQL SERVER 执行计划各字段注释

    SET SHOWPLAN_ALL使 Microsoft® SQL Server™ 不执行 Transact-SQL 语句.相反,SQL Server 返回有关语句执行方式和语句预计所需资源的详细信息. ...

  6. 4.5 .net core下直接执行SQL语句并生成DataTable

    .net core可以执行SQL语句,但是只能生成强类型的返回结果.例如var blogs = context.Blogs.FromSql("SELECT * FROM dbo.Blogs& ...

  7. .net core下直接执行SQL语句并生成DataTable

    .net core可以执行SQL语句,但是只能生成强类型的返回结果.例如var blogs = context.Blogs.FromSql("SELECT * FROM dbo.Blogs& ...

  8. 应用Druid监控SQL语句的执行情况

    Druid是什么? Druid首先是一个数据库连接池.Druid是目前最好的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池,包括DBCP.C3P0.BoneCP.Proxool.JBo ...

  9. 浅析SqlServer简单参数化模式下对sql语句自动参数化处理以及执行计划重用

    我们知道,SqlServer执行sql语句的时候,有一步是对sql进行编译以生成执行计划, 在生成执行计划之前会去缓存中查找执行计划 如果执行计划缓存中有对应的执行计划缓存,那么SqlServer就会 ...

随机推荐

  1. bitmap2drawable-两者的转化实现

    先来看今天遇到的一个问题,是关于mms报错的.后来发现报的地方如下 Bitmap deleteBitMap = ((BitmapDrawable)mChipDelete).getBitmap(); D ...

  2. c#中反射的用法(即如何根据字符找到已定义的变量)

    2013-07-20 08:06 720人阅读 评论(0) 收藏 举报  分类: C#(9)  作者同类文章 X 版权声明:本文为博主原创文章,未经博主允许不得转载. 常常羡慕javascript中, ...

  3. MyBatis学习总结(14)——Mybatis使用技巧总结

    1. 区分 #{} 和 ${}的不同应用场景 1)#{} 会生成预编译SQL,会正确的处理数据的类型,而${}仅仅是文本替换. 对于SQL: select * from student where x ...

  4. 洛谷—— P1069 细胞分裂

    https://www.luogu.org/problem/show?pid=1069#sub 题目描述 Hanks 博士是 BT (Bio-Tech,生物技术) 领域的知名专家.现在,他正在为一个细 ...

  5. 1.1 Python基础知识 - 变量

    1.什么是变量? 变量是可以通过变量名访问的内存地址,变量通常是可变的. 2.怎样去定义? 变量格式: 变量名 = "变量值" 例如: name = "Zhanghk&q ...

  6. 微信支付v2开发(3) JS API支付

    本文介绍如何使用JS API支付接口完成微信支付. 一.JS API支付接口(getBrandWCPayRequest) 微信JS API只能在微信内置浏览器中使用,其他浏览器调用无效.微信提供get ...

  7. HDU 2063 过山车 第一道最大二分匹配

    http://acm.hdu.edu.cn/showproblem.php?pid=2063 题目大意: m个女生和n个男生一起做过山车,每一排必须一男一女,而每个女孩愿意和一些男生坐一起,, 你要找 ...

  8. (转)oracle表空间使用率统计查询

    转自:http://www.cnblogs.com/xwdreamer/p/3511047.html 参考文献 文献1:http://blog.itpub.net/24104518/viewspace ...

  9. swift项目第四天:动态加载控制器

    一:Appdelegate import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate ...

  10. vue学习笔记二:v-if和v-show的区别

    v-if vs v-show v-if 是“真正的”条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建. v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做—— ...