Monday, May 19, 2014

NHibernate logging in Visual Studio output window

NHibernate 'show_sql=true' does not log the generated queries to the output window of Visual Studio when working in ASP.NET MVC 4.
I made a simple implementation for logging NHibernate queries in Visual Studio's output window, without use of third party loggers.

Create an interceptor class, and override one method
public class NHLogger : EmptyInterceptor, IInterceptor
    public override NHibernate.SqlCommand.SqlString 
       OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
        System.Diagnostics.Debug.WriteLine("NHIBERNATE: " +  sql);
        return base.OnPrepareStatement(sql);

Then create an instance of it in the OpenSession of the Factory.
SessionFactory.OpenSession(new NHLogger());