记录NHibernate SQL查询

有没有办法在我的代码中访问完整的SQL查询,包括值?

我能够使用log4net记录SQL查询:

    

但是,我想找到一种从代码中记录SQL查询的方法。 这样我将在try / catch语句中记录导致exception的特定SQL查询。

现在,我必须对SQLFileLog进行数据挖掘,以便在发生exception时找到导致exception的查询并且效率不高。

你可以使用拦截器来做到这一点:

 public class LoggingInterceptor : EmptyInterceptor { public override SqlString OnPrepareStatement(SqlString sql) { Debug.WriteLine(sql); return sql; } } 

有关使用nhibernate注册它的不同方法,请参阅Nhibernate Docs 。

你可以覆盖驱动程序:

 public class LoggerSqlClientDriver:SqlClientDriver, IEmbeddedBatcherFactoryProvider { public override void AdjustCommand(IDbCommand command) { //log here base.AdjustCommand(command); } //protected override void OnBeforePrepare(IDbCommand command) //{ // //log here // base.OnBeforePrepare(command); //} } 

然后在配置中使用它:

 var config = Fluently.Configure(). Database(MsSqlConfiguration.MsSql2005.Driver(); 

要么使用sql profiler,要么在http://nhprof.com/查看nhprof

两者都会让你看到sql输出。

还要在hibernate配置文件中设置show_sql属性

 true 

使用具有特定目标的log4net appender(它支持切换打开/关闭)或者只是扩展它并在try-catch-finally-off中切换它。