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

原文地址:https://www.cnblogs.com/libingql/p/11534385.html

时间: 2024-08-06 20:51:31

EntityFramework优化:SQL语句日志的相关文章

【转】 如何优化sql语句

============推荐============ csdn:http://blog.csdn.net/e3002/article/details/1817941 ====如何优化sql语句==== (1)选择最有效率的表名顺序(只在基于规则的优化器中有效): ORACLE的解析器按照从右到左的顺序处理FROM子句中的表名,FROM子句中写 在最后的表(基础表 driving table)将被最先处理,在FROM子句中包含多个表的 情况下,你必须选择记录条数最少的表作为基础表.如果有3个以上的

mysql优化sql语句

mysql优化sql语句 常见误区 www.2cto.com 误区1: count(1)和count(primary_key) 优于 count(*) 很多人为了统计记录条数,就使用 count(1) 和 count(primary_key) 而不是 count(*) ,他们认为这样性能更好, 其实这是一个误区.对于有些场景,这样做可能性能会更差,应为数据库对 count(*) 计数操作做了一些特别的优化. 误区2: count(column) 和 count(*) 是一样的 这个误区甚至在很多

通过profile优化SQL语句

开启profile优化SQL语句:set profiling=1;执行SQL语句show profiles;show profile for query 2;//根据query_id 查看某个查询的详细时间耗费 SHOW STATUS LIKE 'last_query_cost';//查询上一条语句执行的代价 例: mysql> show profiles;+----------+------------+----------------------------------------+| Qu

性能优化——SQL语句(续)

上篇博客介绍了一下自己在项目中遇到的一种使用sql语句的优化方式(性能优化--SQL语句),但是说的不够完整.在对比的过程中,没有将max函数考虑在内,经人提醒之后赶紧做了一个测试,测试过程中又学到了不少的东西.现给大家分享一下 上次用的是select count(*) 和select * 的执行效率问题,因为我的需求是获取数据的一个总数来自动给出新的id,然后网友给出可以使用max的方式给出新id.其实这也是一种不错的思路(当时我们也用过该函数,只不过因为系统数据本身问题,不适合用该函数),然

数据库调优教程(十二) 优化sql语句

五.           优化Sql语句 上一章讲了如何设计一张好的表,一张好的表自然需要好的sql语句去操作它.本章就来聊聊如何优化sql语句. 1.      Sql语句优化原则 优化需要优化的Query 定位优化对象性能瓶颈 从Explain入手 尽可能在索引中完成排序 只取自己需要的Column 尽可能避免复杂的join和子查询 2.     优化limit select * from test1 order by id limit 99999,10 原语句虽然使用了id索引,但是相当于

应用索引技术优化SQL 语句一

一.前言 很多数据库系统性能不理想是因为系统没有经过整体优化,存在大量性能低下的SQL 语句.这类SQL语句性能不好的首要原因是缺乏高效的索引.没有索引除了导致语句本身运行速度慢外,更是导致大量的磁盘读写操作,使得整个系统性能都受之影响而变差.解决这类系统的首要办法是优化这些没有索引或索引不够好的SQL语句. 本文讨论和索引相关的有关内容,以及通过分析语句的执行计划来讲述如何应用索引技术来优化SQL 语句.通过分析执行计划,读者可以检查索引是否有用,以及如何创建高效的索引.本文对数据库管理人员以

应用索引技术优化SQL 语句三

六.有关索引的几个问题 问题1,是否值得在identity字段上建立聚集索引.答案取决于identity 字段如何在语句中使用.如果你经常根据该字段搜索返回很少的行,那么在其上建立索引是值得的.反之如果identity字段根本很少在语句中使用,那么就不应该对其建立任何索引. 问题2,一个表应该建立多少索引合适.如果表的80%以上的语句都是读操作,那么索引可以多些.但是不要太多.特别是不要对那些更新频繁的表其建立很多的索引.很少表有超过5个以上的索引.过多的索引不但增加其占用的磁盘空间,也增加了S

Mysql性能优化----SQL语句优化、索引优化、数据库结构优化、系统配置优化、服务器硬件优化

一.SQL语句优化 1-1.MySQL慢日志 1).慢日志开启方式和存储格式 如何发现有问题的SQL? 使用Mysql慢日志对有效率问题的SQL进行监控 前期准备 mysql> show variables like '%log_queri%'; +-------------------------------+-------+ | Variable_name | Value | +-------------------------------+-------+ | log_queries_no

性能调优篇 - TPS低 - 优化SQL语句(一)

在执行性能测试的时候,问题总千奇百怪的.我这里整理了一些常用的性能测试时查看问题的方法. 一.SQL语句没有引用索引: 执行性能测试时,服务器的运行情况下: 数据库.应用程序CPU不超过80%: 内存足够(空余内存>20M); 网络正常: 磁盘输入/输出正常: 日志没有打印错误,但是TPS很低,如只有100-120(单个接口请求的性能测试,TPS一般会在550-60000这样,除非程序很复杂,那么TPS会小一些).这种情况下应该先查看SQL的语句是不是存在问题: 如: 查询语句,是否有索引,索引