views:

510

answers:

2

How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console? I'm using MsSqlConfiguration.MsSql2008.ShowSql() but it has no parameters and I can't find anything on Google.

+3  A: 

You probably want to use log4net, not ShowSql. Here is some configuration to send queries to Debug:

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

  <log4net debug="false">
    <appender name="WindowsDebugOutput" type="log4net.Appender.DebugAppender,
         log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern"
              value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
      </layout>
    </appender>

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

And then call this from your code before opening an NHibernate session:

log4net.Config.XmlConfigurator.Configure();

When you add a reference to the log4net DLL, make sure to set its "Copy Local" property to "true".

This isn't specific to FluentNHibernate, it works the same in any variant of NHibernate.

Michael Maddox
+2  A: 

I have not tried this with SQL Server, but with SQLite, the following code will show generated SQL in the Output window (Debug menu -> Windows -> Output, in VS2008).

The "Show output from:" combo box in the Output window should be set to "Debug" - VS2008 did that for me automatically.

            sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                            .UsingFile(DbFile)
                            // Display generated SQL in Output window
                            .ShowSql()
                          )
                .Mappings(m => m.AutoMappings.Add( GetAutoPersistenceModel() ))
                .BuildSessionFactory()
                ;

A word of warning - turning this on can slow down execution considerably.

Tom Bushell
The output window in Visual Studio shows Console, Debug, and Trace output. The ShowSql method writes to the Console, not Debug or Trace. Your recommendation is not different from what he has said he is already doing.
Michael Maddox
@Michael -I just re-tested this, and it works EXACTLY as described! Possibly a difference in implementation of FNH interface to SQLite vs SQL Server?
Tom Bushell
That's not the same "Debug" (notice there is no option for "Trace" or "Console"). :) To see if it is truly writing to Debug, use something like http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx
Michael Maddox