How to configure Log4Net for use with NHibernate

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.

Running without Log4Net

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

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Server=(local);Database=NHibernateFAQ;Integrated Security=SSPI;</property>
    
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

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).

Logging with Log4Net

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

<configuration>
  ...
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender, log4net">
      <layout type="log4net.Layout.PatternLayout, log4net">
        <param name="ConversionPattern" value="%d %p %m%n" />
      </layout>
    </appender>
 
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="log.txt" />
      <param name="AppendToFile" value="true" />
      <param name="DatePattern" value="yyyy.MM.dd" />
 
      <layout type="log4net.Layout.PatternLayout,log4net">
        <conversionPattern value="%d %p %m%n" />
      </layout>
    </appender>
    
    <root>
      <priority value="DEBUG" />
      <appender-ref ref="ConsoleAppender" />
    </root>
    ...
</configuration>

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)

// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

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

2008-07-02 08:40:07,249 INFO NHibernate 2.0.0.1001 (2.0.0.1001)
2008-07-02 08:40:07,251 INFO hibernate-configuration section not found in application configuration file
2008-07-02 08:40:07,254 INFO Bytecode provider name : lcg
2008-07-02 08:40:07,257 INFO Using reflection optimizer
2008-07-02 08:40:08,515 DEBUG connection.provider=NHibernate.Connection.DriverConnectionProvider
2008-07-02 08:40:08,516 DEBUG dialect=NHibernate.Dialect.MsSql2005Dialect
2008-07-02 08:40:08,517 DEBUG connection.driver_class=NHibernate.Driver.SqlClientDriver
2008-07-02 08:40:08,517 DEBUG connection.connection_string=Server=(local);Database=NHibernateFAQ;Integrated Security=SSPI;
2008-07-02 08:40:08,518 DEBUG show_sql=false
2008-07-02 08:40:08,522 DEBUG properties: System.Collections.Generic.Dictionary`2[System.String,System.String]
2008-07-02 08:40:08,526 INFO Mapping resource: LoggingSample.Person.hbm.xml
2008-07-02 08:40:08,872 INFO Using dialect: NHibernate.Dialect.MsSql2005Dialect
2008-07-02 08:40:11,425 INFO Mapping class: LoggingSample.Person -> Person
2008-07-02 08:40:11,537 DEBUG Mapped property: Id -> Id, type: Int32
2008-07-02 08:40:11,612 DEBUG Mapped property: LastName -> LastName, type: String
2008-07-02 08:40:11,614 DEBUG Mapped property: FirstName -> FirstName, type: String
2008-07-02 08:40:11,614 DEBUG Mapped property: Birthdate -> Birthdate, type: DateTime
2008-07-02 08:40:11,632 INFO checking mappings queue
2008-07-02 08:40:11,634 INFO processing one-to-many association mappings
2008-07-02 08:40:11,634 INFO processing one-to-one association property references
2008-07-02 08:40:11,634 INFO processing foreign key constraints
2008-07-02 08:40:11,712 INFO Using dialect: NHibernate.Dialect.MsSql2005Dialect
2008-07-02 08:40:11,716 INFO Using dialect defined converter
...
2008-07-02 08:40:12,410 DEBUG Static SQL for entity: LoggingSample.Person
2008-07-02 08:40:12,411 DEBUG  Version select: SELECT Id FROM Person WHERE Id = ?
2008-07-02 08:40:12,412 DEBUG  Snapshot select: SELECT person_.Id, person_.LastName as LastName0_, person_.FirstName as FirstName0_, person_.Birthdate as Birthdate0_ FROM Person person_ WHERE person_.Id=?
...

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)

<logger name="NHibernate" additivity="false">
  <level value="WARN"/>      
  <appender-ref ref="RollingFile" />
  <appender-ref ref="ConsoleAppender" />
</logger>
 
<logger name="NHibernate.SQL" additivity="false">
  <level value="ALL"/>      
  <appender-ref ref="RollingFile" />
  <appender-ref ref="ConsoleAppender" />
</logger>

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

2008-07-02 08:48:58,636 DEBUG select person0_.Id as Id0_, 
                        person0_.LastName as LastName0_, 
                        person0_.FirstName as FirstName0_, 
                        person0_.Birthdate as Birthdate0_ 
                        from Person person0_

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.

Enjoy

Blog Signature Gabriel .

Print | posted on Tuesday, July 01, 2008 7:07 PM

Comments on this post

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
I have been unable to get any logging output from my Integration Test project.

I copied your log4net section and put it in the app.config for the IntegrationTest project.

I put the assembly attribute on the class file with the tests I'm executing and in the assemblyinfo.cs file of both the test project and the domain assembly.

Is there something else I'm doing wrong?

Thank you for the great content, it is extremely helpful.
Left by John on Jul 02, 2008 2:04 AM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
@John: did you have a look at the demo solution I provide with this post? Does this one work for you?
Left by Gabriel Schenker on Jul 02, 2008 4:35 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
Is this specific to NHibernate 2.0 ? It doesn't seem to be working with 1.2.0
Left by kk on Jul 10, 2008 4:03 AM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
@kk: not that I am aware of... Can you provide some more details about your problem?
Left by Gabriel Schenker on Jul 20, 2008 6:05 PM

# how could connect two different Database

Requesting Gravatar...
hi
my name is zahra ,
i have two database that one tabel of one database have one to many relation with one tabel of another database ,if would you please help me how set connection string and session factory for each database.
thank you
Left by zahra on Oct 23, 2008 4:48 AM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
@zahra: assuming that the two tables are in two different tables of the same sql server you would IIRC have to use the notation "databasename.schema.tablename" when mapping the entities
Left by nhibernate on Oct 27, 2008 6:15 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
Logging in this manner does not seem to work inside of the integrated test suite of VSTS (MSTest?). The suggested configuration works if it's part of any other project, be it web, console, or WinForm though. I suspect it has something to do with the context MSTest uses to run in. I never did figure out a fix for this.
Left by Jamison Roberts on Dec 03, 2008 4:07 AM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
I got NHibernate to work in MSTest by adding a reference to System.Xml, reading app.config from a hard-coded path and telling log4net to put the RollingFile also in a hard-coded path.

Then I open the log file in Notepad++ and it updates every time I give it focus...
Left by Zeke Mulu on Oct 26, 2009 9:09 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
computer directly to the Wes tell modem using an Ethernet cable and see if you can browse the web. If you can, this confirms that your Internet connection is fine and your modem/router configuration is the most likely cause of the problem.they conflict with each other and neither works properly.
Left by online blackjack games on Dec 11, 2009 10:01 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
Interesting article and nice blog you have too!
Left by christmas tree on Jan 02, 2010 3:46 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
I know my readers (all 3 of you) prefer pictures over words so here is a picture.We do,and the bigger the better. I got all excited when I had to maximize my browser to see it. But you tricked us by having words in the picture.I could definitely see this becoming an issue, I will have to check the version of NUnit I'm using.
Left by www.backgammonfever.com on Jan 12, 2010 12:41 AM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
There are several laws through Kate Moss's street shoot photos of three styles UGG Boots sale which is highly exposed. How Nice!! uk ugg boots are the Favorite of Grey bear UGG Boots ukwith pon-poms are right for clothings in grey color, being moderate without losing elegance. The Unknown Cons of
UGG Boots store . Here's the Answer. The black color Ugg is mostly worthy of collection which is never old fashioned. what are you fucking While collocating with black clothes, it sends out cool sense to unlimited degree.Look On Ball:
UGG Boots sale!
Left by igwg on Feb 02, 2010 6:15 PM

# re: How to configure Log4Net for use with NHibernate

Left by ugg boot on Feb 08, 2010 7:01 PM

# re: How to configure Log4Net for use with NHibernate

Left by gucci shoes on Feb 21, 2010 2:12 PM

# re: How to configure Log4Net for use with NHibernate

Left by cheap picture frames on Feb 22, 2010 6:09 PM

# 12sky Gold

Requesting Gravatar...
Do you know12sky Gold? If you play the online game,you will knowTwelve Sky Goldis the game gold. In the game,if you had moreTwelveSky Gold ,you will had a tall level. But if you want,you can come here and spend a little money to boughtbuy 12sky Gold.Quickly come here.
Left by 12sky Gold on Feb 24, 2010 1:37 PM

# discount ed hardy women long sleeve shirts sales online

Requesting Gravatar...
YS0225A5 If you think you are beaten, you are! If you think you dare noted hardy clothing, you don't! If you want to win but think you can't, It's almost a cinch you won't ed hardy hoodies! If you think you'll lose,you're lost! For out of the world we find.Success begins with a fellow's will,It's all in a ed hardy shirts state of mind! Life's battles don't alwys go.To the stronger and faster ed hardy coats man,But sooner or later the man who wins,Is the man who thinks he can! When You Belive http://www.edfashionclothes.com/,Many night we've prayed!With no proof anyone could hear!In our heart a hopeful moncler online store song,we barely understood!Now we are not afraid !Although we know there's much to fear!We were moving the moncler jackets mountian long,Before we knew we could!There can be miracles!
Left by discount mens moncler down coat on Feb 24, 2010 10:54 PM

# discount air jordan shoes 25 sales online

Requesting Gravatar...
YS0225A6 When you belive,Thogh hope is frail.It's hard to kill,Who knows what cheap prada shoes miracles,You can achieve,Whe you belive! Somehow you will,

You will when you belive new nike air max!And in this time of fear, When prayer so often proves in vain, Hope seems like the http://www.nikeaf1jordanshoes.com/summer birds. Too swiftly flown away, And now I am standing wholesale gucci shoes here.My heart's so full I can't explain.Seeking faith and speaking women's nike shox words I never thought I'd say, They don't always happen when you ask authentic air jordan shoes.And it's easy to give in to your fear. But when you're blinded by your pain!
Left by discount mens moncler down coat on Feb 24, 2010 10:55 PM

# discount air jordan shoes 23 sales online

Requesting Gravatar...
YS0225A7 when the sun hugs the moon, the sky clses her eyes.when the sun hug the moon the sea quiet her jordans shoes.when the sun hugs the moon,the forest stops her susurrus.when the sun hugs the nike sb dunk high,the desert hodlds her breathe.Thousands of years's waiting is only for this nike acg shoes moment.Never be disappointed.Never give up.It hax been sucha long time.At nike air max 2003 this momentmeet each other in ourse of time.Do not cry,Moon.I guard you forever.Cause you are in my life,everyting has its meaning.The fascinating Diamond Ring,is the ring i give you,May it give you warm http://www.nikejordanshoes2sell.com/ threduce your tears.Do not cry,Sun,I will be there with you forever/Meeting you has given me precious memeory.The resplendent Baily Beads.is the gem i give you .May i give you cheap air jordan 22 shoes strength, shine in your morning.Meet soon and part soon.It makes peop;e retrospect in spite of lasting a few minutes.A long times waiting is coming.Don't know when the next meeting is .When the sun hugs the Moon. the Moon hugs the sun as well Hugging tightly,regian the lost nicety.
Left by discount nike air max shoes sale on Feb 24, 2010 10:56 PM

# discount Ugg Broome Boots in chestnut leather online sales

Requesting Gravatar...
YS0225A8 Before there was no reason in the world,As now there is!The moncler jackets course of water was my only course,My repetitions oceans' sough and swell ugg adirondack boots!My seasons pleasurable,Before there was reason in the world,As now there is ugg broome boots!To measure time from sleep I rose to sleep,To measure space I pastured on surprise http://www.edhardy-buy.com/,O meadows of resemblances,I was the grove on whose mosaic floors,The moncler online seeds of otherwise were spent,My gods had many arms,I was the Caesar of unmarshaled grass ugg boots!Faustus in the branches,My first ambitions were my sorrows long!Before there was no reason in the world,As now there is!
Left by discount womens moncler jacket on Feb 24, 2010 10:57 PM

# discount christian louboutin sandals online sales

Requesting Gravatar...
YS0226A1 That your heart has been broken,Hear the words,I'm here, my child,;And know your christian louboutin uk anel has spoken.For even in the darkest hour,When all of discount louboutin shoes hope seems gone,They'll give you strength to live your life,And desire to go on.And if your faith in Heaven, Should ever fade away,They'll help renew your christian louboutin boots spirit, And help you find your way.Even though you're ever filled with doubt, About the christian louboutin pumps life you live,Know that they are there to give you All that they can give.For you see, the Father sent them,Because to Him, you mean so much,That He sent them just for you,my louboutin sale friend,And your life, they will touch.They will always be here,They will never leave your http://www.christianlouboutinshoestore.com/ side;And upon their strength and guidance,You always may rely.Take comfort in their guidance, Draw strength from up above,And know that their sweet presence,Is God's precious gift of love.
Left by cheap christian louboutin shoes on Feb 25, 2010 2:59 PM

# discount women's ugg elsey boots 5596 sales online

Requesting Gravatar...
YS0226A2 If I wer a boy again, I would practice perseverance more often, and never give up a thing because it was ugg australia boots or inconvenient. If we want light, we must conquer darkness. Perseverance can sometimes equal genius cheap ugg boots in its results. “There are only two creatures,” syas a proverb, “who can surmount the pyramids—the eagle and the snail.” If I were a uggs sale boy again, I would school myself into a habit of http://www.topsnowboots.com/ attention; I would let nothing come between me and the subject in hand. I would remember that a good skater never tries to skate in two ugg cardy boots directions at once. The habit of attention becomes part of our life, if we begain early enough. I often hear cheap gucci shoes grown up people say “ I could not fix my attention on the sermon or ugg coquette book, although I wished to do so” , and the reason is, the habit was not formed in youth.
Left by cheap ugg upside boots 5163 on Feb 25, 2010 3:01 PM

# discount Women's ugg adirondack boots II sales online

Requesting Gravatar...
YS0226A3 Hold fast t dreams.For if dreams die. Life is a broken-winged bird,That ugg australia boots can never fly.Hold fast to dreams. For when dreams go,Life is a barren ugg tall boots field, Frozen only with snow !You never know until you try; And you never try unless you really try ugg cardy boot. You give it your best shot; You do the best you can. And if you have done everything http://www.uggsnowbootsbest.com/! In your power,and still,The truth of the uggs argyle knit matter is! That you haven\'t failed at all.When you reach for your dreams,No matter what ugg boots they may be,You grow from the reaching;You learn from the trying;You win from the doing.
Left by cheap ugg classic cardy boots on Feb 25, 2010 3:05 PM

# discount reebok nfl jerseys online sales

Requesting Gravatar...
YS0226A4 A friend is someone who reaches for your hand and touches your cheap hockey jerseys heart.There's always going to be people that hurt you,so what you have to do is keep on trusting nfl jerseys and just be more careful about who sport jerseys you trust next time around.Make youself a better person and know who you are discount nba jerseys before you try and know someone else and expect them to know you mlb jerseys on sale.Remember:Whatever happens,happens for a reason.How many people actually have 8 true http://www.nfljerseymlb.com/friends Hardly anyone I know.But some of us have all right friends and good friends.
Left by cheap adiads nba jerseys sale on Feb 25, 2010 3:09 PM

# discount ugg sienna miller boots 5818 sales online

Requesting Gravatar...
YS0226A9 Unweed still, lover by lover,They paddle in the cold,Companionable ugg australia shoes streams or climb the air;Their hearts have not grown old;ugg coquette Passion or conquest, wander where they will, Attend upon them still ugg adirondack boots. But now they drift on the still water, Mysterious, beautiful; Among what http://www.uggboots4buy.com/ rushes will they build, By what lake’s edge or pool,Delight men’s mbt shoes eyes when I awake some day.To find they have flown uggs classic cardy away?Before there was no reason in the world As now there is I was the bough bent easy by a ugg boots bird I was the vague blue-grazing flock The sleeping and invisible!
Left by cheap women's ugg elsey boots on Feb 25, 2010 3:12 PM

# discount mens air jordan shoes 13 online sales

Requesting Gravatar...
YS0226A10 When you ar old and gray and full of sleep,And nodding by the moncler jackets fire, take down this book! And slowly read jordans sheoes , and dream of the soft look,Your eyes had once, and of their cheap nike shoes shadows deep;How many loved your moments of glad grace,And loved your beauty with nike air force 1 love false or true; But one man loved the pilgrim soul in you,And http://www.onestop-onlineshopping.com/ loved the sorrows of your changing face; And bending down beside the designer clothing glowing bars,Murmur, a little sadly, how love fled.And paced upon the mountains overhead discount air jordan shoes,And hid his face amid a crowd of stars.
Left by cheap nike air max 90 online on Feb 25, 2010 3:23 PM

# discount louis vuitton damier canvas handbags online sales

Requesting Gravatar...
YS0226A11 Surunding you are angels,They are there to guide your path.If designer purses weaesskn overcomes you,They'll give you strength if you will ask. They are your protection.When discount designer bags on sale life seems too hard to bear,And though you feel alone at times, The louis vuitton 2009 angels ... they are there.Their faces may be hidden And their voices you might not hear,But they are ALWAYS with you,Through your laughter or your tears.http://www.handbags4buy.com/ They'll walk along beside you,They'll guide your leather handbags steps along the way, They'll comfort you and hold you,Protect you dior handbags night and day.They'll hold to your hand tightly ,They'll not ever let it go,And they'll gently lead you cheap designer handbagsforward,Taking each step very slow.For even as you slumber,They watch closely over you;They are there beside you. In each and every thing you do.
Left by cheap nike air max 90 online on Feb 25, 2010 3:26 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...

wedding dresses,wedding gowns,bride dresses,bridesmaids dresses,evening dresses,bridal gowns,flower girl dresses
Wedding Gowns
Formal Gowns
Cocktail Gowns
Find the wedding dress designer and wedding dress that's right for you! Browse dresses from
Bridesmaid Gowns
Evening Gowns
View our selection of exquisite, handmade gowns and dresses for your wedding
Wedding Dresses, Wedding Shoes and Wedding Accessories from wedding shop, the UK's finest collection of designer wedding dresses.
Use the wedding dress and
cheap wedding
wedding dresses
wedding shop


wwwww
Left by sbb on Mar 02, 2010 8:11 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
I was very pleased to find this site.
Left by ucvhost on Mar 06, 2010 2:36 AM

# ugg boots

Requesting Gravatar...


they are very good and useful!!!
ugg outlet
cheap uggs
nike shoes
wholesale watches 854
Left by ugg boots on Mar 07, 2010 5:32 PM

# ugg boots

Requesting Gravatar...


they are very good and useful!!!
ugg outlet
cheap uggs
nike shoes
wholesale watches 854563
Left by ugg boots on Mar 07, 2010 5:32 PM

# re: How to configure Log4Net for use with NHibernate

Requesting Gravatar...
It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks Don’t stop writing, you’ve given me lots of good info! Youtube to MP4 Converter
Convert PDF to image
23ra
Left by powerpoint on Mar 08, 2010 2:23 PM

# ugg classic tall

Left by chanel handbags on Mar 09, 2010 2:10 AM

Your comment:

 (will show your gravatar)
 
Please add 6 and 3 and type the answer here: