Class LoggingOutputStream

  • All Implemented Interfaces:
    Closeable, Flushable, AutoCloseable

    public class LoggingOutputStream
    extends OutputStream
    Output stream that redirects all writes to provided logger. Useful with legacy code that expects PrintStream as logging facility.

    Example:

         // Create PrintStream with autoFlush=true, otherwise
         // LoggingOutputStream will accumulate bytes until closed.
         System.setErr(new PrintStream(
              new LoggingOutputStream(
                  Logger.getLogger("outLog"), Level.ERROR),
                  true));
    • Constructor Detail

      • LoggingOutputStream

        public LoggingOutputStream​(@NonNull org.apache.log4j.Logger log,
                                   @NonNull org.apache.log4j.Level level)
        Creates the Logging instance to flush to the given logger.
        Parameters:
        log - the Logger to write to
        level - the log level
        Throws:
        NullPointerException - in case if one of arguments is null.
    • Method Detail

      • write

        public void write​(int b)
                   throws IOException
        Writes the specified byte to this output stream.
        Specified by:
        write in class OutputStream
        Parameters:
        b - the byte to write
        Throws:
        IOException - if an I/O error occurs.
      • flush

        public void flush()
        Flushes this output stream and forces any buffered output bytes to be written out.
        Specified by:
        flush in interface Flushable
        Overrides:
        flush in class OutputStream
      • close

        public void close()
        Closes this output stream and releases any system resources associated with this stream.
        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Overrides:
        close in class OutputStream
      • processLine

        protected String processLine​(String s)
        Examines an inout line and amends, if needed. Return null to skip logging the given line. Subclasses may override this method if further processing is required.
        Parameters:
        s - an input line as was written to the stream
        Returns:
        processed line or null if no logging is required