Sk8erPeter

custom java.util.logging.StreamHandler

Apr 24th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. public class Foo {
  2.  
  3.     // ...
  4.  
  5.     public static final Logger logger = Logger.getLogger("FooLog");
  6.     private static Foo.MyConsoleHandler myConsoleHandler = new MyConsoleHandler();
  7.  
  8.     static {
  9.         java.util.logging.LogManager.getLogManager().reset();
  10.         logger.addHandler(myConsoleHandler);
  11.         logger.setLevel(java.util.logging.Level.ALL);
  12.     }
  13.  
  14.     /**
  15.      * We don't want ALL the logging stuffs to be printed out in red color to the console (e.g. in Eclipse)
  16.      * - for example, the texts printed out with logger.info("...") should remain black.
  17.      *
  18.      * @see http://stackoverflow.com/questions/9794516/change-appengine-console-red-color-in-eclipse/16229664#16229664
  19.      * @author Pete
  20.      */
  21.     public static class MyConsoleHandler extends java.util.logging.StreamHandler {
  22.         private java.util.logging.Formatter formatter = new SimpleFormatter();
  23.  
  24.         public void publish(java.util.logging.LogRecord record) {
  25.             if (record.getLevel().intValue() < java.util.logging.Level.WARNING.intValue()) {
  26.                 System.out.println(formatter.formatMessage(record));
  27.                 // flushing the stream, because the error output stream is not buffered, and this way the messages can mix:
  28.                 // (@see http://stackoverflow.com/questions/9146257/why-do-system-err-statements-get-printed-first-sometimes)
  29.                 System.out.flush();
  30.             } else {
  31.                 System.out.flush(); // we have to flush it here too
  32.                 System.err.println(formatter.format(record));
  33.             }
  34.         }
  35.     }
  36.    
  37.     // ...
  38.    
  39.     public void bar() {
  40.         logger.info("Info");
  41.         logger.severe("Severe");
  42.         // ...
  43.     }
  44.  
  45.     // ...
  46. }
Add Comment
Please, Sign In to add comment