Android-Log工具类

一、Log的基本格式

如下为Android Studio抓取的一条Log:

格式:
date time PID-TID/package priority/tag: message

例子:
2022-09-21 19:34:15.293 14923-14923/com.lzq.mycustomdemo D/linzhiqin: LZQ IS GOOD BOY!!!

格式定义如下:

格式 描述
date 日志输出时设备的日期
time 日志输出时设备的时间,精确到毫秒
PID 进程标识符
TID 线程标识符,若进程中只存在一个线程,则PID与TID可以相同
package 输出该条日志的应用包名
priority 日志优先级,取值如下,优先级从低到高排列(V:详细 D:调试 I:信息 W:警告 E:错误 A:断言)
tag 标签,用来标明日志发起者以及方便对日志进行过滤筛选
message 日志的主体内容

二、为什么要自定义Log类

  1. 方便应用全局管理Log的输出;
  2. 更友好得展示应用的log,有助于开发者调试、定位问题;

三、Log工具类实现

package com.lzq.mycustomdemo.utils;

import android.util.Log;

/**
 * @author: linzhiqin
 * @date: 2022/9/21
 */
public class LogUtil {
    public static String tag = "linzhiqin";

    public static int VERBOSE = 1;
    public static int DEBUG = 2;
    public static int INFO = 3;
    public static int WARN = 4;
    public static int ERROR = 5;
    public static int NOTHING = 6;

    public static int LEVEL = VERBOSE;//当前Log的打印等级
    private static boolean needDetail = false;//是否需要Log详细信息

    public static void v(String msg) {
        if (LEVEL <= VERBOSE) {
            Log.v(tag, getDetailInfo() + msg);
        }
    }

    public static void d(String msg) {
        if (LEVEL <= DEBUG) {
            Log.d(tag, getDetailInfo() + msg);
        }
    }

    public static void i(String msg) {
        if (LEVEL <= INFO) {
            Log.i(tag, getDetailInfo() + msg);
        }
    }

    public static void w(String msg) {
        if (LEVEL <= WARN) {
            Log.w(tag, getDetailInfo() + msg);
        }
    }

    public static void e(String msg) {
        if (LEVEL <= ERROR) {
            Log.e(tag, getDetailInfo() + msg);
        }
    }

    private static String getDetailInfo() {
        if (needDetail) {
            return getClassName() + "$" + getMethodName() + "(" + getLineNumber() + ")"+ ": ";
        }
        return "";
    }

    /**
     * 获取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;
    }
}

四、代码仓库地址

Demo地址:  https://gitee.com/linzhiqin/custom-demo

posted @ 2022-10-10 21:20  林奋斗同学  阅读(115)  评论(0编辑  收藏  举报