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语句日志的更多相关文章

  1. mysql优化SQL语句的一般步骤及常用方法

    一.优化SQL语句的一般步骤 1. 通过show status命令了解各种SQL的执行频率 mysqladmin extended-status 或: show [session|global]sta ...

  2. mysql优化sql语句

    mysql优化sql语句   常见误区   www.2cto.com   误区1:   count(1)和count(primary_key) 优于 count(*)   很多人为了统计记录条数,就使 ...

  3. MySql(五)SQL优化-优化SQL语句的一般步骤

    MySql(五)SQL优化-优化SQL语句的一般步骤 一.优化SQL语句的一般步骤 1.1 通过show status命令了解各种SQL的执行频率 1.2 定位执行效率较低的SQL语句 1.3 通过e ...

  4. 优化 SQL 语句的步骤

    优化 SQL 语句的步骤 1.分析MySQL服务器当前的状态信息 SHOW SESSION STATUS; SHOW SESSION STATUS LIKE 'Com_%' //当前会话下所有语句类型 ...

  5. MySQL查询不使用索引汇总 + 如何优化sql语句

    不使用索引原文 : http://itlab.idcquan.com/linux/MYSQL/918330.html MySQL查询不使用索引汇总 众所周知,增加索引是提高查询速度的有效途径,但是很多 ...

  6. 8.2.优化SQL语句

    8.2.优化SQL语句 数据库应用程序核心操作逻辑都是通过执行SQL语句来执行,不管是直接通过解释器还是通过后台API提交. 调优手册里面的这一节内容帮助各种各样MySQL程序加快速度.手册包括SQL ...

  7. 浅谈MySQL中优化sql语句查询常用的30种方法 - 转载

    浅谈MySQL中优化sql语句查询常用的30种方法 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中使 ...

  8. 通过profile优化SQL语句

    开启profile优化SQL语句:set profiling=1;执行SQL语句show profiles;show profile for query 2;//根据query_id 查看某个查询的详 ...

  9. 应用索引技术优化SQL 语句(转)

    原文出处 一.前言 很多数据库系统性能不理想是因为系统没有经过整体优化,存在大量性能低下的SQL 语句.这类SQL语句性能不好的首要原因是缺乏高效的索引.没有索引除了导致语句本身运行速度慢外,更是导致 ...

  10. Egg上层框架CabloyJS是如何输出SQL语句日志的?

    背景 在Egg开发实践中,经常会遇到一个问题:如何查看刚刚执行过的Egg组装的原生SQL语句呢? 1. 现有方案 可以直接在项目的config配置文件中添加MySQL配置debug: true.这会启 ...

随机推荐

  1. 如何给HTML页面的文本设置字符和单词间距

    设置字符和单词间距介绍 属性名 单位 描述 letter-spacing px 设置字符间距 word-spacing px 设置单词间距 letter-spacing设置字符间距 letter-sp ...

  2. 微信小程序访问webservice(wsdl)+ axis2发布服务端(Java)

    0.主要思路:使用axis2发布webservice服务端,微信小程序作为客户端访问.步骤如下: 1.服务端: 首先微信小程序仅支持访问https的url,且必须是已备案域名.因此前期的服务器端工作需 ...

  3. JDK10源码分析之HashMap

    HashMap在工作中大量使用,但是具体原理和实现是如何的呢?技术细节是什么?带着很多疑问,我们来看下JDK10源码吧. 1.数据结构 采用Node<K,V>[]数组,其中,Node< ...

  4. 网络流媒体协议之——RTSP协议

    RTSP(Real-Time Stream Protocol)协议是一个基于文本的多媒体播放控制协议,属于应用层.RTSP以客户端方式工作,对流媒体提供播放.暂停.后退.前进等操作.该标准由IETF指 ...

  5. springboot中http 的get post put delete请求

    组合注解(RequestMapping的变形) @GetMapping = @RequestMapping(method = RequestMethod.GET)@PostMapping = @Req ...

  6. CodeForces - 573A (简单数论+模拟)

    题意 https://vjudge.net/problem/CodeForces-573A 有n个数ai​ ,你可以把每个数任意次×2 或×3 ,问能否最终使得每个数相等. 思路 x2和x3只能改变数 ...

  7. ue4 FString 中文乱码问题

    使用FString出现乱码,最简单的情况,FString Str = "你好"; 这时候就会出现乱码,解决方法是改成这样 FString Str = TEXT("你好&q ...

  8. 6. Go语言—字符串操作

    一.字符串支持的转义字符 \r 回车符(返回行首) \n 换行符(直接跳到下一行的同列位置) \t 制表符 \' 单引号 \" 双引号 \\ 反斜杠 \uXXXX Unicode字符码值转义 ...

  9. xargs 用法理解

    原来一直不理解,linux shell下 xargs和 管道的区别: 1.管道在linux shell用得比较广泛,管道常常用来组合两个及以上的命令,共同完成一个功能: 比如:我们要统计某一个文件有多 ...

  10. UOS系统 - 国产统一操作系统UOS的基本知识

    一.UOS操作系统含义及现状 UOS操作系统与windows不同的是,UOS统一操作系统支持龙芯.申威.华为鲲鹏等一票国产处理器芯片.它的诞生是多家国内科技公司联合孕育的结果,包括中国电子集团.武汉深 ...