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.这会启 ...
随机推荐
- 2019年上半年收集到的人工智能LSTM干货文章
2019年上半年收集到的人工智能LSTM干货文章 门控神经网络:LSTM 和 GRU 简要说明 LSTM-CNN-Attention算法系列之一:LSTM提取时间特征 对时间序列分类的LSTM全卷积网 ...
- swift个人总结
最近iOS10 已经开始正式使用,研究使用了swift3.0,将一些总结记录于此,以便以后查阅.持续更新中. swift中一般将一些功能相近的方法写在同一个延展中,便于代码的规范,找起来也方便.区别o ...
- 程序卡在 while(SPI_I2S_GetFlagStatus(W5500_SPI, SPI_I2S_FLAG_TXE) == RESET) 处
stm32 SPI1,发现程序卡在 while(SPI_I2S_GetFlagStatus(W5500_SPI, SPI_I2S_FLAG_TXE) == RESET); 解决方式: 1.检查RCC时 ...
- Docker安装并运行mysql5.6数据库
1.在/home目录下新建mysql目录 mysql目录中新建三个目录:conf目录.logs目录.data目录,建这些目录的目的是用来挂载docker中的mysql下的目录的. 结果如下: 1.1. ...
- yum工具及源码包
目录 yum工具及源码包 yum yum源 yum实战案例 yum全局配置文件 制作本地yum仓库 构建企业级yum仓库 源码包 yum工具及源码包 yum yum是RedHat以及CentOS中的软 ...
- [20191012]组成rowid.txt
[20191012]组成rowid.txt --//昨天做了拆分rowid的测试,链接http://blog.itpub.net/267265/viewspace-2659613/=>[2019 ...
- Weblogic的三种部署方式
Weblogic的三种部署方式 在weblogic中部署项目通常有三种方式:第一,在控制台中安装部署:第二,将部署包放在domain域中autodeploy目录下部署:第三,使用域中配置文件c ...
- cobalt strike入门和防护
1.入门: https://blog.csdn.net/localhost01/article/details/86741124 2.cs的防护: 由于关乎渗透人员自身的安全,建议大家好好看看,这里贴 ...
- 关于ML.NET v1.0 的发布说明
今天,我们很高兴宣布发布 ML.NET 1.0.ML.NET 是一个免费的.跨平台的开源机器学习框架,旨在将机器学习(ML)的强大功能引入.NET 应用程序. ML.NET GitHub:https: ...
- Html学习之十八(表格与表单学习--统计表制作)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...