José F. Romaniello

Las aventuras y desventuras de un codificador.

I will show you in this post two tricks you can do to enhance and add value to your nhibernate logs.

Format Sql

This is widely know trick, you can add a configuration setting to your hibernate.cfg.xml, app.config or web.config as follow:

<property name="hibernate.format_sql" value="true" />

or you can simply do it in code:

config.DataBaseIntegration(db => db.LogFormatedSql = true)

with this trick you will get nicely formated sql in your logs files.

Logging the session identifier

All nice, we have a bunch of sql logs, but we don’t know which queries belongs to which sessions. This might be useful when you are debugging an application with multiples threads or requests.

I found this trick inside NHibernate, the easy way I found so far is to add a log4net appender like this one:

<appender name="NHibernateAppender" type="log4net.Appender.RollingFileAppender">
  <appendToFile value="true"/>
  <datePattern value="yyyyMMdd"/>
  <file value="./logs/NHibernate.log"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date Session id: %property{sessionId} - %message%newline"/>
  <rollingStyle value="Date"/>

See the %property{sessionId} in the conversion pattern?

Well, in order to log something there you need to do two steps.

Add a class like this one:

public class SessionIdCapturer
    public override string ToString()
        return SessionIdLoggingContext.SessionId.ToString();

Add the following code in some place at the application initialization:

ThreadContext.Properties["sessionId"] = new SessionIdCapturer();

That is all! I found this code inside a nhibernate test.. it is something not very known.

After doing so, your logs will look like:

2011-05-05 18:35:59,899 Session id: 5e172068-5064-44b6-bf96-99362ca05c46 - 
        myFoo0_.AccountId as AccountId3_0_,
        myFoo0_.Name as Name3_0_,
        myFoo0_.Version as Version3_0_ 
        MyFoo myFoo0_
    @p0 = 1 [Type: Int32 (0)]

Another way to have this information (and much more) is to use the nhprof tool.

| More

2 comentarios:

Mauricio Scheffer dijo...

I recommend also adding at least the requested URL. In fact I also add the client IP, referrer (when it exists) and user id (if user is logged in, of course). It bloats the log a bit, but when things go wrong (or for diagnostic purposes) it's totally worth it. I have all this stuff packed in a little HttpModule that sets up the ThreadContext when the request starts.

José F. Romaniello dijo...

mmmmmmmmmmmm thats super cool idea!, I am doing wcf right now, but i will
add those to the blog post. Thank you

Publicar un comentario en la entrada