Greg Witczak
Greg Witczak

Reputation: 1684

log counter in java Logger

I'm using java.util.logging.Logger for logging various messages, on different levels (eg. by methods .fine(), .finer(), .info(), .warning()). I'd like to get info how many messages on each level were logged. Is it possible without writting my own class like:

public class MyLogger extends Logger
{
   int infoCounter = 0;

   @Override
   public void info(String msg)
   {
      super.info(msg);
      infoCounter++; 
   }
}

Upvotes: 4

Views: 2775

Answers (1)

James Dunn
James Dunn

Reputation: 8274

The answer is no, this is not possible.
The way you are doing it now is good (once it's synchronized, of course).

There is an alternative: instead of extending Logger, extend java.util.logging.Handler, and then:

  1. Override the publish() method

  2. Implement flush() and close()

  3. 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 to this is that you don't have to override methods for every single Level. The only thing is that you'll have to add this handler to each of your loggers:

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

So take it for what it's worth. Whatever you do, you'll have to write your own class.

Upvotes: 4

Related Questions