EntityFramework优化:SQL语句日志
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Text;
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
using System.Data.Common; using NLog; namespace Libing.Portal.Web.Common.Interceptors
{
public class NLogDbCommandInterceptor : DbCommandInterceptor
{
private static readonly Stopwatch watch = new Stopwatch();
private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuting(command, interceptionContext); watch.Restart();
} public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
watch.Stop(); if (interceptionContext.Exception != null)
{
logger.Error("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
StringBuilder message = new StringBuilder();
message.AppendFormat("\r\n-->{0}", command.CommandText);
foreach (DbParameter parameter in command.Parameters)
{
message.AppendFormat("\r\n-- {0}: '{1}' (Type = {2}, IsNullable = {3})", parameter.ParameterName, parameter.Value, parameter.DbType, parameter.IsNullable);
}
message.AppendFormat("\r\n-- Completed in {0} ms", watch.ElapsedMilliseconds, command); logger.Trace(message.ToString());
} base.ScalarExecuted(command, interceptionContext);
} public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuting(command, interceptionContext); watch.Restart();
} public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
watch.Stop(); if (interceptionContext.Exception != null)
{
logger.Error("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
StringBuilder message = new StringBuilder();
message.AppendFormat("\r\n-->{0}", command.CommandText);
foreach (DbParameter parameter in command.Parameters)
{
message.AppendFormat("\r\n-- {0}: '{1}' (Type = {2}, IsNullable = {3})", parameter.ParameterName, parameter.Value, parameter.DbType, parameter.IsNullable);
}
message.AppendFormat("\r\n-- Completed in {0} ms", watch.ElapsedMilliseconds, command); logger.Trace(message.ToString());
} base.NonQueryExecuted(command, interceptionContext);
} public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
base.ReaderExecuting(command, interceptionContext); watch.Restart();
} public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
watch.Stop(); if (interceptionContext.Exception != null)
{
logger.Error("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
StringBuilder message = new StringBuilder();
message.AppendFormat("\r\n-->{0}", command.CommandText);
foreach (DbParameter parameter in command.Parameters)
{
message.AppendFormat("\r\n-- {0}: '{1}' (Type = {2}, IsNullable = {3})", parameter.ParameterName, parameter.Value, parameter.DbType, parameter.IsNullable);
}
message.AppendFormat("\r\n-- Completed in {0} ms", watch.ElapsedMilliseconds, command); logger.Trace(message.ToString());
} base.ReaderExecuted(command, interceptionContext);
}
}
}
NLogDbCommandInterceptor.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web; using System.Data.Entity.Infrastructure.Interception;
using Libing.Portal.Web.Common.Interceptors; namespace Libing.Portal.Web.Data
{
public class PortalContext : DbContext
{
static PortalContext()
{
Database.SetInitializer<PortalContext>(null); // 日志:Entity Framework生成的Sql语句
DbInterception.Add(new NLogDbCommandInterceptor());
}
}
}
PortalContext.cs
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true">
<targets>
<target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target xsi:type="File"
fileName="${basedir}/Logs/${shortdate}.log"
layout="${longdate} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}"
keepFileOpen="false"
archiveFileName="${basedir}/Logs/${shortdate}.{##}.log"
archiveAboveSize="1048576"
encoding="UTF-8" />
</target>
</targets>
<rules>
<!--Trace->Debug->Info->Warn->Error->Fatal-->
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
NLog.config
EntityFramework优化:SQL语句日志的更多相关文章
- mysql优化SQL语句的一般步骤及常用方法
一.优化SQL语句的一般步骤 1. 通过show status命令了解各种SQL的执行频率 mysqladmin extended-status 或: show [session|global]sta ...
- mysql优化sql语句
mysql优化sql语句 常见误区 www.2cto.com 误区1: count(1)和count(primary_key) 优于 count(*) 很多人为了统计记录条数,就使 ...
- MySql(五)SQL优化-优化SQL语句的一般步骤
MySql(五)SQL优化-优化SQL语句的一般步骤 一.优化SQL语句的一般步骤 1.1 通过show status命令了解各种SQL的执行频率 1.2 定位执行效率较低的SQL语句 1.3 通过e ...
- 优化 SQL 语句的步骤
优化 SQL 语句的步骤 1.分析MySQL服务器当前的状态信息 SHOW SESSION STATUS; SHOW SESSION STATUS LIKE 'Com_%' //当前会话下所有语句类型 ...
- MySQL查询不使用索引汇总 + 如何优化sql语句
不使用索引原文 : http://itlab.idcquan.com/linux/MYSQL/918330.html MySQL查询不使用索引汇总 众所周知,增加索引是提高查询速度的有效途径,但是很多 ...
- 8.2.优化SQL语句
8.2.优化SQL语句 数据库应用程序核心操作逻辑都是通过执行SQL语句来执行,不管是直接通过解释器还是通过后台API提交. 调优手册里面的这一节内容帮助各种各样MySQL程序加快速度.手册包括SQL ...
- 浅谈MySQL中优化sql语句查询常用的30种方法 - 转载
浅谈MySQL中优化sql语句查询常用的30种方法 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中使 ...
- 通过profile优化SQL语句
开启profile优化SQL语句:set profiling=1;执行SQL语句show profiles;show profile for query 2;//根据query_id 查看某个查询的详 ...
- 应用索引技术优化SQL 语句(转)
原文出处 一.前言 很多数据库系统性能不理想是因为系统没有经过整体优化,存在大量性能低下的SQL 语句.这类SQL语句性能不好的首要原因是缺乏高效的索引.没有索引除了导致语句本身运行速度慢外,更是导致 ...
- Egg上层框架CabloyJS是如何输出SQL语句日志的?
背景 在Egg开发实践中,经常会遇到一个问题:如何查看刚刚执行过的Egg组装的原生SQL语句呢? 1. 现有方案 可以直接在项目的config配置文件中添加MySQL配置debug: true.这会启 ...
随机推荐
- 控制台程序(C#)不弹出登录窗口连接到Dynamics CRM Online的Web API
微软动态CRM专家罗勇 ,回复331或者20190505可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 我之前的文章 控制台程序(C#)不弹出认证窗口连接到Dynami ...
- [转]Outlook VBA自动处理邮件
本文转自:https://blog.csdn.net/hnwyllmm/article/details/44874331 需求描述公司里面每天都会有很多邮件,三分之一都是不需要看的,Outlook的过 ...
- 一文解读ARM架构 (转)
本文主要介绍的是arm架构和x86架构的区别,首先介绍了ARM架构图,其次介绍了x86架构图,最后从性能.扩展能力.操作系统的兼容性.软件开发的方便性及可使用工具的多样性及功耗这五个方面详细的对比了a ...
- 使用 gitlab 进行代码管理
这里使用 gitlab 做服务器, 客户端主要使用 git extensions. ============================= gitlab 项目成员类型: ============= ...
- Linux—网络防火墙详解
一.防火墙基本知识 二.firewall防火墙 # 安装firewalld [root@localhost ~]# apt-get install firewalld [root@localhost ...
- 元素无法定位问题 NoSuchElementException: Message: no such element: Unable to locate element 解决方法
定位网页上某个按钮时,总是报错元素定位不到,具体如下:NoSuchElementException: Message: no such element: Unable to locate elemen ...
- 21.Java基础_String类
String类构造方法 package pack1; //推荐使用直接赋值的方式得到字符串 public class test { public static void main(String[] a ...
- Div转为Canvas简直不要太好玩~~~
html2canvas库 今天发现了一个神奇的玩意,简直不要太好玩~~ 用canvas做动画是很难,但是div能比canvas简单不少,只是因为canvas中不能操作Dom元素 这款神器,可以直接将D ...
- adb的端口号5037被占用的解决方法
1.在cmd中执行adb nodaemon server,查看adb的端口号是多少,一般情况下是5037(why?应该软件使用的端口号是固定的) 2.再执行netstat -ano | findstr ...
- shiro异步请求返回JSON响应
shiro异步请求返回JSON响应 需求1:当shiro请求资源,但是没有进行认证时,默认是进行重定向,现在需要返回JSON响应.注意异步请求,服务器重定向后,ajax拿到的是浏览器重定向后的到的页面 ...