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.这会启 ...
随机推荐
- 常用RGB颜色表 色值
转自:http://blog.sina.com.cn/s/blog_7f422a8901019d8j.html R G B 值 R G B 值 R G B 值 黑色 0 0 0 #0000 ...
- c# 打印的问题总结
近期 做了一个打印的类,有一下功能: /// <summary> /// 打印数据表格的类 /// 2016/05/19 @佳序 /// 功能: /// 01.自动 ...
- Socket简单实现ssh笔记
Scoket概念: socket本质上就是在2台网络互通的电脑之间,架设一个通道,两台电脑通过这个通道来实现数据的互相传递. 我们知道网络 通信 都 是基于 ip+port 方能定位到目标的具体机器上 ...
- 利用python去实现数学基本值的计算
def get_nums(): nums = []#获取列表 num = input('请输入数字:').strip() while num != '': nums.append(num)#添加数字 ...
- mysql常见错误代码解释
mysql常见错误代码解释 原创 作者:bayaim 时间:2017-12-26 11:07:14 38 ---------------------------------------------- ...
- Jmeter+ant+Jenkins构建接口自动化测试时构建失败 提示:Fatal Error! 字符引用 "&#原因
Jmeter+ant+Jenkins构建接口自动化测试时构建失败 提示:Fatal Error! 字符引用 "&#原因:接口响应数据中有&#
- c# 第25节 方法重载
本节内容: 1:方法重载简介 2:方法重载的实现实例 1:方法重载简介 2:方法重载的实现实例 决定方法是否构成重载有三个条件: 1:在同一个类中 2:方法名相同 3:参数列表不同 实例例子: 实现:
- 详解C++ STL priority_queue 容器
详解C++ STL priority_queue 容器 本篇随笔简单介绍一下\(C++STL\)中\(priority_queue\)容器的使用方法和常见的使用技巧. priority_queue容器 ...
- 其它 用VB6创建ActiveX.dll
1.打开VB6 2.选择 ActiveX DLL,点击打开 3.在窗口输入测试代码 Public Function addstr(str As String) As String addstr = & ...
- ESP8266 LUA脚本语言开发: 外设篇-GPIO输入检测
咱使用 GPIO0 https://nodemcu.readthedocs.io/en/master/modules/gpio/#gpioread 第一种 GPIO设置为输出的状态下读取引脚状态 gp ...