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.这会启 ...
随机推荐
- js验证手机号、身份证等
//验证手机号function check_lxdh(lxdh){ var mobile = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0 ...
- SAP MM 有了采购订单历史的PO行项目里的采购附加费不允许再改了?
SAP MM 有了采购订单历史的PO行项目里的采购附加费不允许再改了? 正确答案是: 不允许,这是SAP标准逻辑. 那么问题来了!今日收到业务人员报说采购订单4300013979,完成了收货和IV, ...
- Android自定义注解
1.元注解 概念:用来定义其他注解的注解,自定义注解的时候,需要使用它来定义我们的注解. 在jdk 1.5之后提供了 java.lang.annotation 来支持注解功能 常见的四种元 ...
- C# 运行时的关系
简介 记录c#对象在托管堆中运行时的相互关系,如下记录了一个方法在执行时候的生命周期,当方法在之前,CLR会先执行将方法里面所有用到的局部变量.参数对应的内存地址等全部存放当前线程栈当中,并且会将所有 ...
- [20190531]建立job与commit.txt
[20190531]建立job与commit.txt --//昨天看链接:https://connor-mcdonald.com/2019/05/28/dbms_job-the-joy-of-tran ...
- 《大话处理器》Cache一致性协议之MESI【转】
转自:https://blog.csdn.net/muxiqingyang/article/details/6615199 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载 ...
- web的前台、后台、前端、后端
前台:呈现给用户的视觉和基本的操作.后台:用户浏览网页时,我们看不见的后台数据跑动.后台包括前端,后端.前端:对应我们写的html .javascript 等网页语言作用在前端网页.后端:对应jsp. ...
- sql 以某个字段分组,另一个字段为参加比较的列,取得前n项的值
假设表A有三个字段 { id int: subject varchar(20): socre int: } 语句为 select * from A x where (select count(*) ...
- Log日志级别从高到低排序 ERROR、WARN、INFO、DEBUG
Log4j建议只使用四个级别,优先级从高到低分别是 ERROR.WARN.INFO.DEBUG.通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关.比如在这里定义了INFO级别,则应 ...
- ionic4 新建 - 报错
npm install -g cordova ionic 安装依赖 ionic start myApp tabs 新建项目 ionic g page name name为页面名称 新建组件 创建公共模 ...