我通過將異常和實際命令傳遞給新的Exception類來記錄SQL異常。該類包裝SqlException和System.Data.Common.DbCommand對象。利用這些信息,我可以創造一個消息提供SQL命令的詳細信息:
public override string Message
{
get
{
StringBuilder message = new StringBuilder("");
StringBuilder sql = new StringBuilder("");
sql.AppendFormat(" {0} ", Command.CommandText);
foreach (SqlParameter param in Command.Parameters)
{
sql.AppendFormat(" {0} - {1}", param.ParameterName,
param.Value.ToString());
}
message.AppendFormat("Error: {0} SQL: {1} User: {2}", SqlEx.Message,
sql, Username);
return message.ToString();
}
}
最後,我用的是ErrorSignal提高方法登錄ELMAH消息:
Elmah.ErrorSignal.FromCurrentContext().Raise(new DetailSqlException(e.Exception as SqlException, e.Command, user));