Can anyone explain to me why, in the presence of a static initialization block, does the logger duplicate a message in the console?

Java Code:

public class LoggerProxy { private final static Logger log = Logger.getLogger(Example.class.getName()); /*static */{ // <- ΠΏΡ€ΠΈ Π½Π°Π»ΠΈΡ‡ΠΈΠΈ static, сообщСниС дублируСтся log.setLevel(Level.ALL); log.addHandler(new ConsoleHandler()); } public static void info(String msg){ log.info(messageFormat(new Exception(msg))); } public static void info(Exception ex){ log.info(messageFormat(ex)); } private static String messageFormat(Exception ex){ StackTraceElement[] stackTraceElement = ex.getStackTrace(); int index = 1; return String.format( "[%s/%s.%s()]: %s", stackTraceElement[index].hashCode(), stackTraceElement[index].getClassName(), stackTraceElement[index].getMethodName(), ex.getMessage() // OR -> ex.getLocalizedMessage() ); } public static void config(String msg){...} public static void config(Exception ex){...} public static void fine(String msg){...} public static void fine(Exception ex){...} public static void finer(String msg){...} public static void finer(Exception ex){...} public static void finest(String msg){...} public static void finest(Exception ex){...} public static void severe(String msg){...} public static void severe(Exception ex){...} public static void warning(String msg){...} public static void warning(Exception ex){...} public static void addHandler(Handler handler){...} public static void removeHandler(Handler handler){...} } 

Console:

 // ΠΏΡ€ΠΈ Π½Π°Π»ΠΈΡ‡ΠΈΠΈ static Π² Π±Π»ΠΎΠΊΠ΅ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ мая 02, 2018 7:17:25 ПП LoggerProxy info INFO: ... мая 02, 2018 7:17:25 ПП LoggerProxy info INFO: ... // ΠΏΡ€ΠΈ отсутствии static Π² Π±Π»ΠΎΠΊΠ΅ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ мая 02, 2018 7:17:25 ПП LoggerProxy info INFO: ... 
  • 2
    Try log.addHandler(new ConsoleHandler()); out the line log.addHandler(new ConsoleHandler()); - not a Programmer
  • Eh, I should have dealt with the initialization block a bit better ... First, I forgot that the dynamic initialization block is executed only when an instance of the class is created. Secondly, I did not know that the default in the Logger is the ConsoleHandler handler and re-adding it leads to duplication of the message. Thank. - NoComments

1 answer 1

First, by default, the CongerHandler handler is installed in the Logger and re-adding it leads to message duplication.

Secondly, the dynamic initialization block is processed when the class is instantiated.

As a result, there should be the following.

 . . . static{ log.setLevel(Level.ALL); } . . .