12

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,

mtk
  • 13,221
  • 16
  • 72
  • 112
balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

18

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]
Crowie
  • 3,220
  • 7
  • 28
  • 48
MaDa
  • 10,511
  • 9
  • 46
  • 84