1.看似针对同样一段查询表ef达式,重复执行却没有被记录下来。其实这是正常情况,因为ef并没有重复去执行 相同sql查询。

2.MiniProfiler结合MVC过滤器进行 拦截记录Sql,示例代码:

using Mobile360.Core;
using Mobile360.Core.Interfaces;
using Mobile360.Core.Models;
using Mobile360.Web.Common;
using Newtonsoft.Json.Linq;
using StackExchange.Profiling;
using StackExchange.Profiling.Storage;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc; namespace Mobile360.Web
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class OperationHandlerAttribute : FilterAttribute,IActionFilter, IExceptionFilter
{
private IRepository repo; /// <summary>
/// 模块描述
/// </summary>
public string ModuleName { get; set; } /// <summary>
/// 方法名称
/// </summary>
public string ActionName { get; set; } /// <summary>
/// 方法描述
/// </summary>
public string ActionDescription { get; set; } /// <summary>
/// 控制器名称
/// </summary>
public string ControllerName { get; set; } /// <summary>
/// 方法参数
/// </summary>
public string ActionParameters { get; set; } /// <summary>
/// 访问时间
/// </summary>
public DateTime AccessDate { get; set; } /// <summary>
/// 操作备注
/// </summary>
public string OperationRemark { get; set; } /// <summary>
/// 是否记录入库
/// </summary>
public bool IsLog { get; set; } /// <summary>
/// 操作人id
/// </summary>
public int OperatorId { get; set; } /// <summary>
/// 操作人名
/// </summary>
public string OperatorName { get; set; } public OperationHandlerAttribute()
{
this.AccessDate = DateTime.Now;
this.IsLog = true;
this.repo = DependencyResolver.Current.GetService<IRepository>();
} /// <summary>
/// 操作日志记录
/// </summary>
/// <param name="option">操作动作描述</param>
/// <param name="remark">其他备注</param>
public OperationHandlerAttribute(string actionDescription , string remark = "")
{
this.AccessDate = DateTime.Now;
this.IsLog = true;
//this.ModuleName = moduleName;
this.OperationRemark = remark;
this.ActionDescription = actionDescription;
this.repo = DependencyResolver.Current.GetService<IRepository>();
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
if (this.IsLog)
{
MiniProfiler.Start(); this.OperatorName = filterContext.HttpContext.User.Identity.Name; this.ActionName = filterContext.ActionDescriptor.ActionName;
this.ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
IDictionary<string, object> dic = filterContext.ActionParameters;
var parameters = new System.Text.StringBuilder();
foreach (var item in dic)
{
parameters.Append(item.Key + "=" + Json.Encode(item.Value) + "|");
}
this.ActionParameters = parameters.ToString(); }
} void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
if (this.IsLog)
{
MiniProfiler.Stop();
string efSqlStr2Json = MiniProfiler.Current.Root.CustomTimingsJson; AuditLog log = new AuditLog();
log.AuditAccount = string.IsNullOrEmpty(this.OperatorName)?"(未登录用户)": this.OperatorName;
log.Action = this.ActionName;
log.ActionDescription = this.ActionDescription;
log.Controller = this.ControllerName;
log.Parameters = this.ActionParameters;
log.StartTime = this.AccessDate;
log.SqlQuery = efSqlStr2Json;
log.EndTime = DateTime.Now;
log.Result = true;
log.IP = IPHelper.GetRealIP(); repo.Insert<AuditLog>(log);
repo.SaveChanges();
}
} #region IExceptionFilter 成员
void IExceptionFilter.OnException(ExceptionContext context)
{
if (ConfigurationManager.AppSettings["IsDev"] == "true")
{
throw new Exception(context.Exception.Message, context.Exception);
} SystemLog slog = new SystemLog();
slog.Action = this.ActionName;
slog.Level = (int)SystemLogType.ERROR;
slog.LoginAccount = this.OperatorName;
slog.Message = BuildExceptionInfo(context);
slog.OccurTime = DateTime.Now; repo.Insert<SystemLog>(slog);
repo.SaveChanges(); JObject jsonResult = new JObject(); //返回的json数据
jsonResult.Add(new JProperty("Code", -));
jsonResult.Add(new JProperty("Msg", "系统发生异常,请查看内部日志"));
ContentResult cr = new ContentResult();
cr.Content = jsonResult.ToString();
cr.ContentType = "application/json";
context.Result = cr;
context.ExceptionHandled = true;
} private string BuildExceptionInfo(ExceptionContext context)
{
var sb = new StringBuilder();
var req = context.HttpContext.Request;
sb.AppendLine(String.Format("处理对“{0}”的“{1}”请求时发生了异常", req.RawUrl, req.HttpMethod));
sb.AppendLine("以下是参数的信息:");
this.AppendRequestLine(sb, req.QueryString);
this.AppendRequestLine(sb, req.Form);
sb.AppendLine("以下是异常的信息:");
sb.AppendLine(context.Exception.ToString());
//sb.AppendLine(context.Exception.StackTrace.ToString()); return sb.ToString();
} private void AppendRequestLine(StringBuilder sb, NameValueCollection coll)
{
for (int i = ; i < coll.Count; i++)
{
sb.AppendFormat("{0}: {1}", coll.Keys[i], coll[i]);
sb.AppendLine();
}
} #endregion }
}

3.以上的miniprofiler并不能 拦截到 sql语句查询,需要使用 minprofiler 封装的ado.net对象。

 /// <summary>
/// 执行自定义SQL(创建、更新、删除操作)
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="commandText"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public async Task<int> ExecuteSqlCommandAsync(string commandText, params object[] parameters)
{
var connection1 = this.Database.Connection;//使用EF的sql连接对象。统一管理。
if (connection1 != null)
{
DbCommand command = new SqlCommand();
ProfiledDbCommand prcommand = new ProfiledDbCommand(command, connection1, MiniProfiler.Current);
prcommand.CommandType = CommandType.Text;
prcommand.CommandText = commandText;
prcommand.Parameters.AddRange(parameters);
prcommand.Connection = connection1; if (connection1.State == ConnectionState.Closed)
connection1.Open(); return await prcommand.ExecuteNonQueryAsync();
}
return ;
}
ProfiledDbCommand,
ProfiledDbConnection等对象都是MiniProfiler的对象。这样才能抓到 Sql语句。

4.由于miniprofiler是用来性能调优的,用来做审计日志记录(包括哪个用户最终生成的sql查询)看似并不合适,非常耗性能。
所以,我们并没有准备去使用它来获取Sql语句。 运用在
Application_BeginRequest和
Application_EndRequest
期间用EF6.0版本以上才有的 拦截器接口
DbCommandInterceptor
拦截的所有sql语句作为一次请求的sql查询语句 来作为尝试,不知道这样有啥劣势不?  希望有尝试过的 前辈 指点。
												

MiniProfiler使用点滴记录-2017年6月23日11:08:23的更多相关文章

  1. 读C#开发实战1200例子记录-2017年8月14日11:20:38获取汉字编码值

    try { char chr = textBox1.Text[0]; byte[] gb2312_bt = Encoding.GetEncoding("gb2312").GetBy ...

  2. 读C#开发实战1200例子记录-2017年8月14日10:03:55

    C# 语言基础应用,注释 "///"标记不仅仅可以为代码段添加说明,它还有一项更重要的工作,就是用于生成自动文档.自动文档一般用于描述项目,是项目更加清晰直观.在VisualStu ...

  3. 猖獗的假新闻:2017年1月1日起iOS的APP必须使用HTTPS

    一.假新闻如此猖獗 刚才一位老同事 打电话问:我们公司还是用的HTTP,马上就到2017年了,提交AppStore会被拒绝,怎么办? 公司里已经有很多人问过这个问题,回答一下: HTTP还是可以正常提 ...

  4. [转载]Ubuntu17.04(Zesty Zapus)路线图发布:2017年4月13日发布

    Canonical今天公布了Ubuntu 17.04(Zesty Zapus)操作系统的发布路线图,该版本于今年10月24日上线启动,toolchain已经上传且首个daily ISO镜像已经生成.面 ...

  5. 2017年1月5日 星期四 --出埃及记 Exodus 21:31

    2017年1月5日 星期四 --出埃及记 Exodus 21:31 This law also applies if the bull gores a son or daughter.牛无论触了人的儿 ...

  6. 2017年1月4日 星期三 --出埃及记 Exodus 21:30

    2017年1月4日 星期三 --出埃及记 Exodus 21:30 However, if payment is demanded of him, he may redeem his life by ...

  7. 2017年1月3日 星期二 --出埃及记 Exodus 21:29

    2017年1月3日 星期二 --出埃及记 Exodus 21:29 If, however, the bull has had the habit of goring and the owner ha ...

  8. 2017年1月2日 星期一 --出埃及记 Exodus 21:28

    2017年1月2日 星期一 --出埃及记 Exodus 21:28 "If a bull gores a man or a woman to death, the bull must be ...

  9. 2017年1月1日 星期日 --出埃及记 Exodus 21:27

    2017年1月1日 星期日 --出埃及记 Exodus 21:27 And if he knocks out the tooth of a manservant or maidservant, he ...

随机推荐

  1. Java IO最详解

    初学java,一直搞不懂java里面的io关系,在网上找了很多大多都是给个结构图草草描述也看的不是很懂.而且没有结合到java7 的最新技术,所以自己来整理一下,有错的话请指正,也希望大家提出宝贵意见 ...

  2. AOJ/堆与动态规划习题集

    ALDS1_9_A-CompleteBinaryTree. Codes: //#define LOCAL #include <cstdio> int parent(int i) { ret ...

  3. DOM4J案例详解(添加 ,查询 ,删除 ,保存)

    先看一下XML文档 <?xml version="1.0" encoding="gb2312"?> <exam> <student ...

  4. poj3159 Candies SPFA

    题目链接:http://poj.org/problem?id=3159 题目很容易理解 就是简单的SPFA算法应用 刚开始用STL里的队列超时了,自己写了个栈,果断过,看来有时候栈还是快啊.... 代 ...

  5. 关于开发微信小程序后端linux使用xampp配置https

    关于开发微信小程序后端linux使用xampp配置https 背景 由于最近开发微信小程序,前后端交互需要使用https协议,故需要配置https服务 服务器环境 服务器系统 ubuntu 环境 xa ...

  6. vue.js应用开发笔记

    看vue.js有几天了,之前也零零散散的瞅过,不过一直没有动手去写过demo,这几天后台事比较少,一直在讨论各种需求(其实公司对需求还是比较重视与严谨的,一个项目需求讨论就差不多一周了,这要搁之前,天 ...

  7. redis安装学习

    Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理.它支持字符串.哈希表.列表.集合.有序集合,位图,hyperloglogs等数据类型.内置复制.Lu ...

  8. javaWeb基础核心之一Servlet

    既然是做JAVA开发的,先从一些基本的整理起来,算是知识回顾,加深记忆. 第一篇想到那理到哪,可能有点乱,不是太会排版,见谅,估计可能也就我自己看的懂. servlet在百度百科上的定义是这样的: S ...

  9. hive网站日志数据分析

    一.说在前面的话 上一篇,楼主介绍了使用flume集群来模拟网站产生的日志数据收集到hdfs.但我们所采集的日志数据是不规则的,同时也包含了许多无用的日志.当需要分析一些核心指标来满足系统业务决策的时 ...

  10. 1、在eclipse中导入Java的jar包方法---JDBC【图文说明】

    1.Eclipse环境下jar包导入 在Eclipse环境下编写Java程序,常常会借用到各种jar包.如:连接数据库时,导入jar包是必须的.导入方法如下: 1.打开eclipse,右击要导入jar ...