2

I'm trying to use NLog (3.1) with Windsor Castle Facility, but it's not working for me (no errors, nothing happens)

These are my steps so far:

  1. Downloaded from Nuget: Castle Windsor NLog integration
  2. Downloaded from Nuget: NLog Configuration
  3. Updates nlog config like this:

    <target xsi:type="File" name="f" fileName="d:\nlog.log"
            layout="${longdate}|${level:uppercase=true}|${logger}|${message}" />
    

    <logger name="*" minlevel="Trace" writeTo="f" />
    

  4. Added Windsor Installer

     public class LoggingInstaller : IWindsorInstaller
     {
            public void Install(IWindsorContainer container, IConfigurationStore store)
            {
                container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.NLog).WithConfig("NLog.config"));
            }
    }
    

    Which I'm calling it (I've checked that a breakpoint in there is being hit.

  5. Added the logger class like this:

    namespace WebApi.App_Start
    {
        public class MyLogger
        {
            private ILogger logger = NullLogger.Instance;
    
            public ILogger Logger
            {
                get { return logger; }
                 set { logger = value; }
            }
        }
    }
    
  6. Using it in a controller like this:

    new MyLogger().Logger.Info("New Request Created.");
    

But I don't see the file created.

Any step missing?

Thanks in advance. Guillermo.

polonskyg
  • 4,269
  • 9
  • 41
  • 93
  • If you use `new MyLogger()` then Windsor won't know about it and won't inject the Logger. So need to have all the `private ILogger logger = NullLogger.Instance;` etc. code inside your controller class where you want to use the logger... – nemesv Dec 20 '14 at 21:35
  • @nemesv. The problem was having the step 5 in the App_Code class instead of having it in the controller. Please create an answer with that so I can choose it as correct. BTW, Do you know why it doesn't work in the App_Code class? Thx! – polonskyg Dec 21 '14 at 12:21

1 Answers1

0

You need to put the Logger property to every class where you want to log something and the instances of the class has to be created/managed by Windsor.

So you need to add it to your controller:

public class MyController : Controller
{
    private ILogger logger = NullLogger.Instance;

    public ILogger Logger
    {
        get { return logger; }
        set { logger = value; }
    }

    public ActionResult MyAction() 
    {
         Logger.Info("New Request Created.");
    }
}

It was not working with the MyLogger because that class was not managed/created by Windsor so it was not injected your Logger property. But because the controller isntances are created by Windsor and ILogger inejtion is wokring in them: Windsor Tutorial - Part Five - Adding logging support

nemesv
  • 138,284
  • 16
  • 416
  • 359