Logging InputStream

2019-08-12 01:45发布

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!

2条回答
萌系小妹纸
2楼-- · 2019-08-12 02:11

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.

查看更多
何必那么认真
3楼-- · 2019-08-12 02:31

You can combine TeeInputStream and Logger.stream():

new TeeInputStream(
  yourStream, 
  Logger.stream(Level.INFO, this)
);
查看更多
登录 后发表回答