Android一点 Log优化

1 篇文章 0 订阅

开发中经常需要log输出调试,但是怎么样看比较合适呢?

package com.tets.util;

import android.util.Log;

/**
 * log信息类
 * @author Flyjun
 *
 */
public class Logger {

    private static final String TAG="debug";

    //类名
    static String className;
    //方法名
    static String methodName;
    //debug行数
    static int lineNumber;


    /**
     * 控制log显示的显示
     */
    public static boolean isShowLog=true;

    public static void setShowLog(boolean isLog){
        isShowLog=isLog;
    }

    public static void debug(Object msg){

        if(!isShowLog){
           return;
        }
        getMethodNames(new Throwable().getStackTrace());
        Log.d(TAG ,createLog(msg));
    }

    public static void debug(String tag,Object msg){
        if(!isShowLog){
            return;
        }
        getMethodNames(new Throwable().getStackTrace());
        Log.d(tag, createLog(msg));
    }

    /**
     * debug多个参数
     * @param args
     * 
     * debugs(new Object[]{"params1",t1},new Object[]{"params2",t2})
     */
    public static void debugs(Object[] ... args) {
        if(!isShowLog){
            return;
        }

        getMethodNames(new Throwable().getStackTrace());

        for (Object[] o:args) { //o[0]表示参数名称 o[1]表示参数值

            if(null == o){

                Log.d(TAG,createLog("args is null"));
                continue;
            }

            if(o.length >= 2){

                if(null == o[1]){
                    Log.d(TAG,createLog(o[0]+" is null"));
                }else{
                    Log.d(TAG,createLog(o[0]+":"+o[1]));
                }

            }else{

                    Log.d(TAG,createLog(o[0]));

            }

        }
    }

    /**
     * 创建log输出信息
     * @param log
     * @return
     */
    private static String createLog(Object log ) {

        StringBuffer buffer = new StringBuffer();
        buffer.append(className);
        buffer.append(": [");
        buffer.append(methodName);
        buffer.append(":");
        buffer.append(lineNumber);
        buffer.append("]");
        buffer.append(" "+log);

        return buffer.toString();
    }

    /**
     * 获取类名等信息
     * @param sElements
     */
    private static void getMethodNames(StackTraceElement[] sElements){
        className = sElements[1].getFileName();
        methodName = sElements[1].getMethodName();
        lineNumber = sElements[1].getLineNumber();
    }

}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值