Log counter in java logger

I use java.util.logging.Logger to register various messages at different levels (for example, with the methods .fine() , .finer() , .info() , .warning() ). I would like to know how many posts at each level have been logged. Is it possible to write my own class without :

 public class MyLogger extends Logger { int infoCounter = 0; @Override public void info(String msg) { super.info(msg); infoCounter++; } } 
+4
source share
1 answer

The answer is no, it is impossible .
The way you do it now is good (as soon as it syncs, of course).

There is an alternative: instead of the Logger extension, expand java.util.logging.Handler, and then:

  • Override publish () method
  • Inject flush () and close ()
  • Create a method to count messages by level

    I tried this and tested it and it worked:

     import java.util.ArrayList; import java.util.List; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; public class CountHandler extends Handler { List<LogRecord> records = new ArrayList<LogRecord>(); @Override public void publish(LogRecord record) { records.add(record); } public int howMany(Level level) { int howMany = 0; for(LogRecord record : records) { if (record.getLevel().intValue() == level.intValue()) { howMany++; } } return howMany; } @Override public void flush() { } @Override public void close() throws SecurityException { } } 

The advantage of this is that you do not need to redefine the methods for each individual Level. The only thing you need to add this handler to each of your registrars:

 CountHandler messageCounter= new CountHandler(); logger.addHandler(messageCounter); 

So take it for what it costs. Whatever you do, you have to write your own class.

+4
source

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


All Articles