Recently there was a question in the NHUser group about how to configure Log4Net to log the queries generated by NHibernate. First of all: you can get Log4Net here. There you also find the documentation. If you are not sure about details of the configuration shown below please refer to this documentation.
If you only want NHibernate to log the queries it sends to the data source when running unit tests you don't have to configure Log4Net at all. It suffices to add the show_sql key to the NHibernate configuration. If you are using a separate xml file to configure NHibernate (e.g. the hibernate.cfg.xml) then its content might look similar to the one below
Now when running any unit test that involves NHibernate the queries generated by NHibernate will be logged in the output window (be it the unit test runner of Resharper or be it the Output Window of Visual Studio when you use TestDriven).
If you want to use Log4Net to collect logging information generated by NHibernate you have to add the necessary configuration to the config file of your application. If you want to log to two different targets (e.g. to the console and to a file) the relevant sections in your config file might look like follows
Here I define that all output with a priority of at least DEBUG goes to the console.
Now I have to tell my application that I want to use Log4Net. I can do that with an assembly level attribute. That is, you have to put the following code snippet somewhere in your application (e.g. the "Global. asax" if you are building a web application)
having done do we can now run a first unit test that accesses the database via NHibernate. The output generated by Log4Net in the unit test runner is similar to this
as you can see LOADS of information.
To tune the generated logging information a little bit we can filter the output generated by NHibernate by putting the following configuration section into our config file (put them just after the root section inside the log4net node)
Obviously NHibernate defines two different loggers NHibernate and NHibernate.SQL. The first one receives all logging output that NHibernate generates where as the second one only receives the sql statements generated by NHibernate.
With the above settings in place the output generated is reduced to
That's what we want. Only if we have some weird problems we need to change the priority level of the NHibernate filter to say INFO or DEBUG.
As usual you can find a demo solution here.