1

Just wondering if I am doing this right:
I declare Log4Net object:

private static readonly log4net.ILog _log = log4net.LogManager.GetLogger
        (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

And then in methods in whole class when log I just use:

_log.Debug("passing...");

Is this ok or I should declare and use Log4Net object inside methods (instatiate _log in every method)?

1110
  • 7,829
  • 55
  • 176
  • 334
  • is better the way you are using now. I generally have the logger instantiated in the cinstructor, or sometimes injected by IOC with the proper declaring type. – Felice Pollano Apr 07 '14 at 10:16
  • 3
    I'd at least shorten it down to `LogManager.GetLogger(typeof(MyType))`, I don't see what the reflection buys you. – khellang Apr 07 '14 at 10:26
  • Apart from different techniques for configuration and starting long4net up, I guess you can use GetLogger freely everywhere and count on intelligence of the log4net writers to returning a cached-version each time (if you are concerning performance matters) – Ali Dehghan Apr 07 '14 at 10:27
  • I would drop the usage of the reflection at all, initialize it using the name of the class into a string `LogManager.GetLogger("myClass")` – Menelaos Vergis Apr 07 '14 at 12:13
  • 1
    @MenelaosVergis ah but then if the type name changes your logger name is now wrong, but if you use `typeof(…)` then the name is updated when the type name changes – stuartd Apr 07 '14 at 15:14
  • @stuartd well it's a matter of codding process. I always put the logger at the top of my class, If I change the class name it's very easy to spot the logger and change the text there too. I do this because I know that reflection is something that is relative slow and this is something that it can help the overall speed of my app. Nothing much, I know, but why not? – Menelaos Vergis Apr 08 '14 at 08:37
  • @MenelaosVergis I was under the impression that `typeof(…)` is determined at compile time with no need for reflection. – stuartd Apr 08 '14 at 09:21
  • @stuartd well you are right, it's determined at compile time. I wonder why I am not using this, thanks for that – Menelaos Vergis Apr 08 '14 at 13:40

1 Answers1

2

The way you do it is better than declaring the logger in every method. The name of the method you are in can be found again by walking up the call stack, which is described here so initializing logs in each method would be counterproductive since reflection would eat some time at each call.

Even with a static object the reflection calls to resolve your class names take some resources but until you time them you won't know how they impact you. If you start to observe a long delay at startup it may be because the loggers initialisation is run as the classes types are resolved. If so then you will need to optimize. But for now, don't bother, you're doing it right

Community
  • 1
  • 1
samy
  • 14,832
  • 2
  • 54
  • 82