Quo*_*ter 3 c# logging entity-framework sqlcommand interceptor
我正在尝试拦截并将所有SQL命令记录到数据库中.我也需要参数及其值.但command.Parameters没有IEnumerable.我可以去找一个for-statement但有点感觉就像一个退缩.
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);
}
Run Code Online (Sandbox Code Playgroud)
我需要构建一个string(我知道我应该使用StringBuilder而不是string为了param,但为了问题,我希望保持简单)以便我可以将它传递给Message属性Log.
此代码略有调整,取自这个博客.
你可以把它变成一个列表......
StringBuilder sb = new StringBuilder();
command.Parameters.Cast<DbParameter>()
.ToList()
.ForEach(p => sb.Append(
string.Format("{0} = {1}{2}",
p.ParameterName,
p.Value,
Environment.NewLine)));
Console.WriteLine(sb.ToString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1745 次 |
| 最近记录: |