Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j2 class name when using multiple loggers besides root

I'm using log4j2. I have defined multiple loggers, so that, my log4j2.xml looks like:

   <Property name="LOG_PATTERN">[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</Property>
   ...
   ...
   <Loggers>
        <Logger name="trace" level="INFO" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
        <Logger name="error" level="ERROR" additivity="false">
            <AppenderRef ref="errorLog" />
        </Logger>
        <Logger name="warn" level="WARN" additivity="false">
            <AppenderRef ref="warnLog" />
        </Logger>
   </Loggers>

Then I invoke them from code. Snippet:

Class myclass{
...

    Logger LOGGER1 = LogManager.getLogger("trace");
    Logger LOGGER2 = LogManager.getLogger("error");
...
     LOGGER1.trace("whatever message");

My problem is that, when invoking the logger from code, as far as I know, I get to specify the logger from log4j2.xml. For example, if I want to use "trace logger" I get to code LogManager.getLogger("trace")

Then, when "printing the log", %c{1} is not any longer the classname, it is the logger name... In this example, log4j2 will print as %c "trace" and not "myclass" (that is what I want).

I want to know, is it possible:

  • option 1. call a concrete logger, while printing the "real" classname (not the classname passed as parameter in the getLogger method),
  • option 2. using the classname in the gerLogger Method and them mapping this logger from code to a logger from the log4j2.xml

thanks in advance for your clues.

like image 750
David G. Hdez Avatar asked Sep 15 '26 09:09

David G. Hdez


1 Answers

In the log4j2.xml file, when defining the log pattern you can use two DIFFERENT things: "c" (lower case) and "C" (upper case).

  1. "c" will be log as the logger name and
  2. "C" will be log as the class where the logger was created (class where %M is been executed).

A possible pattern including the second would look something like:

<Property name="LOG_PATTERN">[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%C][%M] - %msg%n</Property>

more info here: http://logging.apache.org/log4j/2.x/manual/usage.html#LoggerVsClass

Anyway, the articles proposed by https://stackoverflow.com/users/1709216/rgoers previously, are a gold mine.

like image 154
David G. Hdez Avatar answered Sep 16 '26 22:09

David G. Hdez