打造史上最简单,最实用的Log工具类
16lz
2021-01-26
在Android开发过程中,打印Log应该是程序员经常做的事情,毕竟在多数情况下比单步要方便,但是使用Android自带的Log工具类,在某种程度上难以满足我们的需求,比如:
1. 不能定位Log所在的位置;
2. 不能快速清除应用中的所有Log信息;
基于以上两点,对Android提供的Log类进行了简单的封装,完成了一个功能强大的Log工具类,该工具类具有以下特点:
- 可控制整个应用的Log输出;
- 可自定义Log标签;
- 简化了Log输出语句;
- 可快速, 准确定位Log所在位置;
代码实现如下:
public class LogUtil { /** * tag */ public static String tag = "znm"; /** * 是否需要开启Log(needLog:true开启, false关闭) */ private static boolean needLog = true; public static void i(String content) { if (needLog) { Log.i(tag, getLogInfo() + content); } } public static void i(String tag, String content) { if (needLog) { Log.i(tag, getLogInfo() + content); } } public static void d(String content) { if (needLog) { Log.d(tag, getLogInfo() + content); } } public static void d(String tag, String content) { if (needLog) { Log.d(tag, getLogInfo() + content); } } public static void e(String content) { if (needLog) { Log.e(tag, getLogInfo() + content); } } public static void e(String tag, String content) { if (needLog) { Log.e(tag, getLogInfo() + content); } } public static void v(String content) { if (needLog) { Log.v(tag, getLogInfo() + content); } } public static void v(String tag, String content) { if (needLog) { Log.v(tag, getLogInfo() + content); } } public static void w(String content) { if (needLog) { Log.w(tag, getLogInfo() + content); } } public static void w(String tag, String content) { if (needLog) { Log.w(tag, getLogInfo() + content); } } private static String getLogInfo() { return getClassName() + "(" + getLineNumber() + ")" + "$" + getMethodName() + ": "; } /** * 获取Log所在的类名 (getStackTrace的索引根据调用的顺序来决定,可通过打印Log栈来获取) * @return */ private static String getClassName() { try { String classPath = Thread.currentThread().getStackTrace()[5].getClassName(); return classPath.substring(classPath.lastIndexOf(".") + 1); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取Log所在的方法名 * @return */ private static String getMethodName() { try { return Thread.currentThread().getStackTrace()[5].getMethodName(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取Log所在的行 * @return */ private static int getLineNumber() { try { return Thread.currentThread().getStackTrace()[5].getLineNumber(); } catch (Exception e) { e.printStackTrace(); } return 0; } }
Log输出格式:
所在文件(所在行号)$所在方法名: Log信息
示例:
TabMainActivity(10)$onCreate: “onCreate running…”
更多相关文章
- 我的安卓应用——SchoolSystem的代码展示
- android-从音频数据库获取音乐数据
- Android(安卓)Studio + Eclipse 实现类似微博主页功能APP
- android 使用Photoshop获取图片某一点的颜色
- Android下的Java之interface接口泛型 动态获取泛型的类型
- android 6.0获取mac 地址都是02:00:00:00:00:00 的问题
- Android动态获取资源ID并使用javabean进行赋值
- Android触摸滑动全解(三)——View坐标体系详解
- 如何获取和安装Android(安卓)L开发者预览版