Michael
Michael

Reputation: 1421

How do I trap query execution in NHibernate 5?

I'd like to be able to put a try/catch around SqlCommand.ExecuteReader and the like, so that I can catch ADO exceptions and log the offending query with better information than is contained in the exception that gets thrown by NH. I've tried to get there in various ways, like overriding SqlClientDriver to return my own version of SqlCommand, but between the fact that the interface changed with NH5 to using DbCommand rather than IDbCommand (so I can't use a proxy) and the fact that SqlCommand itself is sealed (so I can't use a subclass), I've been stymied.

To be clear: I don't want to simply translate the exception. I want all the information about the original query in hand wherever I catch it.

Thanks.

Upvotes: 1

Views: 44

Answers (1)

Amit Joshi
Amit Joshi

Reputation: 16409

Exception thrown by NHibernate includes the query itself. I am not sure what "all the information" means.

Other alternative is to log the generated SQL using Log4Net:

Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders();

FileAppender fileAppender = new FileAppender();
fileAppender.Name = "NHFileAppender";
fileAppender.File = config.LogFilePath;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.Layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss}:%m%n%n");
fileAppender.ActivateOptions();

Logger logger = hierarchy.GetLogger("NHibernate.SQL") as Logger;
logger.Additivity = false;
logger.Level = Level.Debug;
logger.AddAppender(fileAppender);

hierarchy.Configured = true;

This logs both success and failed statements. You can play with PatternLayout aand GetLogger to get additional information about query.

Upvotes: 1

Related Questions