本文介绍了Nhibernate - 使用特定 ISession 或 ISessionFactory 的日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用的是 NHibernate 3.2.

We're using NHibernate 3.2.

我希望能够记录来自特定 ISession 的 SQL 查询.这可能吗?

I'd like to be able to log SQL queries from a specific ISession. Is that possible?

或者,如果这是不可能的,我可以将记录器设置为特定的 ISessionFactory 吗?然后我可以从这个特定的工厂创建这个 ISession.

Alternatively, if that is not possible, could I set a logger to a specific ISessionFactory? Then I could create this ISession from this specific factory.

据我所知,要设置记录器,您必须执行以下操作:

From what I saw, to set the logger, you have to do something like that:

<appSettings>
       <add key="nhibernate-logger" value="NH3SQLLogger.LoggerFactory, NH3SQLLogger" />
</appSettings>

但是,这将使所有工厂的设置全局化.

However, that would make the setting global for all the factories.

我可以这样做吗:

        var config = new Configuration();
        config.Configure();
        config.SetProperty("nhibernate-logger",
                       "NH3SQLLogger.LoggerFactory, NH3SQLLogger");
        _sessionFactory = config.BuildSessionFactory();

那行得通吗?或者有其他方法吗?

Would that work? Or is there another way?

推荐答案

不,你只能全局指定一个记录器.做你想做的事情会相当复杂.

No, you can only specify a logger globally. To do what you want would be fairly complicated.

您需要:

  1. 编写您自己的 ILoggerFactory 实现
  2. 从 NHibernate.SQL 捕获日志数据以捕获所有 SQL
  3. 从 NHibernate.Impl.SessionImpl 捕获日志数据,以捕获生成 SQL 的 ISession 和 ISessionFactory.
  4. 编写逻辑以忽略除您命名的 ISessionFactory 生成的 SQL 之外的所有 SQL.

以下是一些帮助您入门的代码:

Here's some code to get you started:

public class LoggerFactory : ILoggerFactory
{
    #region Implementation of ILoggerFactory

    /// <summary>
    /// Returns the logger for a given key name
    /// </summary>
    /// <param name="keyName">Key or class name</param>
    /// <returns>Logger</returns>
    public IInternalLogger LoggerFor( string keyName )
    {
        if ( string.IsNullOrWhiteSpace( keyName ) )
            return new NoLoggingInternalLogger();

        switch ( keyName )
        {
            case "NHibernate.SQL":
                return new SqlLogger(); // Create this class to capture the SQL
            case "NHibernate.Impl.SessionImpl":
                return new SessionLogger(); // Create this class to capture ISession-related stuff
            default:
                return new NoLoggingInternalLogger();
        }
    }

    /// <summary>
    /// Returns the logger for a given type
    /// </summary>
    /// <param name="type">Class name</param>
    /// <returns>Logger</returns>
    public IInternalLogger LoggerFor( Type type )
    {
        return LoggerFor( type.FullName );
    }

    #endregion Implementation of ILoggerFactory
}

这篇关于Nhibernate - 使用特定 ISession 或 ISessionFactory 的日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:29