Android Log日志的封装类,显示类名以及行号,快速定位

转自麦罗的博客

Log日志是很常用的一个工具,这个实现比较简单,也参考网络上一般实现。现在将其总结了一下,麦洛将在项目中也会使用这个工具类。
Logger类其实是对android.util.Log这个类的封装,以下是代码实现:

 

public class ArLog { 
 /**
  * debug or not
  * when release, set debug 'false'
  */
 private static boolean debug = true;
  
 
 private ArLog() {
 
 }
   
 private static String getFunctionName() {
  StackTraceElement[] sts = Thread.currentThread().getStackTrace();
 
  if (sts == null) {
   return null;
  }
  
   StringBuilder sb = new StringBuilder();
 
  for (StackTraceElement st : sts) {
   if (st.isNativeMethod()) {
    continue;
   }
 
   if (st.getClassName().equals(Thread.class.getName())) {
    continue;
   }
  
   return "[" + Thread.currentThread().getName() + "(" + Thread.currentThread().getId()
     + "): " + st.getFileName() + ":" + st.getMethodName() + ":" + st.getLineNumber() + "]";
  }
 
  return null;
 }
 
 private static String createMessage(String msg) {
  String functionName = getFunctionName();
  String message = (functionName == null ? msg : (functionName + " - " + msg));
  return message;
 }
 
 /**
  * log.i
  */
 public static void i(String tag, String msg) {
  if (debug) {
   String message = createMessage(msg);
   Log.i(tag, message);
  }
 } 
 
 /**
  * log.v
  */
 public static void v(String tag, String msg) {
  if (debug) {
   String message = createMessage(msg);
   Log.v(tag, message);
  }
 }
 
 /**
  * log.d
  */
 public static void d(String tag, String msg) {
  if (debug) {
   String message = createMessage(msg);
   Log.d(tag, message);
  }
 }
 
 /**
  * log.e
  */
 public static void e(String tag, String msg) {
  if (debug) {
   String message = createMessage(msg);
   Log.e(tag, message);
  }
 }
 /**
  * log.error
  */
 public static void error(String tag, Exception e){
  if(debug){
   StringBuffer sb = new StringBuffer();
         String name = getFunctionName();
         StackTraceElement[] sts = e.getStackTrace();
 
         if (name != null) {
                sb.append(name+" - "+e+"\r\n");
            } else {
                sb.append(e+"\r\n");
            }
         if (sts != null && sts.length > 0) {
             for (StackTraceElement st:sts) {
                 if (st != null) {
                     sb.append("[ "+st.getFileName()+":"+st.getLineNumber()+" ]\r\n");
                 }
             }
         }
         Log.e(tag,sb.toString());
  }
 }
 /**
  * log.w
  */
 public static void w(String tag, String msg) {
  if (debug) {
   String message = createMessage(msg);
   Log.w(tag, message);
  }
 }
   
 /**
  * set debug false
  */
 public static void setDebug(boolean d) {
  debug = d;
 }
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值