CHAPTER 12
NHibernate has out-of-the-box integration with log4net, a general purpose and widely used logging framework. If you added the NHibernate support from NuGet, you already have log4net because it is a required dependency. If not, do add a reference to it, preferably with NuGet:

Otherwise, navigate to http://logging.apache.org/log4net and download the latest binaries.
Either way, configure your NHibernate environment to use log4net instead of its own logging facility, which you should disable. The configuration file Web/App.config should have a section like this:
|
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> </configSections> <log4net debug="false"> <appender name="trace" type="log4net.Appender.ConsoleAppender, 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"> <level value="DEBUG" /> <priority value="DEBUG" /> <appender-ref ref="trace" /> </logger> </log4net> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="format_sql">true</property> <property name="show_sql">false</property> </session-factory> </hibernate-configuration> |
For web applications, replace the ConsoleAppender with the TraceAppender to use the trace window instead of the console for the log output:
<appender name="trace" type="log4net.Appender.TraceAppender, log4net"> |
Now we just have to tell log4net to read its configuration and start producing output:
NHibernate will output nicely formatted SQL for every query it sends to the database, including all parameters’ types and values.
Another nice feature is statistics. NHibernate keeps a count of virtually anything it does, at the session factory level. This means that for all sessions spawning from it, this information is available as the ISessionFactory.Statistics property. Some of the data available is:
Normally, statistics are enabled unless we disable them explicitly by configuration:
Or by code:
cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, Boolean.FalseString); |
At any point, we can also reset all statistics to their initial values:
sessionFactory.Statistics.Clear(); |