首页 > 学院 > 开发设计 > 正文

一个打印Log日志,好用的工具logger

2019-11-08 00:31:43
字体:
来源:转载
供稿:网友

首先在build.gradle中添加:

compile 'com.orhanobut:logger:1.15'

尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。 OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。 OkHttp 处理了很多网络疑难杂症:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个ip地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。

使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果你用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。

Okhttp的拦截器很好用,这是我写的用来拦截日志的,

/** * * <p> * 描述:api请求log拦截器,使用{@link com.orhanobut.logger.Logger}打印日志 */public class LoggerInterceptor implements Interceptor { PRivate static final String TAG = "OkHttp";//请求标签 private static final Charset UTF8 = Charset.forName("UTF-8"); public enum Level { /** * logs request and response basic info * <p> * request info [method url Protocol] * <p> * response info [code message tookTime responseBody] */ BASIC, /** * include all info{@link #BASIC} * <p>logs request headers and response headers */ HEADERS } private final Level mLevel; public LoggerInterceptor() { this(Level.BASIC); } /** * @param level {@link Level} */ public LoggerInterceptor(Level level) { mLevel = level; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); StringBuilder requestBuilder = new StringBuilder(); Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1; requestBuilder.append(request.method()) .append(" ") .append(request.url()) .append(" ") .append(protocol) .append("/n"); if (mLevel == Level.HEADERS) { Headers requestHeaders = request.headers(); for (int i = 0, count = requestHeaders.size(); i < count; i++) { String name = requestHeaders.name(i); if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { requestBuilder.append(name) .append(": ") .append(requestHeaders.value(i)) .append("/n"); } } } RequestBody requestBody = request.body(); if (requestBody != null) { if (requestBody.contentType() != null) { requestBuilder.append("Content-Type: ") .append(requestBody.contentType()) .append("/n"); } if (requestBody.contentLength() != -1) { requestBuilder.append("Content-Length: ") .append(requestBody.contentLength()) .append("/n"); } Buffer buffer = new Buffer(); requestBody.writeTo(buffer); requestBuilder.append("Request-Body: ") .append(buffer.readUtf8()) .append("/n"); } Logger.t(TAG).d(requestBuilder.toString()); StringBuilder responseBuilder = new StringBuilder(); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (IOException e) { Logger.t(TAG).e(e, "HTTP FAILED"); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); responseBuilder.append(response.code()) .append(" ") .append(response.message()) .append(" ") .append(response.request().url()) .append(" (took: ") .append(tookMs) .append("ms") .append(")/n"); if (mLevel == Level.HEADERS) { Headers responseHeaders = response.headers(); for (int i = 0, count = responseHeaders.size(); i < count; i++) { responseBuilder.append(responseHeaders.name(i)) .append(": ") .append(responseHeaders.value(i)) .append("/n"); } } if (bodyEncoded(response.headers())) { responseBuilder.append("END HTTP (encoded body omitted)"); Logger.t(TAG).d(responseBuilder.toString()); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { responseBuilder.append("Couldn't decode the response body; charset is likely malformed.") .append("END HTTP"); Logger.t(TAG).d(responseBuilder.toString()); return response; } } if (!isPlaintext(buffer)) { responseBuilder.append("END HTTP (binary ") .append(buffer.size()) .append("-byte body omitted)"); Logger.t(TAG).d(responseBuilder.toString()); return response; } responseBuilder.append("END HTTP (") .append(buffer.size()) .append("-byte body)"); Logger.t(TAG).d(responseBuilder.toString()); if (contentLength != 0) { Logger.t(TAG).json(buffer.clone().readString(charset)); } } return response; } /** * Returns true if the body in question probably contains human readable text. Uses a small sample * of code points to detect unicode control characters commonly used in binary file signatures. */ private boolean isPlaintext(Buffer buffer) { try { Buffer prefix = new Buffer(); long byteCount = buffer.size() < 64 ? buffer.size() : 64; buffer.copyTo(prefix, 0, byteCount); for (int i = 0; i < 16; i++) { if (prefix.exhausted()) { break; } int codePoint = prefix.readUtf8CodePoint(); if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) { return false; } } return true; } catch (EOFException e) { return false; // Truncated UTF-8 sequence. } } private boolean bodyEncoded(Headers headers) { String contentEncoding = headers.get("Content-Encoding"); return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity"); }

在okhttp中插入方法:

OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10000, TimeUnit.MILLISECONDS) .readTimeout(10000, TimeUnit.MILLISECONDS) .addInterceptor(new LoggerInterceptor(LoggerInterceptor.Level.HEADERS)) .build();

搞定,下面你就可以打印出很漂亮的Logger了.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表