I'm trying to intercept and log all SQL
commands to the database. And I need the parameters and their values as well. But command.Parameters
doesn't have an IEnumerable
. I could go for a for-statement
but kinda feels like a set back.
public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
_logger.Error(interceptionContext.Exception, "Error executing command: {0}", command.CommandText);
string param = string.Empty;
if (command.Parameters.Count > 0)
{
foreach (var t in command.Parameters)
{
param += t....
}
}
Log log = new Log()
{
Date = DateTime.UtcNow,
LogLevel = LogLevel.Error,
Message = command.CommandText + "\r\n " + param.
};
}
else
_logger.TraceApi("SQL Database", "CommandInterceptor.ScalarExecuted", _stopwatch.Elapsed, "Command: {0}: ", command.CommandText);
base.ScalarExecuted(command, interceptionContext);
}
I need to build a string
(I know I should use StringBuilder
in stead of string
for the param
, but for the question's sake want to keep it simple) so that I can pass it to the Message
property of Log
.
This code is slightly adjusted and taken from this blog.
sql
commands.