LoggingOutputStream.java

  1. /**
  2.  * LoggingOutputStream
  3.  *
  4.  */
  5. package gov.usgs.util.logging;

  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;

  10. /**
  11.  * An OutputStream that writes contents to a Logger upon each call to flush().
  12.  *
  13.  * From http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and
  14.  */
  15. public class LoggingOutputStream extends ByteArrayOutputStream {

  16.     private String lineSeparator;

  17.     private Logger logger;
  18.     private Level level;

  19.     /**
  20.      * Constructor
  21.      *
  22.      * @param logger
  23.      *            Logger to write to
  24.      * @param level
  25.      *            Level at which to write the log message
  26.      */
  27.     public LoggingOutputStream(Logger logger, Level level) {
  28.         super();
  29.         this.logger = logger;
  30.         this.level = level;
  31.         lineSeparator = System.getProperty("line.separator");
  32.     }

  33.     /**
  34.      * upon flush() write the existing contents of the OutputStream to the
  35.      * logger as a log record.
  36.      *
  37.      * @throws java.io.IOException
  38.      *             in case of error
  39.      */
  40.     public void flush() throws IOException {

  41.         String record;
  42.         synchronized (this) {
  43.             super.flush();
  44.             record = this.toString().trim();
  45.             super.reset();

  46.             if (record.length() == 0 || record.equals(lineSeparator)) {
  47.                 // avoid empty records
  48.                 return;
  49.             }

  50.             logger.logp(level, "", "", record);
  51.         }
  52.     }
  53. }