android的Log工具Log源码分析

来源:互联网 发布:免费自学英语软件 编辑:程序博客网 时间:2024/05/17 02:29

 

我觉得几乎没有人没有使用过Log.v(d,i)...等这样的打log的代码吧,( ⊙ o ⊙ )是的,我们都用过,但是却很少认真分析过。

android.util.Log常用的方法有以下5个:Log.v()  Log.d()   Log.i()   Log.w() 以及 Log.e() 。根据首字母对应VERBOSE,DEBUG,INFO, WARN,ERROR。

        1、Log.v 的调试颜色为黑色的,任何消息都会输出,这里的v代表verbose啰嗦的意思,平时使用就是Log.v("","");

  2、Log.d的输出颜色是蓝色的,仅输出debug调试的意思,但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择;

  3、Log.i的输出为绿色,一般提示性的消息information,它不会输出Log.v和Log.d的信息,但会显示i、w和e的信息;

  4、Log.w的意思为橙色,可以看作为warning警告,一般需要我们注意优化Android代码,同时选择它后还会输出Log.e的信息;

  5、Log.e为红色,可以想到error错误,这里仅显示红色的错误信息,这些错误就需要我们认真的分析,查看栈的信息了;

public final class Log {   } 可以看出,这个Log类是一个final的,不可被修改的。下面是源码中对这个类的解释,告诉我们如何使用。

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Tip: A good convention is to declare a TAG constant in your class:

private static final String TAG = "MyActivity";

and use that in subsequent calls to the log methods.

Tip: Don't forget that when you make a call like

Log.v(TAG, "index=" + i);

that when you're building the string to pass into Log.d, the compiler uses a StringBuilder and at least three allocations occur: the StringBuilder itself, the buffer, and the String object. Realistically, there is also another buffer allocation and copy, and even more pressure on the gc. That means that if your log message is filtered out, you might be doing significant work and incurring significant overhead.

 

里面定义了一些诸如  public static final int VERBOSE = 2; 这样的静态的、final的常量,去标示log的级别。

我们举例看v这个方法:

 public static int v(String tag, String msg) {
        return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
    }

需要两个参数,里面调用了println_native()这个方法来实现打印log信息,

   /** @hide */ public static native int println_native(int bufID, int priority, String tag, String msg);

 

log信息的路径是通过调用这个方法打印出来的:getStackTraceString()

public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        return sw.toString();
    }

 

请注意,里面还有这样一个内部静态类,从方法的注释中,我们知道,它是用来抓取异常信息的

Exception class used to capture a stack trace in {@link #wtf()}.

private static class TerribleFailure extends Exception {
        TerribleFailure(String msg, Throwable cause) { super(msg, cause); }
    }

然后通过wtf()这个方法打印出log信息。

 

 

 

 

 

 

 

 

 

 

 

 

 

原创粉丝点击