Monitoring NHibernate

April 2nd, 2008

At this time, the NHibernate API don't provide a way to obtain generic statistics (like we have on Hibernate). But monitoring an ORM mapper is very important to make sure you're not being stabbed in the back by some lazy parameters, or even to make sure that you aren't fetching more information than you really should.

While the NHibernate API won't help us at this time, we can use something to get some top level statistics. We can use an IInterceptor with only one job: store statistics. We can attach the interceptor when we open a session:

C#:
  1. public static ISession OpenSession()
  2. {
  3. #if INCLUDE_STATS_INTERCEPTOR
  4.         return Factory.OpenSession(new StatsInterceptor());       
  5. #else
  6.         return Factory.OpenSession();
  7. #endif
  8. }

The StatsInterceptor is a very simple class that implements IInterceptor:

C#:
  1. public class StatsInterceptor : IInterceptor {
  2.  
  3.     ...
  4.  
  5.     #region IInterceptor Members
  6.  
  7.     ...
  8.  
  9.     public object Instantiate(Type type, object id)
  10.     {
  11.         Statistics.AddInstantiate(type.Name);
  12.         return null;
  13.     }
  14.  
  15.     public void OnDelete(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
  16.     {
  17.         Statistics.AddDelete(entity.GetType().Name);
  18.     }
  19.  
  20.     public bool OnLoad(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
  21.     {
  22.         Statistics.AddLoad(entity.GetType().Name);
  23.         return false;
  24.     }
  25.  
  26.     public bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
  27.     {
  28.         Statistics.AddSave(entity.GetType().Name);
  29.         return false;
  30.     }
  31.  
  32.     #endregion
  33.  
  34. };

Something like this will generate the following output:

NHibernate Stats
--
Flushes: 5
--
Loads:
- Principal : 17
- PrincipalRole : 1
- Role : 1
- EntityA : 2
- EntityB : 2
- EntityC : 1
- EntityD : 1
--
Saves:
--
Deletes:

If you need more hardcore methods to check NHibernate performance, check out this article: Identifying NHibernate Related Bottlenecks through Performance Monitoring.

Related Posts

2 Responses to “Monitoring NHibernate”

  1. Ayende Rahien Says:

    Note that NHibernate 2.0 does have the Statistics feature.

  2. Pedro Santos Says:

    Thank you for the intel.
    We’re still using NHibernate 1.2.