Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j, patternLayout, class and category

I am having trouble establishing the exact difference between using those two log4j conversion characters when used in a log4j PatternLayout (log4j patternLayout)

  • category (%c)
  • class (%C)

Can someone please give me an example where those two would be different?

Doesn't the category always match the class name?

Regards,

like image 885
balteo Avatar asked Oct 19 '11 14:10

balteo


1 Answers

It will be the same if you initialize the logger in the popular way suggested by the documentation, and use it inside the X class:

Logger logger = Logger.getLogger(com.foo.X.class);

then you'll get the same for %c and %C, because logger name (constructed by "com.foo.X.class.getName()") would match the class name where a logging statement was issued.

Call your logger "something"

Logger logger = Logger.getLogger("something");

and you'll have "something" for %c and the class name for %C.

Note that %C is computed by log4j out of the current thread's stack trace, so it carries big performance impact, unlike %c, which is simply a String. You can conduct an interesting experiment to validate it:

package com.foo;

class A {
     private Logger = Logger.getLogger(B.class);
     // ...
     logger.log("inside A class");
}

The output for pattern [%c][%m] assuming B is in package com.foo will be:

[com.foo.B][inside A class]

The output for pattern [%C][%m] regardless of the location of B will be:

[com.foo.A][inside A class]
like image 78
MaDa Avatar answered Oct 07 '22 23:10

MaDa