Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject logger using NLog

Tags:

c#

nlog

ninject

I've just started learning Ninject but have come across a problem with the logger. I've currently got a controller that has a service and logger injected into the constructor like so:

public ToolsController(IToolsService toolsService, ILogger logger)
{
    logger.Info("ToolsController Created");
    this.toolsService = toolsService;
    this.logger = logger;
}

The problem is on the logger.Info line (for example) in the constructor which seems to use the wrong logger, so the logger name it prints out is incorrect.

Tools.IGeocodeImporter: ToolsController Created 

Below is how it is setup to get the logger name:

kernel.Bind<ILogger>().To<Logger>().WithConstructorArgument("name", x => x.Request.ParentContext.Request.Service.FullName);

Any advice would be appreciated.

like image 979
user1883004 Avatar asked Dec 06 '12 16:12

user1883004


3 Answers

I use the following:

.Bind<ILog>().ToMethod(p => LogManager.GetLogger(
                   p.Request.Target.Member.DeclaringType));

To have the logger with the name of the class. I'm using Log4net, but I think the idea can be applied to any log as well: in fact binding to a method open you to any solution in order to create the needed instance.

like image 91
Felice Pollano Avatar answered Nov 05 '22 17:11

Felice Pollano


I use a ninject extension called Ninject.Extensions.Logging.NLog2, which can be found on NuGet or GitHub. It handles the binding of NLog, so you don't have to do anything else than just add it to your project and remove any bindings to NLog that you have right now.

like image 31
gligoran Avatar answered Nov 05 '22 17:11

gligoran


As Felice mentioned you can use the same method, However for Nlog you need a little bit change which is :

.Bind<ILogger>().ToMethod(p => NLog.LogManager.GetCurrentClassLogger(
                   p.Request.Target.Member.DeclaringType));
like image 2
Hosein Djadidi Avatar answered Nov 05 '22 17:11

Hosein Djadidi