Android 解决超长Log无法显示及显示不全的工具类
2020-04-13 本文已影响0人
懵懂_傻孩纸
当我们们使用Android Stuido时候,经常需要打印Log,而Android Studio自带的Log使用又较为繁琐且无法打印超长Log,所以自己封装一个Log工具类,大家直接CV即可.
public class MyLog {
//读取BuildConfig.LOG_DEBUG 签名时为FALSE 不打印 debug时为true 打印
public static void i(String tag, String message) {
if (BuildConfig.LOG_DEBUG) {
int max_str_length = 2001 - tag.length();
//大于4000时
while (message.length() > max_str_length) {
Log.i(tag, message.substring(0, max_str_length));
message = message.substring(max_str_length);
}
//剩余部分
Log.i(tag, message);
}
}
public static void d(String tag, String message) {
if (BuildConfig.LOG_DEBUG) {
int max_str_length = 2001 - tag.length();
//大于4000时
while (message.length() > max_str_length) {
Log.d(tag, message.substring(0, max_str_length));
message = message.substring(max_str_length);
}
//剩余部分
Log.d(tag, message);
}
}
public static void e(String tag, String message) {
if (BuildConfig.LOG_DEBUG) {
int max_str_length = 2001 - tag.length();
//大于4000时
while (message.length() > max_str_length) {
Log.e(tag, message.substring(0, max_str_length));
message = message.substring(max_str_length);
}
//剩余部分
Log.e(tag, message);
}
}
// json打印
public static String format(String mJson){
StringBuilder soruce=new StringBuilder(mJson);
if(mJson==null||mJson.equals("")){
return null;
}
int offset=0;//目标字符串插入空格偏移量
int bOffset=0;//空格偏移量
for(int i=0;i<mJson.length();i++){
char charAt=mJson.charAt(i);
if(charAt=='{'||charAt=='['){
bOffset+=4;
soruce.insert(i+offset+1,"\n"+generateBlank(bOffset));
offset+=(bOffset+1);
}else if(charAt==','){
soruce.insert(i+offset+1,"\n"+generateBlank(bOffset));
offset+=(bOffset+1);
}else if(charAt=='}'||charAt==']'){
bOffset-=4;
soruce.insert(i+offset,"\n"+generateBlank(bOffset));
offset+=(bOffset+1);
}
}
return soruce.toString();
}
/**
* 打印
* @param shouldShowAll 是否将全部打印出来
*/
public static void print(String mJson,boolean shouldShowAll){
if(!BuildConfig.LOG_DEBUG) return;
if(mJson==null) return;
try {
System.out.println("----------print begin-----------");
String willPrintString = format(mJson);
if (!shouldShowAll) {
System.out.println(willPrintString);
} else {
int length = willPrintString.length();
int index = 0;
while (length > 2000) {
System.out.println(willPrintString.substring(index * 2000, (index + 1) * 2000));
length -= 2000;
index++;
}
System.out.println(willPrintString.substring(index * 2000));
}
System.out.println("----------print end-----------");
}catch (Exception e){
e.printStackTrace();
}
}
private static String generateBlank(int num){
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<num;i++){
stringBuilder.append(" ");
}
return stringBuilder.toString();
}
}
使用方式同样也很简单直接在使用地方调用即可
public void completed(String response) {
MyLog.e("话题Id",response);
mVO = new Gson().fromJson(response,HomeTopicVO.class);
mAdapter.setNewData(mVO.getData());