DataRabbit 轻量的ORM框架(18)-- 捕获数据库访问异常的详细信息

最新版本的DataRabbit(版本号:V3.2)新增一项重要功能--可以捕获访问数据库时产生的异常的详细信息,包括:异常对象、Sql语句、sql参数的名称和值。这是由IDBOperationLogger接口提供支持的。

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> /// <summary>
/// IDBOperationLogger用于捕获住DB操作异常。可以用于记录DB操作失败时的语句和参数。
/// </summary>
public interface IDBOperationLogger
{
void LogException(Exceptionee, string methodName, string cmdText,IDataParameterCollectionparameters);
}

当通过DataRabbit访问数据库时,所产生的任何异常,都会被IDBOperationLogger接口捕获住,你可以实现自己的Filter来对捕获的异常进行处理,比如,记录下执行失败的SQL语句和对应的参数值。

DataRabbit内部提供了IDBOperationLogger接口的两种实现:EmptyDBOperationLogger DBOperationLoggerEmptyDBOperationLogger 将忽略异常信息,而DBOperationLogger将会把异常的详细信息记录到日志文件。

比如,在数据库的Student表中插入一条记录时,产生主键冲突的异常,则DBOperationLogger会记录类似下面的的日志:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> 2008 / 11 / 19 11 : 49 : 20 :高--违反了PRIMARYKEY约束 ' PK_Student ' 。不能在对象 ' dbo.Student ' 中插入重复键。语句已终止。错误类型:System.Data.SqlClient.SqlException。位置:
< dbCommand >
< method > ExcuteCommand </ method >
< text > INSERTINTOStudent([AutoID],[Name],[Age],[Comment])VALUES(@AutoID,@Name,@Age,@Comment) </ text >
< parameters >
< paraname = " @AutoID " value = " 0 " />
< paraname = " @Name " value = " Sky " />
< paraname = " @Age " value = " 30 " />
< paraname = " @Comment " value = " NoComment " />
</ parameters >
</ dbCommand >

日志中,<dbCommand>节点下的<text>子节点的内容就是执行失败的SQL语句,而<parameters>节点下的子节点则列出了所有的参数名称及其对应的值。

那么,如何注入IDBOperationLogger实例到DataRabbit框架中了?通过TransactionScopeFactoryDBOperationLogger属性。例如:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> DataConfigurationconfig = ;
TransactionScopeFactorytransactionScopeFactory
= new TransactionScopeFactory();
transactionScopeFactory.DataConfiguration
= config;
transactionScopeFactory.DBOperationLogger
= new DBOperationLogger( " DBException.txt " );
transactionScopeFactory.Initialize();

上述配置会将异常日志记录到当前目录下的DBException.txt 文件中。

如果不设置DBOperationLogger属性,则DataRabbit框架默认采用EmptyDBOperationLogger。

记录执行失败的SQL语句和对应的参数值,对于我们分析异常产生的原因是十分有用的,而DataRabbit可以自动为你记录了这些信息。

关于V3.2版本的DataRabbit 请到DataRabbit 轻量的ORM框架(00) -- 序 文末处下载,谢谢!

你可能感兴趣的:(Data)