Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does NHibernate implement optional log4net logging

I remember the days (not too long ago, really) when log4net came along with NH and was compulsory for the OR-Mapper. Nowadays it isn't compulsory anymore, but optional.

I really wonder how this is achieved by NHibernate. If anyone could explain in a few words, that would be highly appreciated!

like image 222
Sebastian Edelmeier Avatar asked Dec 26 '22 23:12

Sebastian Edelmeier


2 Answers

NHibernate has an ILoggerFactory to create the logger defined as below:

public interface ILoggerFactory
    {
        IInternalLogger LoggerFor(string keyName);
        IInternalLogger LoggerFor(System.Type type);
    } 

The IInternalLogger interface, that depites the name is not internal at all, is the actual logger interface, that non surprisingly map exactly the ILog interface of log4net. NH internally ask logger factory when it needs to log. If no other logger is configured, and log4net assembly is present, the factory return a wrapper around log4net. If you want provide your own you just need to provide a logger factory and configure it as:

 <appSettings>
        <add key="nhibernate-logger" 
                  value="MyLoggingLoggerFactory, MyLoggingAssembly"/>
    </appSettings>

As you guess, the class MyLoggingLoggerFactory must implement ILoggerFactory. The returned loggers of course must implement IInternalLogger, that as said before is public even if the unhappy name can be misleading. This is the startegy they use to be log4net independent. As an addition, if you don't want log at all, just remove the log4net assembly from your deploy directory: NH will degrade gracefully and use internally a null logger.

like image 112
Felice Pollano Avatar answered Feb 02 '23 03:02

Felice Pollano


NHibernate no longer references log4net.dll. It does have its own logger abstraction layer, however, they do have a built-in implementation of their own logger abstraction that is designed for log4net.

They accomplish this by forcing the CLR to load the log4net assembly using reflection, when you configure NHibernate to use log4net, of course. See NHibernate.Log4NetLogger and NHibernate.Log4NetLoggerFactory using your favorite reflector, if you're interested in more.

like image 36
moribvndvs Avatar answered Feb 02 '23 04:02

moribvndvs