logger 是Android 的日志管理工具
github地址 https://github.com/orhanobut/logger
一 简单使用
使用步骤:
(1):首先在Android Studio 的glide文件中添加依赖
compile 'com.orhanobut:logger:1.15'
初始化logger 可以在自定义Application 中对logger 进行初始化 【不进行初始化也可以正常使用】
/**
* 初始化logger 默认tag = PRETTYLOGGER
*/
Logger.init();
/**
* 初始化logger 自定义TAG
*/
Logger.init(TAG);
之后就可以使用logger 打印日志
先看一下logger的打印API
logger 提供了非常丰富的方法用来打印相关数据下面我们逐个分析一下使用方式
创建几个变量用于打印数据
int number = 10;
String id = "1323290412";
String message = "msg";
String name = "小明";
List<String> strings = new ArrayList<>(Arrays.asList("北京","上海"));
List<City> cityList = new ArrayList<>(Arrays.asList(
new City("北京"),
new City("上海"),
new City("广州"),
new City("杭州")));
- logger.i() 和 logger.i()打印格式化字符串
效果如下:
2.logger.d() 打印数组,对象数据等
Logger.d(strings);
Logger.d(cityList);
效果如下:
自定义Java bean
private String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
@Override
public String toString() {
return "City{" + "cityName='" + cityName + '\'' + '}';}
logger.e() 打印错误日志和logger.log()等 打印自定义Tag 日志 使用方式大同小异就不介绍了
Logger.t(TAG).d(message);
logger.t() 可用于打印临时Tag,不同于Application 初始化中的TAG 这样就非常方便了
3.logger.json() 打印json 数据
效果如下:
4.logger.xml() 打印Xml 类型数据
效果如下:
二 结合OKHttp使用
以上就是logger 的基本使用方式,可以使用logger 与OkHttp 结合打印http 请求相关数据 先看一下效果图:
利用logger 实现与OKhttp结合打印请求数据 需要借助OKhttp的网络拦截器 在自定义网络拦截器 实现Interceptor 接口 中添加logger 打印信息,自定义网络拦截器代码如下:
private static final String TAG = "OKHttp";
private static final Charset UTF8 = Charset.forName("UTF-8");
public LoggerHttpInterceptor() {
}
@Override
public Response intercept(Chain chain) throws IOException {
//log 信息
StringBuilder builder = new StringBuilder();
Request request = chain.request();
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "请求方式----> " + request.method() + "\n请求地址: " + request.url() + "\nHttp 版本:" + protocol;
builder.append(requestStartMessage);
if (hasRequestBody) {
if (requestBody.contentType() != null) {
builder.append("\n请求头:----> Content-Type: " + requestBody.contentType());
}
}
builder.append("\n请求参数:");
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
builder.append(name + ": " + headers.value(i));
}
}
// builder.append("\n请求参数:---end");
if (!hasRequestBody) {
builder.append("\n请求结束 --> END " + request.method());
} else if (bodyEncoded(request.headers())) {
builder.append("\n请求结束 --> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (isPlaintext(buffer)) {
builder.append("\n" + buffer.readString(charset));
builder.append("\n请求结束 --> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)");
} else {
builder.append("\n请求结束 --> END " + request.method() + " (binary "
+ requestBody.contentLength() + "-byte body omitted)");
}
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
builder.append("\n<-- 请求出错: " + e);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
builder.append("\n<-- 请求code: " + response.code() + " 请求状态: " + response.message() + " 请求地址: " + response.request().url() + " 用时:(" + tookMs + "ms)");
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) {
builder.append("\nCouldn't decode the response body; charset is likely malformed.");
builder.append("\n<-- END HTTP");
return response;
}
}
if (!isPlaintext(buffer)) {
builder.append("\n<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
builder.append("\n返回数据:");
builder.append("\n" + buffer.clone().readString(charset));
}
builder.append("\n<-- 请求结束 END HTTP (" + buffer.size() + "-byte body)");
Logger.t(TAG).d("请求信息如下:\n" + builder);
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.
*/
static boolean isPlaintext(Buffer buffer) throws EOFException {
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");
}