2008-09-24 57 views

回答

39

你可以把这样的事情在你的app.config/web.config文件:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 
在配置节点

在configSections节点

<log4net> 
    <appender name="NHibernateFileLog" type="log4net.Appender.FileAppender"> 
    <file value="logs/nhibernate.txt" /> 
    <appendToFile value="false" /> 
    <layout type="log4net.Layout.PatternLayout"> 
     <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" /> 
    </layout> 
    </appender> 
    <logger name="NHibernate.SQL" additivity="false"> 
    <level value="DEBUG"/> 
    <appender-ref ref="NHibernateFileLog"/> 
    </logger> 
</log4net> 

而且别忘了打电话

log4net.Config.XmlConfigurator.Configure(); 

在您的应用程序的启动,或把

[assembly: log4net.Config.XmlConfigurator(Watch=true)] 

在AssemblyInfo.cs中

在配置设置中,“show_sql”属性设置为true。

6

使用sql server profiler。编辑(1年后):正如@Toran Billups所述,NHibernate profiler Ayende写的非常酷。

+0

是比通过MB日志文件涉水更容易。 – 2009-02-06 15:53:48

16

在配置设置中,将“show_sql”属性设置为true。 这将导致SQL在NHibernate的日志文件中输出,由log4net提供。

+0

不错。我忘了那个。 *点击* – 2008-09-24 19:05:21

+0

为什么这不是公认的答案? :) 谢谢你的提示。 – 2012-10-03 08:23:47

+0

这并不显示完整的SQL。我看不到实际值,如下所示:`SELECT application0_.ApplicationId as app === App1_101_1_,application0_.ApplicationNumberCounty as ApplicationNu2_101_1 ...' – 2016-03-28 19:22:07

5

您也可以尝试NHibernate Profiler(30天试用,如果没有其他)。这个工具是最好的恕我直言。

这不仅显示生成的SQL也警告/建议的/ etc

1

如果你使用SQL Server(不表达),你可以尝试SQL Server Profiler中。

5

我有点迟,我知道,但这是窍门,它是独立的工具/数据库/框架。 而不是那些有效的选项,我使用NH Interceptors

首先,实施延伸NHibernate.EmptyInterceptor并实现NHibernate.IInterceptor类:

using NHibernate; 

namespace WebApplication2.Infrastructure 
{ 
    public class SQLDebugOutput : EmptyInterceptor, IInterceptor 
    { 
     public override NHibernate.SqlCommand.SqlString 
      OnPrepareStatement(NHibernate.SqlCommand.SqlString sql) 
     { 
      System.Diagnostics.Debug.WriteLine("NH: " + sql); 

      return base.OnPrepareStatement(sql); 
     } 
    } 
} 

然后,当你打开你的会议只是通过一个实例。请务必仅在调试时进行:

public static void OpenSession() { 

#if DEBUG 
    HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(new SQLDebugOutput()); 

#else 
    HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(); 

#endif 
} 

就是这样。

从现在开始,你的sql命令就像这些...

var totalPostsCount = Database.Session.Query<Post>().Count(); 

var currentPostPage = Database.Session.Query<Post>() 
     .OrderByDescending(c => c.CreatedAt) 
     .Skip((page - 1) * PostsPerPage) 
     .Take(PostsPerPage) 
     .ToList(); 

..显示直接在输出窗口:

NH:SELECT CAST(COUNT(*)作为INT)作为col_0_0_从帖子post0_

NH:选择post0_.Id作为Id3_,post0_.user_id为user2_3_,post0_.Title为 Title3_,post0_.Slug为Slug3_,post0_.Content为Content3_, post0_.created_at为created6_3_,post0_.updated_at为updated7_3_, post0_.deleted_at从帖子post0_ deleted8_3_通过订购post0_.created_at desc限制?抵消?