Java – how do I get a subclass recorder?
I have a subclass and a superclass In superclasses, I have a way to record something When I create an instance of a subclass, the logger will create a logging message for the superclass Why did this happen?
Code example:
SuperClass. java
import java.util.logging.Level; import java.util.logging.Logger; public abstract class SuperClass { public void logAndPrintClass(){ String name = this.getClass().getName(); System.out.println(name); Logger logger = Logger.getLogger(name); logger.log(Level.INFO,"Logmessage"); } }
SubClass. java
public class SubClass extends SuperClass { }
TestLogBubClass. java
public class TestLogBubClass { public static void main(String[] args){ SuperClass obj = new SubClass(); obj.logAndPrintClass(); } }
Output:
SubClass Mar 15,2013 6:30:04 PM SuperClass logAndPrintClass INFO: Logmessage
As you can see, the class name is printed correctly, but it is incorrectly represented in the log message
Solution
The reason is that in Javadoc for LogRecord:
In this case, the call stack ends with a superclass defined method, so LogRecord assumes that it is the called class If you want to view this action, execute the following code:
public class Example { public static class Superclass { public void foo() { new Exception().printStackTrace(); } } public static class Subclass extends Superclass { // nothing here } public static void main(String[] argv) throws Exception { Superclass s = new Subclass(); s.foo(); } }
Edit: I don't use j.u.l, but I want a simple way to configure the output (as provided by all other logger implementations) It seems that you must implement your formatter class and use Java util. logging. ConsoleHandler. The formatter property specifies it
If possible, I suggest switching to slf4j You can bridge all existing j.u.l codes to the actual recorder through slf4j, so that you can better control its output (such as log4j or logback)