Logger的解析使用

Logger的解析使用

作为一个入世未深的小程序猿,在运行过程中程序崩溃看到满屏的谷歌原生的log日志脑子里有一万只草泥马飞过,然而,我们的成长必须站在巨人的肩膀上,大神已经封装好了一个perfect的打印日志类Logger给广大猿们带来了方便,下面是个人的一点理解和使用:
首先我们看一下原生的log日志:

这里写图片描述

如果你已经习惯了这种日志,那么只能说你太容易满足了,接下来看一下Logger的日志,没有对比就看不出差别;

这里写图片描述

怎么样对比之后是不是觉得天都变亮了,平时在开发中是不是经常打印一些json、xml、map、List等信息啊,对于原生log打印就是比较乱一点,比如json数据我们需要复制出来利用GsonFormat将该json字符串生成实体类啊(如果你不知道GsonFormat问一下度娘吧),而对于我们的Logger类来说,妈妈就再也不用担心我的学习了,下面我来测试一下它的牛逼之处吧;

  • 打印map数据
Map map = new HashMap();
 for (int i = 0; i < 10; i++) {
            map.put(i,"你好"+i);
              }
Logger.d(map);

这里写图片描述

  • 打印List数据
List mList = new ArrayList();
for(int i = 0;i < 10;i++){
   mList.add("你好"+i);
   }
   Logger.d(mList);

这里写图片描述

  • 打印Exception数据
try {
            InputStream  is =  getAssets().open("hello.xml");
        } catch (IOException e) {
           Logger.e(e,"ExceptionMessage");
        }

这里写图片描述

  • 打印xml数据
 String xmls = "<luweicheng>\n" +
                "<home>甘肃省庆阳市</home>\n" +
                "<school>兰州交通大学</school>\n" +
                "<heading>简介</heading>\n" +
                "<body>我是一个小小鸟!欧耶</body>\n" +
                "</luweicheng>";
      Logger.xml(xmls);

这里写图片描述
- 打印json数据

 String json = "{\"items\":[{\"password\":\"\",\"userId\":1,\"userName\":\"zhangsan\"},{\"password\":\"\",\"userId\":2,\"userName\":\"lisi\"}],\"results\":2}";
 Logger.json(json);

这里写图片描述

其实对于Logger而言他的方法Logger.d(Object obj)大家肯定就猜出来了,对于你传入的数据类型Logger类会强转成所需的类型打印出来的。其实我们看一下Logger源码,我这里Logger.d(Object object)、Logger.json(String json)、Logger.xml(String xml)这三个方法的部分源码贴出来:

  @Override public void d(Object object) {
    String message;
    if (object.getClass().isArray()) {
      message = Arrays.deepToString((Object[]) object);
    } else {
      message = object.toString();
    }
    log(DEBUG, null, message);
  }

/**
   * Formats the json content and print it
   *
   * @param json the json content
   */
  @Override public void json(String json) {
    if (Helper.isEmpty(json)) {
      d("Empty/Null json content");
      return;
    }
    try {
      json = json.trim();
      if (json.startsWith("{")) {
        JSONObject jsonObject = new JSONObject(json);
        String message = jsonObject.toString(JSON_INDENT);
        d(message);
        return;
      }
      if (json.startsWith("[")) {
        JSONArray jsonArray = new JSONArray(json);
        String message = jsonArray.toString(JSON_INDENT);
        d(message);
        return;
      }
      e("Invalid Json");
    } catch (JSONException e) {
      e("Invalid Json");
    }
  }

  /**
   * Formats the json content and print it
   *
   * @param xml the xml content
   */
  @Override public void xml(String xml) {
    if (Helper.isEmpty(xml)) {
      d("Empty/Null xml content");
      return;
    }
    try {
      Source xmlInput = new StreamSource(new StringReader(xml));
      StreamResult xmlOutput = new StreamResult(new StringWriter());
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      transformer.transform(xmlInput, xmlOutput);
      d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
    } catch (TransformerException e) {
      e("Invalid xml");
    }
  }

以上源码不必每局都理解你只需要理解Logger类是将map、list等数据格式在打印之前利用反射进行判断是否为Array,如果是将重新包装,不是直接object.toString();而对于json和xml看源码基本可以看出首先对传入的数据进行判断之后格式化拼接成了xml和json格式的数据。
Logger如何配置呢?
首先,我们导入Logger的依赖包:

 compile 'com.orhanobut:logger:1.15'//导入后Sync Now一下

如果你想自定义TAG,只需如下操作:

/**
 * Created by luweicheng on 2016/12/11.
 * 自定义Application
 */

public class MyApplication extends Application {
    public static String TAG = "luweicheng_LOG";
    @Override
    public void onCreate() {
        super.onCreate();
        Logger.init(TAG);
    }
}
//在manifests中注册该Application
<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

ok,大功告成,下面见证你的自定义TAG使用效果:

这里写图片描述

That is perfect 马上动手操作一下吧!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值