转自: http://my.oschina.net/wolfcs/blog/164624
在android Java code中输出log
android系统有4种类型、6个优先级的log,有一些常量用于标识这些信息,相关的定义在frameworks/base/core/Java/android/util/Log.java中可以看到:
01
/**
02
* Priority constant for the println method; use Log.v.
03
*/
04
public static final int VERBOSE =2;
05
06
/**
07
* Priority constant for the println method; use Log.d.
08
*/
09
public static final int DEBUG =3;
10
11
/**
12
* Priority constant for the println method; use Log.i.
13
*/
14
public static final int INFO =4;
15
16
/**
17
* Priority constant for the println method; use Log.w.
18
*/
19
public static final int WARN =5;
20
21
/**
22
* Priority constant for the println method; use Log.e.
23
*/
24
public static final int ERROR =6;
25
26
/**
27
* Priority constant for the println method.
28
*/
29
public static final int ASSERT =7;
30
31
/** @hide */ public static final int LOG_ID_MAIN =0;
32
/** @hide */ public static final int LOG_ID_RADIO =1;
33
/** @hide */ public static final int LOG_ID_EVENTS =2;
34
/** @hide */ public static final int LOG_ID_SYSTEM =3;
Java层可以通过三个class来输出其中三种类型的log,三种类型分别为MAIN、RADIO和SYSTEM,三个class分别为Log、Rlog和Slog,其package则分别为android.util、android.telephony和 android.util。这些用于打印log的classes,其构造函数都为private,因而都不能创建其对象,但它们都提供了静态方法来给用户打印log。各个log打印class的实现都大同小异,可以看一下Log这个class中的一些:
01
public static int v(String tag, String msg, Throwable tr) {
02
return println_native(LOG_ID_MAIN, VERBOSE, tag, msg +'\n' + getStackTraceString(tr));
03
}
04
05
/**
06
* Send a {@link #DEBUG} log message.
07
* @param tag Used to identify the source of a log message. It usually identifies
08
* the class or activity where the log call occurs.
09
* @param msg The message you would like logged.
10
*/
11
public static int d(String tag, String msg) {
12
return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
13
}
最终都会是调用Log.println_native()静态native方法来打印log,各个类中各个方法的不同之处也仅在于参数的差异。
Log.println_native()方法
这个方法的code在/frameworks/base/core/jni/android_util_Log.cpp,为:
01
static jint android_util_Log_println_native(JNIEnv* env, jobject clazz,
02
jint bufID, jint priority, jstring tagObj, jstring msgObj)
03
{
04
const char* tag = NULL;
05
const char* msg = NULL;
06
07
if (msgObj == NULL) {
08
jniThrowNullPointerException(env,"println needs a message");
09
return -1;
10
}
11
12
if (bufID < 0 || bufID >= LOG_ID_MAX) {
13
jniThrowNullPointerException(env,"bad bufID");
14
return -1;
15
}
16</