views:

28

answers:

2

I haven't been able to find much good documentation for Castle's logging facility, but reading here gives me enough to work with. I have one question though, how do you obtain a logger in situations where you can't use properties. Two examples I can think of are in a static method or inside of a struct.

Bonus points for any useful documentation of this facility.

A: 

Just get the logger from the underlying log implementation, e.g. for log4net:

    private static readonly ILog logger = LogManager.GetLogger(typeof(MyClass));

Using the container for this case is more complex and just pointless.

Logging facility docs are here.

Mauricio Scheffer
BTW what's missing in the docs?
Mauricio Scheffer
That kind of defeats the purpose of using a container.
brian
and the docs (I use plural lightly because it's a single anemic wiki page) are missing, just as an egregious example, what method to call to log a message.
brian
@brian: **having static stuff** is what defeats the purpose of using a container.
Mauricio Scheffer
@brian: do you mean ILogger methods? Debug, Warn, DebugFormat, etc? Do they really have to be documented? They are pretty standard, used by most (all?) logging libraries. The wiki is open for anyone to edit it, please add that information is you feel it's relevant.
Mauricio Scheffer
@Mauricio can you explain why that defeats the purpose of using a container? What about logging inside of structs?
brian
@brian: a struct is a data container. I wouldn't log anything there. I would log any *operations* on that struct, operations that happen in Windsor-managed services, where you can inject ILogger without issues. Data containers are 99% of the time **not** managed by DI/IoC containers.
Mauricio Scheffer
A: 

I don't use Castle or any other DI/IoC at the moment, so I can't comment on the validity or not or logging a static or a struct...

Having said that, it seems like it should not be too difficult to log from a static method (on a non-static class). It might be cheesy, but I suppose you could do something like this:

public class MyClass
{
  private ILogger logger = NullLogger.Instance;
  private static ILogger staticLogger;

  public ILogger Logger 
  { 
    get
    {
      return logger;
    }
    set 
    {
      logger = value; 
      if (staticLogger == null)
      {
        staticLogger = value;
      }
    }
  }

  public void MyMethod()
  {
    logger.Info("Hello from instance method!");
  }

  public static void MyStaticMethod()
  {
    staticLogger.Info("Hello from static method!");
  }
}

Probably have to be careful not to log with the static logger before the real logger gets injected.

wageoghe