显示样式如下,复制内容的时候使用鼠标中键进行选中
打印内容:code,请求方式,url,请求头,请求体,返回json
class LoggerInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain?): Response { val orgRequest = chain!!.request() val response = chain.proceed(orgRequest) val body = orgRequest.body() val sb = StringBuilder() if (orgRequest.method() == "POST" && body is FormBody) { val body1 = body for (i in 0 until body1.size()) { sb.append(body1.encodedName(i) + "=" + body1.encodedValue(i) + ",") } sb.delete(sb.length - 1, sb.length) //打印post请求的信息 Logger.t(AppConfigs.LOGGER_NET_TAG).d("code=" + response.code() + "|method=" + orgRequest.method() + "|url=" + orgRequest.url() + "\n" + "headers:" + orgRequest.headers().toMultimap() + "\n" + "post请求体:{" + sb.toString() + "}") } else { //打印get请求的信息 Logger.t(AppConfigs.LOGGER_NET_TAG).d("code=" + response.code() + "|method=" + orgRequest.method() + "|url=" + orgRequest.url() + "\n" + "headers:" + orgRequest.headers().toMultimap()) } //返回json val responseBody = response.body() val contentLength = responseBody!!.contentLength() val source = responseBody.source() source.request(java.lang.Long.MAX_VALUE) val buffer = source.buffer() var charset = UTF8 val contentType = responseBody.contentType() if (contentType != null) { try { charset = contentType.charset(UTF8) } catch (e: UnsupportedCharsetException) { return response } } if (contentLength != 0L) { //打印返回json //json日志使用鼠标中键进行选中 Logger.t(AppConfigs.LOGGER_NET_TAG).json(buffer.clone().readString(charset)) } return response } }
在Application中进行初始化Logger
val strategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) // 是否显示线程信息,默认为ture .methodCount(1) // 显示的方法行数 .methodOffset(0) // 隐藏内部方法调用到偏移量 .tag("tag") .build() Logger.addLogAdapter(object : AndroidLogAdapter(strategy) { override fun isLoggable(priority: Int, tag: String?): Boolean { return BuildConfig.DEBUG } })
除了需要依赖Retrofit2相关依赖外还需要依赖
implementation 'com.orhanobut:logger:2.2.0'
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。