Subclass org.apache.log4j.Logger without changing% C?

To enable features such as

logger.info("This is a formatted number: %.2f", number) 

I decided to write a subclass of org.apache.log4j.Logger . I know I could write a wrapper class to achieve the same result, but since I add a lot of additions to the log at runtime, I prefer to use inheritance.

The subclass is as follows:

 public final class FormatLogger extends Logger { private final static FormatLoggerFactory factory = new FormatLoggerFactory(); protected FormatLogger(String name) { super(name); } public static Logger getLogger(String name) { return Logger.getLogger(name, factory); } public void fatal(String formatter, Object... args) { log(Level.FATAL, formatter, args); } public void log(Level level, String formatter, Object... args) { if (super.isEnabledFor(level)) { super.log(level, String.format(formatter, args)); } } } 

Everything works well - all but one: the message text now adds the name of the journal subclass, rather than the name of the class that calls the registrar. As a template for the template, I use the following format:

 [%d{yyyyMMdd HHmmss}] %-5p [%t] %C: %m%n 

i.e. it looks like this:

 [20110525 214515] INFO [main] org.xyz.FormatLogger: This is a formatted number: 23.23 

instead:

 [20110525 214515] INFO [main] org.xyz.Main: This is a formatted number: 23.23 

Is there a way to do this β€œcorrectly” so that β€œ% C” continues to print the original class name?

+6
source share
3 answers

The solution is quite simple: add the fully qualified class name (FQCN), i.e.:

 static String FQCN = FormatLogger.class.getName() + "."; 

Then the log (..) method should be modified as follows:

 super.log(FQCN, level, String.format(formatter, args), null); 

This is perfectly shown in the MyLogger.java example that comes with log4j. -1 for my laziness!

+1
source

I did something similar, but in the end I created a wrapper and passed the class name to it. Then, with this class name, I added it in front of all four levels of logging that I have already recruited. This is pretty dirty, but I could not find another way to do this. My registration statements now flatten out the name of the registrar and then the name of the package / class. This is a bit cumbersome, but I would rather get more information without having enough information.

+1
source

Remove the "." at the end of the FQCN line to log in correctly with Log4J version 1.2.16 or later.

+1
source

Source: https://habr.com/ru/post/889040/


All Articles