2012-09-11 35 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。這樣做很簡單,但是依賴於你的用例是否正確的解決方案。