如何使用NHibernate将SQL调用记录到Visual Studio的控制台?

时间:2009-01-23 21:32:11

标签: visual-studio nhibernate logging log4net

我有NHibernate的以下配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.connection_string">Server=.\SQLEXPRESS;Database=mydb;Integrated Security=True;</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.release_mode">auto</property>
    <property name="adonet.batch_size">500</property>

    <property name="show_sql">true</property>

  </session-factory>
</hibernate-configuration>

但是SQL没有显示在Visual Studio的输出窗口中。是否必须安装log4net?或者show_sql应该单独工作吗?

5 个答案:

答案 0 :(得分:57)

要在Visual Studio的输出窗口中显示SQL,请将log4net配置为在log4net配置中使用TraceAppender。这样:

<appender name="DebugSQL" type="log4net.Appender.TraceAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>

然后这个:

<logger name="NHibernate.SQL" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="DebugSQL" />
</logger>

编辑:我似乎无法在此正确格式化。 See this link for code example

答案 1 :(得分:17)

对于那些喜欢代码而不是配置的人,以下代码段将使用简单的控制台appender创建相应的NH记录器。

var hierarchy = (Hierarchy) LogManager.GetRepository();
var logger = (Logger) hierarchy.GetLogger("NHibernate.SQL");
logger.AddAppender(new ConsoleAppender {Layout = new SimpleLayout()});
hierarchy.Configured = true;

答案 2 :(得分:8)

show_sql输出到Console.Out - 在运行集成测试时最有用

答案 3 :(得分:4)

你可以使用一种名为NHibernate的探测器。

http://nhprof.com/

它价格昂贵,但它有效并且有30天的试用期。

答案 4 :(得分:3)

从NHibernate 3.0开始,您可以使用loquacious配置

configuration.DataBaseIntegration(x =>
{
  x.LogSqlInConsole = true;
  x.LogFormattedSql = true;
});

http://fabiomaulo.blogspot.com.ar/2009/07/nhibernate-configuration-through.html

提供的其他信息