android网络日志打印(记录)

OkHttp拦截类(继承Interceptor )

public class OkHttpLoggerInterceptor implements Interceptor {

    //定义字符类型为UTF-8

    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override

    public Responseintercept(Chain chain)throws IOException {

        //获取请求

        Request request = chain.request();

        {

            //获取请求体

            RequestBody requestBody = request.body();

            //获取请求头

            Headers headers = request.headers();

            //判断请求体是否为空

            boolean hasRequestBody = requestBody !=null;

            //开始打印请求体日志

            LogUtil.e("┎━━━━━ request start ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            LogUtil.e("┃" + request.url() +"  " + request.method());

            if (hasRequestBody) {

                //请求体不为空

                if (requestBody.contentType() !=null) {

                //请求体格式类型不为空则打印(用来判断请求体字符类型还是咋样,不太清楚用途,自行看源码)

                    LogUtil.e("┃contentType: " + requestBody.contentType());

                }

if (requestBody.contentLength() != -1) {

                    //请求体长度不为-1则打印

                    LogUtil.e("┃contentLength: " + requestBody.contentLength());

                }

}

for (int i =0; i < headers.size(); i++) {

                //打印请求头

                String name = headers.name(i);

                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-

                Length".equalsIgnoreCase(name))

                LogUtil.e("┃" + headers.name(i) +":" + headers.value(i));

            }

if (!hasRequestBody) {

                //请求体为空打印结束语

                LogUtil.e("┖━━━━━ request end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            }else if (bodyEncoded(request.headers())) {

                LogUtil.e("┖━━━━━ request end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +" 

                (encoded body omitted)");

            }else {

                //打印请求体内容

                Buffer buffer =new Buffer();

                requestBody.writeTo(buffer);

                MediaType contentType = requestBody.contentType();

                String bufferString = buffer.readString(UTF8);

                if (contentType !=null &&"json".equals(contentType.subtype())) {

                    //是json格式打印

                    LogUtil.eJson(bufferString);

                }

                LogUtil.e(bufferString);

                LogUtil.e("┖━━━━━ request end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ " + 

                requestBody.contentLength());

            }

}

{

            long startNs = System.nanoTime();

            //获取响应

            Response response = chain.proceed(request);

            //获取响应时间

            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

            //获取响应体

            ResponseBody responseBody = response.body();

            long contentLength = responseBody.contentLength();

            //开始打印响应体日志

            LogUtil.e("┎━━━━━ response start ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            LogUtil.e("┃" + response.request().url() +"  " + response.code() +"  " + 

            response.message() +" (" + tookMs +"ms" +"" +')');

            //获取响应头

            Headers headers = response.headers();

            for (int i =0; i < headers.size(); i++) {

            //全部打印出来

                LogUtil.e("┃" + headers.name(i) +":" + headers.value(i));

            }

if (!HttpHeaders.hasBody(response)) {

                //响应体为空打印结束语

                LogUtil.e("┖━━━━━ response end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            }else if (bodyEncoded(response.headers())) {

                LogUtil.e("┖━━━━━ response end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 

                (encoded body omitted)");

            }else {

                //响应体只能获取一次,所以不能用string()

                //String source = responseBody.string().trim();

                //获取响应体资源(用source()方法获取响应体内容不会影响响应体的传输)

                BufferedSource source = responseBody.source();

                source.request(Long.MAX_VALUE); // Buffer the entire body.

                Buffer buffer = source.buffer();

                if (contentLength !=0) {

                    MediaType contentType = responseBody.contentType();

                    String bufferString = buffer.clone().readString(UTF8);

                    if (contentType !=null &&"json".equals(contentType.subtype())) {

                        //是json格式

                        LogUtil.eJson(bufferString);

                    }

                        LogUtil.e("┃" + bufferString);

                }

                        LogUtil.e("┖━━━━━ response end ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ " 

                        + buffer.size() +"-byte body)");

            }

                        return response;

        }

}

    /*请求头编码格式???不是很清楚用途*/

    private boolean bodyEncoded(Headers headers) {

        String contentEncoding = headers.get("Content-Encoding");

        return contentEncoding !=null && !contentEncoding.equalsIgnoreCase("identity");

    }

}

日志打印类

public final class LogUtil {

private static final boolean isDebug =true;

    private final String RAILA ="┎┖━┃";

    private static final String LEFT_TOP_RAILA ="┎";

    private static final String LEFT_BOTTOM_RAILA ="┖";

    private static final String LEFT_RAILA ="┃";

    /*正常日志*/

    public static void e(String logs) {

if (isDebug) {

    Log.e(getRandom(), logs);

        }

}

/*打印有调用类的日志*/

    public static void eSuper(String logs) {

        if (isDebug) {

            StackTraceElement[] elements = Thread.currentThread().getStackTrace();

            for (int i =0; i < elements.length; i++) {

                if (elements[i].getClassName().equals(LogUtil.class.getName())) {

Log.e(getRandom(), LEFT_TOP_RAILA +"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

//                    Log.e(getRandom(), LEFT_RAILA + elements[i + 1].getFileName());

                    Log.e(getRandom(), LEFT_RAILA + elements[i] +"");

                    Log.e(getRandom(), LEFT_RAILA + elements[i +1] +"");

                }

}

Log.e(getRandom(), "┠━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            Log.e(getRandom(), LEFT_RAILA + logs);

            Log.e(getRandom(), LEFT_BOTTOM_RAILA +"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

        }

}

/*正常日志*/

    public static void eNormal(String tag, String logs) {

if (isDebug) {

Log.e(tag, logs);

        }

}

/*打印json格式的日志*/

    public static void eJson(String logs) {

if (isDebug) {

Log.e(getRandom(), LEFT_RAILA + JsonFormatter.jsonFormat(logs));

        }

}

/*有调用类的tag*/

    private static StringgetTAG() {

StackTraceElement[] elements = Thread.currentThread().getStackTrace();

        for (int i =0; i < elements.length; i++) {

if (elements[i].getClassName().equals(LogUtil.class.getName())) {

String name = elements[i +2].getFileName() +getRandom();

                return name;

            }

}

return null;

    }

/*获取一万以内的随机数*/

    private static StringgetRandom() {

int random = (int) ((Math.random() *9 +1) *10000);

        return random +"";

    }

}

json打印格式父类

public class JsonFormatter {

static final JsonFormatterformatter =findJsonFormatter();

    public static StringjsonFormat(String logs) {

try {

return formatter.format(logs);

        }catch (Exception e) {

return "";

        }

}

Stringformat(String logs) {

return "";

    }

private static JsonFormatterfindJsonFormatter() {

JsonFormatter gsonFormatter = GsonFormatter.buildIfSupported();

        if (gsonFormatter !=null) {

return gsonFormatter;

        }

JsonFormatter jsonFormatter = OrgJsonFormatter.buildIfSupported();

        if (jsonFormatter !=null) {

return jsonFormatter;

        }

return new JsonFormatter();

    }

}

json打印格式子类(Gson)

public class GsonFormatterextends JsonFormatter {

private final GsonGSON =new GsonBuilder().setPrettyPrinting().create();

    private final JsonParserPARSER =new JsonParser();

    @Override

    Stringformat(String logs) {

return GSON.toJson(PARSER.parse(logs));

    }

protected static GsonFormatterbuildIfSupported(){

try {

Class.forName("com.google.gson.Gson");

            return new GsonFormatter();

        }catch (ClassNotFoundException e) {

return null;

        }

}

}

json打印格式子类(JSONObject)

public class OrgJsonFormatterextends JsonFormatter {

@Override

    Stringformat(String logs) {

try {

return new JSONObject(logs).toString(4);

        }catch (JSONException e) {

return "";

        }

}

protected static OrgJsonFormatterbuildIfSupported() {

try {

Class.forName("org.json.JSONObject");

            return new OrgJsonFormatter();

        }catch (ClassNotFoundException e) {

return null;

        }

}

}

若用其他json库同上处理

你可能感兴趣的:(android网络日志打印(记录))