android日志超长打印 无bug代码

2021-12-17  本文已影响0人  吉凶以情迁

网上是用递归写的,会导致出现oom,我用这个while写了一个。


 public static void debug(String TAG,String content) {

        int startPos = 0;
        int endPos = Math.min(MAX_LENGTH, content.length());
        String current;
//        System.out.println("startPos:"+startPos+",endPos:"+endPos+",totalLen:"+content.length()+",currentlen:");
        while (true) {
            current = content.substring(startPos, endPos);

            startPos = endPos;
            int surplusLen = content.length() -endPos;//current.length();//startPos;
            endPos = startPos+Math.min(MAX_LENGTH, surplusLen);
            System.out.println("after:" + current+",startPos:"+startPos+",endPos:"+endPos+",totalLen:"+content.length()+",currentlen:"+current.length());
            System.out.println(TAG+":"+current);
            if(current.length()<MAX_LENGTH||endPos==current.length()||startPos==endPos){
                break;
            }
            //不用递归了
        }
    }


存在bug的递归写法




    /**
     * 分段打印较长的文本
     *
     * @param tag     标志
     * @param content 内容
     */
    public static void debugLarge(String tag, String content ) {
        if (!BuildConfig.DEBUG) {
            return;
        }

        if (content.length() > MAX_LENGTH) {
            String part = content.substring(0, MAX_LENGTH);
            Log.d(tag, part);

            part = content.substring(MAX_LENGTH, content.length());
            if ((content.length() - MAX_LENGTH) > MAX_LENGTH) {
                int pos = 0;
                debugLarge(tag, part);
            } else {
                Log.d(tag, part);
            }
        } else {
            Log.d(tag, content);
        }
    }

完整用法


public class HttpLog implements HttpLoggingInterceptor.Logger {
    @Override
    public void log(String message) {
        if (message != null && message.length() < DebugUtil.MAX_LENGTH) {
            DebugUtil.debug("HttpLogInfo", message);
        } else {

            int keepLen = Math.min((DebugUtil.MAX_LENGTH/2)-30,message.length());
            String start = message.substring(0, keepLen);
            // 取左边 keepLen个  , 再取右边 keepLen个
            int indexSecond = message.length() - keepLen;
            if(indexSecond<keepLen){
                indexSecond=Math.min(message.length(),keepLen/2);//如果index的位置到了左边,就直接把右边拿过来。
            }
            String end = message.substring(indexSecond);
            int cutcount = keepLen + indexSecond;//
            DebugUtil.debug("HttpLogInfo", start + "|截断了中间" + cutcount + "个字符|" + end);
        }
    }
}

这里用了2种截断法,如果是base64的post参数,这打印会导致大量数据,实在不行完全可以做阉割操作。
阉割操作可以保证 数据格式头部和尾部基本上完整的,除非多个base64,


image.png
上一篇 下一篇

猜你喜欢

热点阅读