0

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)?

2 Answers 2

2

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.

3
  • Thank you. Is it, in your opinion, the right way to log only specific (complex) queries?
    – StockBreak
    Commented Jan 18, 2012 at 20:03
  • Yes, this is the way I would try doing it. You should be able to programmatically turn on the desired logging, execute your query, and then turn off the logging. I am pretty sure something along this line will work; however, I have not personally tested this out myself.
    – Joe Alfano
    Commented Jan 18, 2012 at 20:11
  • It will cause queries of concurrent sessions to be logged by the way. But I do not think another solution is available if the OP want to use NHibernate built-in logging, not some custom one.
    – Frédéric
    Commented Jul 16, 2017 at 19:08
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.