2012-09-11 32 views
0

我从http连接获取流数据。 我想使用log4j将流记录到日志文件。使用log4j记录流数据

我需要这个流还做一些其他操作(必须保留)

我怎么能这样做?

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

我想这一个:

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

其中LogOutputStreamUtil从http://www.java2s.com/Open-Source/Java/Testing/jacareto/jacareto/toolkit/log4j/LogOutputStream.java.htm

但只要它得到了记录。流越来越封闭:(

回答

2

简单的解决办法是写自己的inputStream包装

喜欢的东西:

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 
} 

无论如何,总的想法是,你需要拦截InputStream进行读取的方法

还有其他一些方法可以完成这一点,例如将源inputStream复制到缓冲区(bytearray,string或任何适合您的),记录该缓冲区以及在缓冲区周围创建另一个inputStream并将其返回给调用方, e inputStream。这样做很简单,但是依赖于你的用例是否正确的解决方案。