RaceBase
RaceBase

Reputation: 18848

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 :(

Upvotes: 0

Views: 3636

Answers (2)

Paul Wagland
Paul Wagland

Reputation: 29116

This is a very old question, however the other option to doing this these days would be to use the log4J IOStreams classes. These allow you to present a Streaming interface, but have the results go to a log file of your choice.

Upvotes: 0

Talijanac
Talijanac

Reputation: 1157

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.

Upvotes: 2

Related Questions