Logging InputStream

给你一囗甜甜゛ 提交于 2020-01-15 12:29:05

问题


I create an InputStream class, that extends CiphetInputStream. I want to log all data from my InputStream (that i use as input in parser further) so i done following:

public class MyInputStream extends CipherInputStream {
    private OutputStream logStream = new ByteArrayOutputStream();
.....
    @Override
    public int read() throws IOException {
        int read = super.read();
        logStream.write(read);
        return read;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int read = super.read(b, off, len);
        if (read > 0) {
            logStream.write(b, off, read);
        }
        return read;
    }

    @Override
    public int read(byte[] buffer) throws IOException {
        int read = super.read(buffer);
        if (read()>0) {
            logStream.write(buffer);
        }
        return read;
    }

    @Override
    public void close() throws IOException {
        log();
        super.close();
    }

    public void log() {
        String logStr = new String(((ByteArrayOutputStream) logStream).toByteArray(), Charset.defaultCharset());
        Log.d(getClass(), logStr);
        try {
            logStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In actual my stream has something like this:

<response>
<result>0</result>
</response>

but log show smth like this mutation :

<<response>
<resultt >0</resullt>
</respoonse>
[and (?) symbol at the end]

Thanks for any help!


回答1:


You can combine TeeInputStream and Logger.stream():

new TeeInputStream(
  yourStream, 
  Logger.stream(Level.INFO, this)
);



回答2:


If you want to see log in logcat, try Log.i(String tag, String message); or System.out.println("");. Both of them works. You can also use, Log.d, Log.w and Log.e also.



来源:https://stackoverflow.com/questions/16434699/logging-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!