Beispiel #1
0
 /// <summary>
 /// Called when a reader finishes executing, currently where logging occurs
 /// </summary>
 /// <param name="profiledDbCommand">The profiled DB Command.</param>
 /// <param name="executeType">The execute Type.</param>
 /// <param name="reader">The reader.</param>
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     if (IsActive)
     {
         _log("Finished " + _renderer.Render(profiledDbCommand));
     }
 }
Beispiel #2
0
        /// <summary>
        /// Tracks when 'command' is started.
        /// </summary>
        public void ExecuteStartImpl(IDbCommand command, SqlExecuteType type)
        {
            var id = Tuple.Create((object)command, type);
            var sqlTiming = new SqlTiming(command, type, Profiler);

            _inProgress[id] = sqlTiming;
        }
        /// <summary>
        /// ログに書き出す際の共通フォーマットを出力する。
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="sqlType"></param>
        /// <returns></returns>
        StringBuilder SetCommonLogString(StringBuilder sb, SqlExecuteType sqlType)
        {
            sb.Append("実行SQLログ【CommandType】").Append(sqlType).Append("【SQL】").Append(commandText)
            .Append("【パラメータ】").Append(parametersText).Append("【実行時間(ミリ秒)】").Append(stopwatch.ElapsedMilliseconds);

            return(sb);
        }
        /// <summary>
        /// profile with results.
        /// </summary>
        /// <param name="type">The type of execution.</param>
        /// <param name="func">A function to execute against the profile result.</param>
        /// <typeparam name="TResult">the type of result to return.</typeparam>
        private TResult ProfileWith <TResult>(SqlExecuteType type, Func <TResult> func)
        {
            if (_profiler == null || !_profiler.IsActive)
            {
                return(func());
            }

            TResult result;

            _profiler.ExecuteStart(this, type);
            try
            {
                result = func();
            }
            catch (Exception e)
            {
                _profiler.OnError(this, type, e);
                throw;
            }
            finally
            {
                _profiler.ExecuteFinish(this, type, null);
            }
            return(result);
        }
            public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
            {
                var formatter = new SqlServerFormatter();

                exception.Data["SQL"] = formatter.FormatSql(profiledDbCommand.CommandText, SqlTiming.GetCommandParameters(profiledDbCommand));
                _wrapped.OnError(profiledDbCommand, executeType, exception);
            }
Beispiel #6
0
        // コマンドが完了された時に呼ばれる
        public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            foreach (IDataParameter p in profiledDbCommand.Parameters)
            {
                if (p.Value == null)
                {
                    dic.Add(p.ParameterName, "null");
                }
                else
                {
                    dic.Add(p.ParameterName, p.Value.ToString());
                }
            }

            this._commandText       = profiledDbCommand.CommandText;
            this._commandParameters = JsonConvert.SerializeObject(dic, Formatting.None);

            if (executeType != SqlExecuteType.Reader)
            {
                this._stopwatch.Stop();

                Logging.MyDebugSQLTrace(
                    JsonConvert.SerializeObject(new
                {
                    date    = DateTime.Now,
                    command = executeType,
                    text    = StringConverter.FormattingForOneLineLog(this._commandText),
                    param   = this._commandParameters,
                    ms      = this._stopwatch.ElapsedMilliseconds
                }, Formatting.None));
            }
        }
Beispiel #7
0
        public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception e)
        {
            var formatter  = new Profiling.SqlFormatters.SqlServerFormatter();
            var parameters = SqlTiming.GetCommandParameters(profiledDbCommand);

            e.Data["SQL"] = formatter.FormatSql(profiledDbCommand.CommandText, parameters);
        }
Beispiel #8
0
        public void ExecuteBatch(IEnumerable <string> sqlStatements)
        {
            List <iBatisStatement> theIBatisNetBatchStatements = new List <iBatisStatement>();

            foreach (string sqlStatement in sqlStatements)
            {
                string         tempsql = sqlStatement.ToUpper().Trim();
                SqlExecuteType type    = default(SqlExecuteType);
                if (tempsql.StartsWith(SqlExecuteType.INSERT.ToString()))
                {
                    type = SqlExecuteType.INSERT;
                }
                else if (tempsql.StartsWith(SqlExecuteType.UPDATE.ToString()))
                {
                    type = SqlExecuteType.UPDATE;
                }
                else if (tempsql.StartsWith(SqlExecuteType.DELETE.ToString()))
                {
                    type = SqlExecuteType.DELETE;
                }

                theIBatisNetBatchStatements.Add(new iBatisStatement()
                {
                    StatementName = "ExecuteSqlNoneQuery", ParameterObject = sqlStatement, Type = type
                });
            }

            ExecuteBatch(theIBatisNetBatchStatements);
        }
        /// <summary>
        /// Tracks when 'command' is started.
        /// </summary>
        public void ExecuteStartImpl(IDbCommand command, SqlExecuteType type)
        {
            var id        = Tuple.Create((object)command, type);
            var sqlTiming = new SqlTiming(command, type, Profiler);

            _inProgress[id] = sqlTiming;
        }
Beispiel #10
0
        /// <summary>
        /// Finishes profiling for 'command', recording durations.
        /// </summary>
        /// <param name="profiledDbCommand">The <see cref="IDbCommand"/> that finished.</param>
        /// <param name="executeType">The execution type of the <paramref name="profiledDbCommand"/>.</param>
        /// <param name="reader">(Optional) the reader piece of the <paramref name="profiledDbCommand"/>, if it exists.</param>
        void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
        {
            if (_inProgress == null)
            {
                return;
            }

            var          id = Tuple.Create((object)profiledDbCommand, executeType);
            CustomTiming current;

            lock (_inProgress)
            {
                if (!_inProgress.TryRemove(id, out current))
                {
                    return;
                }
            }

            if (reader != null)
            {
                lock (_dbLocker)
                {
                    _inProgressReaders = _inProgressReaders ?? new Dictionary <IDataReader, CustomTiming>();
                }
                lock (_inProgressReaders)
                {
                    _inProgressReaders[reader] = current;
                }
                current.FirstFetchCompleted();
            }
            else
            {
                current.Stop();
            }
        }
Beispiel #11
0
 /// <summary>
 /// Called when an error happens during execution of a command
 /// </summary>
 /// <param name="profiledDbCommand">The profiled DB Command.</param>
 /// <param name="executeType">The execute Type.</param>
 /// <param name="exception">The exception.</param>
 public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
 {
     if (IsActive)
     {
         _log(_renderer.Render(exception));
         _log(_renderer.Render(profiledDbCommand));
     }
 }
Beispiel #12
0
 /// <summary>
 /// Finishes profiling for 'command', recording durations.
 /// </summary>
 public static void ExecuteFinish(
     this SqlProfiler sqlProfiler,
     IDbCommand command,
     SqlExecuteType type,
     DbDataReader reader = null)
 {
     sqlProfiler?.ExecuteFinishImpl(command, type, reader);
 }
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     if (reader == null)
     {
         _sw.Stop();
     }
     _wrapped?.ExecuteFinish(profiledDbCommand, executeType, reader);
 }
Beispiel #14
0
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     if (reader == null)
     {
         _sw.Stop();
     }
     _wrapped?.ExecuteFinish(profiledDbCommand, executeType, reader);
 }
        public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, System.Data.Common.DbDataReader reader)
        {
            _commandText = profiledDbCommand.CommandText;
            if (executeType == SqlExecuteType.Reader) return;

            _stopwatch.Stop();
            _logger.Trace(new TraceLogMessage(executeType, _commandText, _stopwatch.ElapsedMilliseconds));
        }
Beispiel #16
0
        void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, System.Data.Common.DbDataReader reader)
        {
            if (reader == null)
            {
                _watch.Stop();
            }

            ExecuteFinishCount++;
        }
Beispiel #17
0
        /// <summary>
        /// execute the finish.
        /// </summary>
        /// <param name="profiledDbCommand">The profiled DB command.</param>
        /// <param name="executeType">The execute type.</param>
        /// <param name="reader">The reader.</param>
        void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, System.Data.Common.DbDataReader reader)
        {
            if (reader == null)
            {
                _watch.Stop();
            }

            ExecuteFinishCount++;
        }
        public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
        {
            Count++;

            _wrapped?.ExecuteStart(profiledDbCommand, executeType);

            // This is subtle, avoid measure time gathering stack trace (that happens on execute start)
            _sw.Start();
        }
Beispiel #19
0
        public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
        {
            Count++;

            _wrapped?.ExecuteStart(profiledDbCommand, executeType);

            // This is subtle, avoid measure time gathering stack trace (that happens on execute start)
            _sw.Start();
        }
Beispiel #20
0
        /// <summary>
        /// Finishes profiling for 'command', recording durations.
        /// </summary>
        public void ExceptionImpl(ProfiledDbCommand command, SqlExecuteType type, Exception exception)
        {
            var id      = Tuple.Create((object)command, type);
            var current = _inProgress[id];

            current.Exception(exception);
            SqlTiming ignore;

            _inProgress.TryRemove(id, out ignore);
        }
Beispiel #21
0
        /// <summary>
        /// Called when a command errors.
        /// </summary>
        /// <param name="profiledDbCommand">The <see cref="IDbCommand"/> that finished.</param>
        /// <param name="executeType">The execution type of the <paramref name="profiledDbCommand"/>.</param>
        /// <param name="exception">The exception thrown.</param>
        void IDbProfiler.OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
        {
            var id = Tuple.Create((object)profiledDbCommand, executeType);

            if (_inProgress.TryRemove(id, out var command))
            {
                command.Errored = true;
                command.Stop();
            }
        }
 /// <summary>
 /// コマンドが開始された時に呼ばれます。
 /// </summary>
 /// <param name="profiledDbCommand">SQLステートメントを表すインターフェイス</param>
 /// <param name="executeType">SQL文のカテゴリ</param>
 public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
 {
     foreach (var item in this.profilers)
     {
         if (item != null && item.IsActive)
         {
             item.ExecuteStart(profiledDbCommand, executeType);
         }
     }
 }
 /// <summary>
 /// エラー発生時に呼ばれます。
 /// </summary>
 /// <param name="profiledDbCommand">SQLステートメントを表すインターフェイス</param>
 /// <param name="executeType">SQL文のカテゴリ</param>
 /// <param name="exception">発生した例外</param>
 public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
 {
     foreach (var item in profilers)
     {
         if (item != null && item.IsActive)
         {
             item.OnError(profiledDbCommand, executeType, exception);
         }
     }
 }
 /// <summary>
 /// コマンドが完了された時に呼ばれます。
 /// </summary>
 /// <param name="profiledDbCommand">SQLステートメントを表すインターフェイス</param>
 /// <param name="executeType">SQL文のカテゴリ</param>
 /// <param name="reader">取得結果セットを読み込むインターフェイス</param>
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     foreach (var item in this.profilers)
     {
         if (item != null && item.IsActive)
         {
             item.ExecuteFinish(profiledDbCommand, executeType, reader);
         }
     }
 }
        /// <summary>
        /// Tracks when 'command' is started.
        /// </summary>
        /// <param name="profiledDbCommand">The <see cref="IDbCommand"/> that started.</param>
        /// <param name="executeType">The execution type of the <paramref name="profiledDbCommand"/>.</param>
        void IDbProfiler.ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
        {
            var id     = Tuple.Create((object)profiledDbCommand, executeType);
            var timing = profiledDbCommand.GetTiming(executeType.ToString(), this);

            lock (_dbLocker)
            {
                _inProgress     = _inProgress ?? new Dictionary <Tuple <object, SqlExecuteType>, CustomTiming>();
                _inProgress[id] = timing;
            }
        }
Beispiel #26
0
        /// <summary>
        ///     打开一个Sql数据库连接
        /// </summary>
        /// <returns></returns>
        protected IDbConnection OpenConnection(SqlExecuteType executeType)
        {
            switch (executeType)
            {
            case SqlExecuteType.Read:
                return(Infrastructure.DataAccess.SqlDispatcher.ConnectionManager.ReadConnection());

            default:
                return(Infrastructure.DataAccess.SqlDispatcher.ConnectionManager.WriteConnection());
            }
        }
 void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     if (reader != null)
     {
         SqlProfiler.ExecuteFinish(profiledDbCommand, executeType, reader);
     }
     else
     {
         SqlProfiler.ExecuteFinish(profiledDbCommand, executeType);
     }
 }
 void IDbProfiler.ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     if (reader != null)
     {
         SqlProfiler.ExecuteFinish(profiledDbCommand, executeType, reader);
     }
     else
     {
         SqlProfiler.ExecuteFinish(profiledDbCommand, executeType);
     }
 }
Beispiel #29
0
        /// <summary>
        /// Finishes profiling for 'command', recording durations.
        /// </summary>
        /// <param name="command">The <see cref="IDbCommand"/> that finished.</param>
        /// <param name="type">The execution type of the <paramref name="command"/>.</param>
        /// <param name="reader">(Optional) the reader piece of the <paramref name="command"/>, if it exists.</param>
        public void ExecuteFinish(IDbCommand command, SqlExecuteType type, DbDataReader reader = null)
        {
            var id      = Tuple.Create((object)command, type);
            var current = _inProgress[id];

            current.ExecutionComplete(reader != null);
            _inProgress.TryRemove(id, out var ignore);
            if (reader != null)
            {
                _inProgressReaders[reader] = current;
            }
        }
Beispiel #30
0
 /// <summary>
 /// Finishes profiling for 'command', recording durations.
 /// </summary>
 public void ExecuteFinishImpl(IDbCommand command, SqlExecuteType type, DbDataReader reader = null)
 {
     var id = Tuple.Create((object)command, type);
     var current = _inProgress[id];
     current.ExecutionComplete(reader != null);
     SqlTiming ignore;
     _inProgress.TryRemove(id, out ignore);
     if (reader != null)
     {
         _inProgressReaders[reader] = current;
     }
 }
Beispiel #31
0
        public void OnError(IDbCommand command, SqlExecuteType type, Exception exception)
        {
            DbCommandKey id = Tuple.Create((object)command, type);

            if (_inProgress.TryRemove(id, out Stopwatch stopwatch) && stopwatch.Elapsed > _threshold)
            {
                _logger.Warn(exception, "{LongRunningQuery}", new
                {
                    sql     = command.CommandText,
                    elapsed = (long)stopwatch.Elapsed.TotalMilliseconds
                });
            }
        }
        /// <summary>
        /// コマンドが完了された時に呼ばれます。
        /// </summary>
        /// <param name="profiledDbCommand">SQLステートメントを表すインターフェイス</param>
        /// <param name="executeType">SQL文のカテゴリ</param>
        /// <param name="reader">取得結果セットを読み込むインターフェイス</param>
        public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
        {
            this.commandText = GetCommandText(profiledDbCommand);
            this.parameters  = string.Join(", ", profiledDbCommand.Parameters.Cast <OracleParameter>()
                                           .Select(x => $"{x.ParameterName}:{x.Value}"));
            this.parameters = "{" + this.parameters + "}";

            if (executeType != SqlExecuteType.Reader)
            {
                stopwatch.Stop();
                logger.Trace($"SqlExecute({stopwatch.ElapsedMilliseconds}):{commandText}");
                logger.Trace($"SqlParameters:{parameters}");
            }
        }
        public void OnError(System.Data.IDbCommand profiledDbCommand, SqlExecuteType executeType, System.Exception exception)
        {
            SbForDBLog.Clear();

            SbForDBLog.Append("エラー発生SQL  ");
            SetCommonLogString(SbForDBLog, executeType)
            .AppendLine()
            .AppendLine(exception.ToString())
            .Replace(Environment.NewLine, " ");

            string log = SbForDBLog.ToString();

            logger.LogError(log);
        }
Beispiel #34
0
        public void ExecuteFinish(IDbCommand command, SqlExecuteType type, DbDataReader reader)
        {
            DbCommandKey id = Tuple.Create((object)command, type);

            if (_inProgress.TryRemove(id, out Stopwatch stopwatch) && stopwatch.Elapsed > _threshold)
            {
                _logger.Warn("{LongRunningQuery}", new
                {
                    stackTrace = StackTraceSnippet.Get(Options),
                    sql        = command.CommandText,
                    elapsed    = (long)stopwatch.Elapsed.TotalMilliseconds
                });
            }
        }
        /// <summary>
        ///     打开一个Sql数据库连接
        /// </summary>
        /// <returns></returns>
        protected IDbConnection OpenConnection(SqlExecuteType executeType)
        {
            IDbConnection connection = _factory.CreateConnection();

            try
            {
                connection.ConnectionString = _datastring;
                connection.Open();
                return(connection);
            }
            catch (Exception ex)
            {
                throw new Exception("无法连接到SQL服务器,连接字符串为:" + connection.ConnectionString, ex);
            }
        }
Beispiel #36
0
 /// <summary>
 /// SQLExeCute Finish output Log Exclude Reader
 /// </summary>
 /// <param name="profiledDbCommand"></param>
 /// <param name="executeType"></param>
 /// <param name="reader"></param>
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader)
 {
     commandText = profiledDbCommand.CommandText.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ');
     parameters  = new StringBuilder();
     for (int ix = 0; ix < profiledDbCommand.Parameters.Count; ix++)
     {
         var parameter = (DbParameter)profiledDbCommand.Parameters[ix];
         parameters.Append($" [ParameterName={parameter.ParameterName} ,Value={parameter.Value.ToString()}]");
     }
     if (executeType != SqlExecuteType.Reader)
     {
         stopwatch.Stop();
         logger.Debug($"SQL = {commandText} {parameters.ToString()} ExecuteTime={stopwatch.Elapsed.ToString()}");
     }
 }
Beispiel #37
0
        /// <summary>
        /// Initialises a new instance of the <see cref="SqlTiming"/> class. 
        /// Creates a new <c>SqlTiming</c> to profile 'command'.
        /// </summary>
        public SqlTiming(IDbCommand command, SqlExecuteType type, MiniProfiler profiler)
        {
            if (profiler == null) throw new ArgumentNullException("profiler");
            _profiler = profiler;
            
            var commandText = AddSpacesToParameters(command.CommandText);
            var parameters = GetCommandParameters(command);

            if (MiniProfiler.Settings.SqlFormatter != null)
            {
                commandText = MiniProfiler.Settings.SqlFormatter.GetFormattedSql(commandText, parameters, command);
            }

            _customTiming = profiler.CustomTiming("sql", commandText, type.ToString());
            if (_customTiming == null) throw new InvalidOperationException();
        }
Beispiel #38
0
 /// <summary>
 /// Tracks when 'command' is started.
 /// </summary>
 public static void ExecuteStart(this SqlProfiler sqlProfiler, IDbCommand command, SqlExecuteType type)
 {
     if (sqlProfiler == null) return;
     sqlProfiler.ExecuteStartImpl(command, type);
 }
 void IDbProfiler.OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
 {
     // TODO: implement errors aggregation and presentation
 }
 public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
 {
     _stopwatch = Stopwatch.StartNew();
 }
        // IDbProfiler methods

        void IDbProfiler.ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
        {
            SqlProfiler.ExecuteStart(profiledDbCommand, executeType);
        }
 public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
 {
 }
Beispiel #43
0
 /// <summary>
 /// on error.
 /// </summary>
 /// <param name="profiledDbCommand">
 /// The profiled DB command.
 /// </param>
 /// <param name="executeType">
 /// The execute type.
 /// </param>
 /// <param name="exception">
 /// The exception.
 /// </param>
 void IDbProfiler.OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception)
 {
     ErrorCount++;
     ErrorSql = profiledDbCommand.CommandText;
 }
 public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception e)
 {
     var formatter = new Profiling.SqlFormatters.SqlServerFormatter();
     var parameters = SqlTiming.GetCommandParameters(profiledDbCommand);
     e.Data["SQL"] = formatter.FormatSql(profiledDbCommand.CommandText, parameters);
 }
Beispiel #45
0
 /// <summary>
 /// execute the start.
 /// </summary>
 /// <param name="profiledDbCommand">The profiled DB command.</param>
 /// <param name="executeType">The execute type.</param>
 void IDbProfiler.ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType)
 {
     _watch.Start();
     ExecuteStartCount++;
     ErrorSql = null;
 }
Beispiel #46
0
 /// <summary>
 /// Finishes profiling for 'command', recording durations.
 /// </summary>
 public static void ExecuteFinish(
     this SqlProfiler sqlProfiler, 
     IDbCommand command, 
     SqlExecuteType type, 
     DbDataReader reader = null)
 {
     if (sqlProfiler == null) return;
     sqlProfiler.ExecuteFinishImpl(command, type, reader);
 }