Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log SQL calls with NHibernate to the console of Visual Studio?

I have the following configuration file for 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> 

But the SQL doesn't show in the output window of Visual Studio. Is it mandatory to install log4net? Or should show_sql work alone?

like image 838
Nicolas Cadilhac Avatar asked Jan 23 '09 21:01

Nicolas Cadilhac


People also ask

How do I get SQL query from NHibernate?

Translating NHibernate LINQ expression tree to SQL without executing query against database server is trick we can use to investigate generated SQL when writing complex queries. I'm using ToSql() extension method also when optimizing slow queries to find out what was actually generated by NHibernate.

How do you debug NHibernate?

You just need to choose New Breakpoint from the Debug menu and then Break at function... (or Ctrl + B) and in the Function box type NHibernate. Impl. SessionImpl.


2 Answers

To show the SQL in the output window of Visual Studio, configure log4net to use TraceAppender in your log4net config. This:

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

Then this:

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

EDIT: I can't seem to format this correctly here. See this link for code example

like image 148
2 revs, 2 users 79% Avatar answered Sep 18 '22 15:09

2 revs, 2 users 79%


For those who prefer code rather than configuration, the following snippet will create the appropriate NH logger with a simple console appender.

var hierarchy = (Hierarchy) LogManager.GetRepository(); var logger = (Logger) hierarchy.GetLogger("NHibernate.SQL"); logger.AddAppender(new ConsoleAppender {Layout = new SimpleLayout()}); hierarchy.Configured = true; 
like image 41
Nathan Baulch Avatar answered Sep 18 '22 15:09

Nathan Baulch