Intercept SQL statements containing parameter values generated by NHibernate

1,341 views
Skip to first unread message

kaivalya

unread,
May 18, 2011, 3:38:17 PM5/18/11
to nhusers
I use a simple interceptor to intercept the sql string that nhibernate
generates for loging purposes and it works fine.

public class SessionManagerSQLInterceptor : EmptyInterceptor,
IInterceptor
{
NHibernate.SqlCommand.SqlString
IInterceptor.OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
{
NHSessionManager.Instance.NHibernateSQL = sql.ToString();
return sql;
}
}

This however captures the sql statement without the parameter values..
They are replaced by '?'

Eg: .... WHERE USER0_.USERNAME = ?

The only alternative approach i found so far is using log4nets
nhibernate.sql appender which logs sql statement including parameter
values but that is not serving me well..

I need to use an interceptor so that for eg. when i catch an exception
i want to log the specific sql statement that caused the persistence
problem including the values it contained and log it mail it etc. This
speeds up debuging great deal compared to going into log files looking
for the query that caused the problem..

How can i get full sql statements including parameter values that
nhibernate generate on runtime?

Fabio Maulo

unread,
May 18, 2011, 3:48:25 PM5/18/11
to nhu...@googlegroups.com
1) activating the SQL log and writing a log4net appender (same tech used by NHProf)
2) writing your custom IDriver; with it you can do anything you have in mind.

kaivalya

unread,
May 18, 2011, 3:54:43 PM5/18/11
to nhusers
Thank you for your reply, Fabio.

Am i understanding correct that this will be fairly complicated either
way?

Can you point me to any code examples or references to either approach
that could help me navigate to what i need..

Thanks

Vahid

unread,
May 18, 2011, 4:06:16 PM5/18/11
to nhusers
No, it's very easy with NH 3.0+. here you can find an example:
http://nh3sqllogger.codeplex.com/

kaivalya

unread,
May 18, 2011, 4:31:15 PM5/18/11
to nhusers
Thanks. Example shows how to register it on web.config but does not
show which methods to call to get the generated sql .. Can you tell?
Reply all
Reply to author
Forward
0 new messages