1

I have 3 different Application. I have log4net in a shared library which be shared among 3 application. Is it a bad practice to use the same logger for all the 3 services. I have written something like this

public class Log4netLogger
{
       private ILog _logger = null;
       public Log4netLogger(ILog logger)
       {
           _logger = logger;
       }



       public void write(Level logLevel, string message)
       {
          _logger.Logger.Log(_logger.GetType(),logLevel,message,null);
       }
}

and in my Application 1 app_start i am injecting like this

 myContainer.RegisterType<ILog>
                        (
                            new ContainerControlledLifetimeManager(),
                            new InjectionFactory(x => LogManager.GetLogger("Application 1"))
                        );

And in my code i am using like

 _logger =  myContainer.Resolve<log4net.ILog>();
 Log4netLogger logMessage= new Log4netLogger(_logger);
 logMessage.Write
             (
                 log4net.Core.Level.Info,
                 logMessage
              );

Also i one of the negatives that i think with this approach is i have install log4net in all of my 3 applications. So i am wondering whether i am doing something wrong or is there any better approach ?

Vivekh
  • 4,141
  • 11
  • 57
  • 102

1 Answers1

0

It's good decision, if you loose coupling of Log4net. Then, You can put your logger a different project and shared by all applications. If you want and need you can hide implemantation from middleware projects (services,dal vs..) you can seperate interface and implemeantation to different projects.

Then your middleware classes just know about interface and you can change implemantation of logger without rebuilding or re-deploy this services(loose dependency).

But you can't run your driver projects(main projects) without implemantation, they have to know implemantation of Log4Net (or another library which uses same interface).

For loosing coupling: your services should use your Interface not log4net.ILog.

I'm not experienced about log4net. But here, they used factory for log4net. This is good, your services will know your factory not Log4Net and your factory will know about (Log4Net).

Code on link:

public interface ILoggerFactory
{
    ILogger Create(Type type);   
}

public class LoggerFactory : ILoggerFactory
{
    public ILogger Create(Type type)
    {
        return new Log4netLogger(type);
    }
}

But I say again you can't loose coupling on top level(driver) projects because they have to know all implematations otherwise they can't inject.

Community
  • 1
  • 1
Erkan Demirel
  • 4,302
  • 1
  • 25
  • 43
  • Yeah i had that in mind but to specify the logging level to Write Method the calling application should have log4net – Vivekh Mar 29 '16 at 07:50