StockBreak
StockBreak

Reputation: 2895

Log specific NHibernate SQL queries

I know how to configure NHibernate and log4net to log the resulting SQL of my queries. Is it possible, however, to log only specific queries (for example activating the logging activity before a LINQ query and deactivating it right after the query)?

Upvotes: 0

Views: 472

Answers (2)

Frédéric
Frédéric

Reputation: 9864

You may log the SQL by yourself with an interceptor, which you would enable when needed.

public class SqlLogInterceptor : EmptyInterceptor
{
    private static readonly ILog _log =
        LogManager.GetLogger(typeof(SqlLogInterceptor ));

    public bool Enabled { get; set; }

    public override SqlString OnPrepareStatement(SqlString sql)
    {
        // Adjust your log level as you see fit.
        if (Enabled)
            _log.Info(sql);
        return sql;
    }    
}

When opening the session, provide an instance of the interceptor to OpenSession and keep a reference on it.

Set its Enabled property when you need your logging. Provided you have used the interceptor instance with only one session, it will then log only that session SQL.

Parameter values will not be logged with this solution.

Upvotes: 0

Joe Alfano
Joe Alfano

Reputation: 10299

You can programmatically add and remove appenders to an instance of log4net. So what you could do is when you hit a query that you want to log, programmatically add a new appender, run the query, and then programmatically remove the appender. I have not tested this but I think this should be possible.

Here is a reference for how to programmatically add appenders.

Upvotes: 2

Related Questions