欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

关于Android中log日志(LogUtil)的封装

程序员文章站 2022-03-29 12:04:53
为了便于开发,特此封装了一个日志工具类,可以具体到类名,方法名,行数; 代码如下: public enum LogUtil { INSTANCE;...

为了便于开发,特此封装了一个日志工具类,可以具体到类名,方法名,行数;

代码如下:

public enum  LogUtil {
    INSTANCE;

    private final static boolean all = true;

    private final static boolean i = true;

    private final static boolean e = true;

    private final static boolean d = true;

    private  static String className;

    private static String methodName;

    private static int lineName;

    private final static String TAG = LogUtil.class.getSimpleName();



    public void i(String msg){
        if(all && i){
            getName(new Throwable().getStackTrace());
            Log.i(TAG, createLog(msg));
        }
    }

    public void e (String msg){
        if(all && e){
            getName(new Throwable().getStackTrace());
            Log.e(TAG, createLog(msg) );
        }
    }

    public void d (String msg){
        if(all && d){
            getName(new Throwable().getStackTrace());
            Log.d(TAG, createLog(msg));
        }
    }


    private  static void getName(StackTraceElement []stackTraceElements){
        className = stackTraceElements[1].getClassName();
        methodName = stackTraceElements[1].getMethodName();
        lineName = stackTraceElements[1].getLineNumber();
    }

    private static String createLog(String msg){
        StringBuilder sb = new StringBuilder();
        return sb.append(className).append(methodName).append(lineName).append(":").append(msg).toString();
    }

}

效果:

关于Android中log日志(LogUtil)的封装