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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值