views:

116

answers:

2

here is in C#:

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

Not only in C# but another language i saw the same.. any thought?

+12  A: 

It's private because other classes should not access MyClass' log.

It's static because it doesn't depend on the class instance. (And so that it can be used by static methods)

SLaks
ah.. nice.. thanks..
ktutnik
Would there be any performance loss if the field is not static? Or is it a matter of making it syntaticaly correct?
jpartogi
@jpartogi: If `GetLogger` is an expensive call, or if each `ILog` instance uses a lot of memory, definitely. Otherwise, not much.
SLaks
+2  A: 

So that the field isn't inherited by your sub-classes.

Take this example:

class BaseFoobar
{
   public static readonly ILog log = LogManager.GetLogger(typeof(BaseFoobar));
}

class SpecializedFoobar : BaseFoobar
{
   public void Whatever()
   {
      log.Error("I exploded");
   }
}

If SpecializedFoobar's Whatever() function is ever called the co-responding log would be invalid:

[MyApp.BaseFoobar]: ERROR: I exploded

Aren
thanks for the complete explanation about inheritance problem, but sorry i should choose Slaks answer because he describe about the static too.
ktutnik