How to configure log4net separately for each Sessi

2019-08-16 16:45发布

My application uses two databases. Obviously, there is one session factory for each database; total two.

I have configured log4net for NHibernate to emit the generated SQL. But, this writes the log in single file for both the session factories. I want to configure different log file for each session factory.

Following is my code:

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

FileAppender fileAppender = new FileAppender();
fileAppender.Name = "NHFileAppender";
fileAppender.File = logFilePath;
fileAppender.AppendToFile = false;
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;

As you can see in above code, there is no any way to configure different log file for each session factory. If I am understanding this correctly, there should be a way to link/assign session factory to logger OR logger to session factory.

Is this possible? If yes, how?

1条回答
倾城 Initia
2楼-- · 2019-08-16 17:14

As commented by @RomanKoliada, following is copied from here:

NHibernate logging in Visual Studio output window
NHibernate 'show_sql=true' does not log the generated queries to the output window of Visual Studio when working in ASP.NET MVC 4. I made a simple implementation for logging NHibernate queries in Visual Studio's output window, without use of third party loggers.

Create an interceptor class, and override one method view sourceprint?

public class NHLogger : EmptyInterceptor, IInterceptor
{
    public override NHibernate.SqlCommand.SqlString 
       OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        System.Diagnostics.Debug.WriteLine("NHIBERNATE: " +  sql);
        return base.OnPrepareStatement(sql);
    }
}

Then create an instance of it in the OpenSession of the Factory.

 SessionFactory.OpenSession(new NHLogger());

This is not exactly what I need; but better than what I was already using. I am still open for better solution.

查看更多
登录 后发表回答