How to read sql generated by NHibernate in Visual Studio

不问归期 提交于 2019-12-06 05:29:59

I don't think Visual Studio will show console output for a class library or website project. What I do is configure log4net to write NHibernate's SQL to a text file, then open the file in Visual Studio. With the right configuration, VS will show updates to the file by clicking in the window.

In your Web.config (or app.config), define the log4net section, have NHibernate format the SQL nicely, create a text file appender, and direct NHibernate messages there:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="format_sql">true</property>
    </session-factory>
  </hibernate-configuration>

  <log4net>
    <appender name="NHibernateLogFile" type="log4net.Appender.FileAppender">
      <file value="../Logs/NHibernate.log" />
      <appendToFile value="false" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{HH:mm:ss.fff}%m%n==========%n" />
      </layout>
    </appender>

    <logger name="NHibernate" additivity="false">
      <level value="WARN" />
      <appender-ref ref="NHibernateLogFile" />
    </logger>
    <logger name="NHibernate.SQL" additivity="false">
      <level value="DEBUG" />
      <appender-ref ref="NHibernateLogFile" />
    </logger>
  </log4net>
</configuration>

Then open up NHibernate.Log in Visual Studio. Because of the MinimalLock above, Visual Studio can read the file at the same time log4net is writing to it. When you click in the window, VS will reload the file. Just be sure to turn this off when you deploy the web site or application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!