Search code examples
javaloggingstreamlog4j

Log Stream data using log4j


I am getting stream data from an http connection. I want to log the stream to log files using log4j.

I need this stream further to do some other operations (must be retained)

How can I do that?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream xml = connection.getInputStream();

I tried this one:

StreamUtils.copy(xml, new LogOutputStreamUtil(log, Level.INFO));

where LogOutputStreamUtil from http://www.java2s.com/Open-Source/Java/Testing/jacareto/jacareto/toolkit/log4j/LogOutputStream.java.htm

But as soon as it got logged. Stream is getting closed :(


Solution

  • Simple solution would be to write your own inputStream wrapper

    Something like:

    class LogingInputStream extends BufferedStream {
        ByteArrayOutputStream copy4log = new ByteArrayOutputStream();
        InputStream source;
    
        public LogingInputStream( InputStream source ) { this.source = source; }
    
        public int read() {
            int value = source.read()
            logCopy.write( value );
            return value;
        }
    
        public void close() {
            source.close();
            StreamUtils.copy(xml, new LogOutputStreamUtil(copy4log, Level.INFO));
            copy4log.close();
        }
    
        .....more code here
    }
    

    Anyway, general idea is that you need to intercept inputstream read methods.

    There are other ways to accomplish this like copying source inputStream into a buffer (bytearray, string or whatever suits you), logging that buffer, and creating another inputStream around buffer and returning it to a caller instead source inputStream. It is simpler to do, but is it right solution depends on your usecase.