转载自http://blog.csdn.net/Luoshengyang/article/category/838604/3

Android系统开发中LOG的使用

在程序开发过程中,LOG是广泛使用的用来记录程序执行过程的机制,它既可以用于程序调试,也可以用于产品运营中的事件记录。在Android系统中,提供了简单、便利的LOG机制,开发人员可以方便地使用。在这一篇文章中,我们简单介绍在Android内核空间和用户空间中LOG的使用和查看方法。

一. 内核开发时LOG的使用。Android内核是基于Linux Kerne 2.36的,因此,Linux Kernel的LOG机制同样适合于Android内核,它就是有名的printk,与C语言的printf齐名。与printf类似,printk提供格式化输入功能,同时,它也具有所有LOG机制的特点--提供日志级别过虑功能。printk提供了8种日志级别(<linux/kernel.h>):

[cpp] view plaincopyprint?
  1. #define KERN_EMERG  "<0>"     /* system is unusable           */
  2. #define KERN_ALERT  "<1>"     /* action must be taken immediately */
  3. #define KERN_CRIT   "<2>"     /* critical conditions          */
  4. #deinfe KERN_ERR    "<3>"     /* error conditions         */
  5. #deinfe KERN_WARNING    "<4>"     /* warning conditions           */
  6. #deinfe KERN_NOTICE "<5>"     /* normal but significant condition */
  7. #deinfe KERN_INFO   "<6>"     /* informational            */
  8. #deinfe KERN_DEBUG  "<7>"     /* debug-level messages         */
#define KERN_EMERG   "<0>"   /* system is unusable           */
#define KERN_ALERT  "<1>"   /* action must be taken immediately */
#define KERN_CRIT   "<2>"   /* critical conditions          */
#deinfe KERN_ERR    "<3>"   /* error conditions         */
#deinfe KERN_WARNING    "<4>"   /* warning conditions           */
#deinfe KERN_NOTICE "<5>"   /* normal but significant condition */
#deinfe KERN_INFO   "<6>"   /* informational            */
#deinfe KERN_DEBUG  "<7>"   /* debug-level messages         */

printk的使用方法:

printk(KERN_ALERT"This is the log printed by printk in linux kernel space.");

KERN_ALERT表示日志级别,后面紧跟着要格式化字符串。

在Android系统中,printk输出的日志信息保存在/proc/kmsg中,要查看/proc/kmsg的内容,参照在Ubuntu上下载、编译和安装Android最新内核源代码(Linux Kernel)一文,在后台中运行模拟器:

USER-NAME@MACHINE-NAME:~/Android$ emulator &

       启动adb shell工具:

USER-NAME@MACHINE-NAME:~/Android$ adb shell

       查看/proc/kmsg文件:

root@android:/ # cat  /proc/kmsg

二. 用户空间程序开发时LOG的使用。Android系统在用户空间中提供了轻量级的logger日志系统,它是在内核中实现的一种设备驱动,与用户空间的logcat工具配合使用能够方便地跟踪调试程序。在Android系统中,分别为C/C++ 和Java语言提供两种不同的logger访问接口。C/C++日志接口一般是在编写硬件抽象层模块或者编写JNI方法时使用,而Java接口一般是在应用层编写APP时使用。

Android系统中的C/C++日志接口是通过宏来使用的。在system/core/include/android/log.h定义了日志的级别:

[cpp] view plaincopyprint?
  1. /*
  2. * Android log priority values, in ascending priority order.
  3. */
  4. typedef enum android_LogPriority {
  5. ANDROID_LOG_UNKNOWN = 0,
  6. ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
  7. ANDROID_LOG_VERBOSE,
  8. ANDROID_LOG_DEBUG,
  9. ANDROID_LOG_INFO,
  10. ANDROID_LOG_WARN,
  11. ANDROID_LOG_ERROR,
  12. ANDROID_LOG_FATAL,
  13. ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
  14. } android_LogPriority;
/*
* Android log priority values, in ascending priority order.
*/
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
} android_LogPriority;

在system/core/include/cutils/log.h中,定义了对应的宏,如对应于ANDROID_LOG_VERBOSE的宏LOGV:

[cpp] view plaincopyprint?
  1. /*
  2. * This is the local tag used for the following simplified
  3. * logging macros. You can change this preprocessor definition
  4. * before using the other macros to change the tag.
  5. */
  6. #ifndef LOG_TAG
  7. #define LOG_TAG NULL
  8. #endif
  9. /*
  10. * Simplified macro to send a verbose log message using the current LOG_TAG.
  11. */
  12. #ifndef LOGV
  13. #if LOG_NDEBUG
  14. #define LOGV(...)   ((void)0)
  15. #else
  16. #define LOGV(...)   ((void)LOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
  17. #endif
  18. #endif
  19. /*
  20. * Basic log message macro.
  21. *
  22. * Example:
  23. *  LOG(LOG_WARN, NULL, "Failed with error %d", errno);
  24. *
  25. * The second argument may be NULL or "" to indicate the "global" tag.
  26. */
  27. #ifndef LOG
  28. #define LOG(priority, tag, ...) \
  29. LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
  30. #endif
  31. /*
  32. * Log macro that allows you to specify a number for priority.
  33. */
  34. #ifndef LOG_PRI
  35. #define LOG_PRI(priority, tag, ...) \
  36. android_printLog(priority, tag, __VA_ARGS__)
  37. #endif
  38. /*
  39. * ================================================================
  40. *
  41. * The stuff in the rest of this file should not be used directly.
  42. */
  43. #define android_printLog(prio, tag, fmt...) \
  44. __android_log_print(prio, tag, fmt)
/*
* This is the local tag used for the following simplified
* logging macros. You can change this preprocessor definition
* before using the other macros to change the tag.
*/
#ifndef LOG_TAG
#define LOG_TAG NULL
#endif
/*
* Simplified macro to send a verbose log message using the current LOG_TAG.
*/
#ifndef LOGV
#if LOG_NDEBUG
#define LOGV(...)   ((void)0)
#else
#define LOGV(...)   ((void)LOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#endif
#endif
/*
* Basic log message macro.
*
* Example:
*  LOG(LOG_WARN, NULL, "Failed with error %d", errno);
*
* The second argument may be NULL or "" to indicate the "global" tag.
*/
#ifndef LOG
#define LOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#endif
/*
* Log macro that allows you to specify a number for priority.
*/
#ifndef LOG_PRI
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#endif
/*
* ================================================================
*
* The stuff in the rest of this file should not be used directly.
*/
#define android_printLog(prio, tag, fmt...) \
__android_log_print(prio, tag, fmt)

因此,如果要使用C/C++日志接口,只要定义自己的LOG_TAG宏和包含头文件system/core/include/cutils/log.h就可以了:

#define LOG_TAG "MY LOG TAG"

         #include <cutils/log.h>

就可以了,例如使用LOGV:

LOGV("This is the log printed by LOGV in android user space.");

再来看Android系统中的Java日志接口。Android系统在Frameworks层中定义了Log接口(frameworks/base/core/java/android/util/Log.java):

[java] view plaincopyprint?
  1. ................................................
  2. public final class Log {
  3. ................................................
  4. /**
  5. * Priority constant for the println method; use Log.v.
  6. */
  7. public static final int VERBOSE = 2;
  8. /**
  9. * Priority constant for the println method; use Log.d.
  10. */
  11. public static final int DEBUG = 3;
  12. /**
  13. * Priority constant for the println method; use Log.i.
  14. */
  15. public static final int INFO = 4;
  16. /**
  17. * Priority constant for the println method; use Log.w.
  18. */
  19. public static final int WARN = 5;
  20. /**
  21. * Priority constant for the println method; use Log.e.
  22. */
  23. public static final int ERROR = 6;
  24. /**
  25. * Priority constant for the println method.
  26. */
  27. public static final int ASSERT = 7;
  28. .....................................................
  29. public static int v(String tag, String msg) {
  30. return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
  31. }
  32. public static int v(String tag, String msg, Throwable tr) {
  33. return println_native(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
  34. }
  35. public static int d(String tag, String msg) {
  36. return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
  37. }
  38. public static int d(String tag, String msg, Throwable tr) {
  39. return println_native(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr));
  40. }
  41. public static int i(String tag, String msg) {
  42. return println_native(LOG_ID_MAIN, INFO, tag, msg);
  43. }
  44. public static int i(String tag, String msg, Throwable tr) {
  45. return println_native(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr));
  46. }
  47. public static int w(String tag, String msg) {
  48. return println_native(LOG_ID_MAIN, WARN, tag, msg);
  49. }
  50. public static int w(String tag, String msg, Throwable tr) {
  51. return println_native(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr));
  52. }
  53. public static int w(String tag, Throwable tr) {
  54. return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
  55. }
  56. public static int e(String tag, String msg) {
  57. return println_native(LOG_ID_MAIN, ERROR, tag, msg);
  58. }
  59. public static int e(String tag, String msg, Throwable tr) {
  60. return println_native(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr));
  61. }
  62. ..................................................................
  63. /**@hide */ public static native int println_native(int bufID,
  64. int priority, String tag, String msg);
  65. }
................................................
public final class Log {
................................................
/**
* Priority constant for the println method; use Log.v.
*/
public static final int VERBOSE = 2;
/**
* Priority constant for the println method; use Log.d.
*/
public static final int DEBUG = 3;
/**
* Priority constant for the println method; use Log.i.
*/
public static final int INFO = 4;
/**
* Priority constant for the println method; use Log.w.
*/
public static final int WARN = 5;
/**
* Priority constant for the println method; use Log.e.
*/
public static final int ERROR = 6;
/**
* Priority constant for the println method.
*/
public static final int ASSERT = 7;
.....................................................
public static int v(String tag, String msg) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
}
public static int v(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
}
public static int d(String tag, String msg) {
return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
}
public static int d(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr));
}
public static int i(String tag, String msg) {
return println_native(LOG_ID_MAIN, INFO, tag, msg);
}
public static int i(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr));
}
public static int w(String tag, String msg) {
return println_native(LOG_ID_MAIN, WARN, tag, msg);
}
public static int w(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr));
}
public static int w(String tag, Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
}
public static int e(String tag, String msg) {
return println_native(LOG_ID_MAIN, ERROR, tag, msg);
}
public static int e(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr));
}
..................................................................
/**@hide */ public static native int println_native(int bufID,
int priority, String tag, String msg);
}

因此,如果要使用Java日志接口,只要在类中定义的LOG_TAG常量和引用android.util.Log就可以了:

private static final String LOG_TAG = "MY_LOG_TAG";

        Log.i(LOG_TAG, "This is the log printed by Log.i in android user space.");

要查看这些LOG的输出,可以配合logcat工具。如果是在Eclipse环境下运行模拟器,并且安装了Android插件,那么,很简单,直接在Eclipse就可以查看了:

如果是在自己编译的Android源代码工程中使用,则在后台中运行模拟器:

USER-NAME@MACHINE-NAME:~/Android$ emulator &

       启动adb shell工具:

USER-NAME@MACHINE-NAME:~/Android$ adb shell

       使用logcat命令查看日志:

root@android:/ # logcat

       这样就可以看到输出的日志了

Android日志系统驱动程序Logger源代码分析

我们知道,在Android系统中,提供了一个轻量级的日志系统,这个日志系统是以驱动程序的形式实现在内核空间的,而在用户空间分别提供了Java接口和C/C++接口来使用这个日志系统,取决于你编写的是Android应用程序还是系统组件。在前面的文章浅谈Android系统开发中LOG的使用中,已经简要地介绍了在Android应用程序开发中Log的使用方法,在这一篇文章中,我们将更进一步地分析Logger驱动程序的源代码,使得我们对Android日志系统有一个深刻的认识。

既然Android 日志系统是以驱动程序的形式实现在内核空间的,我们就需要获取Android内核源代码来分析了,请参照前面在Ubuntu上下载、编译和安装Android最新源代码和在Ubuntu上下载、编译和安装Android最新内核源代码(Linux Kernel)两篇文章,下载好Android源代码工程。Logger驱动程序主要由两个文件构成,分别是:

kernel/common/drivers/staging/android/logger.h

kernel/common/drivers/staging/android/logger.c

接下来,我们将分别介绍Logger驱动程序的相关数据结构,然后对Logger驱动程序源代码进行情景分析,分别日志系统初始化情景、日志读取情景和日志写入情景。

一. Logger驱动程序的相关数据结构。

我们首先来看logger.h头文件的内容:

[cpp] view plaincopyprint?
  1. #ifndef _LINUX_LOGGER_H
  2. #define _LINUX_LOGGER_H
  3. #include <linux/types.h>
  4. #include <linux/ioctl.h>
  5. struct logger_entry {
  6. __u16       len;    /* length of the payload */
  7. __u16       __pad;  /* no matter what, we get 2 bytes of padding */
  8. __s32       pid;    /* generating process's pid */
  9. __s32       tid;    /* generating process's tid */
  10. __s32       sec;    /* seconds since Epoch */
  11. __s32       nsec;   /* nanoseconds */
  12. char        msg[0]; /* the entry's payload */
  13. };
  14. #define LOGGER_LOG_RADIO    "log_radio" /* radio-related messages */
  15. #define LOGGER_LOG_EVENTS   "log_events"    /* system/hardware events */
  16. #define LOGGER_LOG_MAIN     "log_main"  /* everything else */
  17. #define LOGGER_ENTRY_MAX_LEN        (4*1024)
  18. #define LOGGER_ENTRY_MAX_PAYLOAD    \
  19. (LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry))
  20. #define __LOGGERIO  0xAE
  21. #define LOGGER_GET_LOG_BUF_SIZE     _IO(__LOGGERIO, 1) /* size of log */
  22. #define LOGGER_GET_LOG_LEN      _IO(__LOGGERIO, 2) /* used log len */
  23. #define LOGGER_GET_NEXT_ENTRY_LEN   _IO(__LOGGERIO, 3) /* next entry len */
  24. #define LOGGER_FLUSH_LOG        _IO(__LOGGERIO, 4) /* flush log */
  25. #endif /* _LINUX_LOGGER_H */
#ifndef _LINUX_LOGGER_H
#define _LINUX_LOGGER_H
#include <linux/types.h>
#include <linux/ioctl.h>
struct logger_entry {
__u16       len;    /* length of the payload */
__u16       __pad;  /* no matter what, we get 2 bytes of padding */
__s32       pid;    /* generating process's pid */
__s32       tid;    /* generating process's tid */
__s32       sec;    /* seconds since Epoch */
__s32       nsec;   /* nanoseconds */
char        msg[0]; /* the entry's payload */
};
#define LOGGER_LOG_RADIO    "log_radio"   /* radio-related messages */
#define LOGGER_LOG_EVENTS   "log_events"  /* system/hardware events */
#define LOGGER_LOG_MAIN     "log_main"    /* everything else */
#define LOGGER_ENTRY_MAX_LEN        (4*1024)
#define LOGGER_ENTRY_MAX_PAYLOAD    \
(LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry))
#define __LOGGERIO  0xAE
#define LOGGER_GET_LOG_BUF_SIZE     _IO(__LOGGERIO, 1) /* size of log */
#define LOGGER_GET_LOG_LEN      _IO(__LOGGERIO, 2) /* used log len */
#define LOGGER_GET_NEXT_ENTRY_LEN   _IO(__LOGGERIO, 3) /* next entry len */
#define LOGGER_FLUSH_LOG        _IO(__LOGGERIO, 4) /* flush log */
#endif /* _LINUX_LOGGER_H */

struct logger_entry是一个用于描述一条Log记录的结构体。len成员变量记录了这条记录的有效负载的长度,有效负载指定的日志记录本身的长度,但是不包括用于描述这个记录的struct logger_entry结构体。回忆一下我们调用android.util.Log接口来使用日志系统时,会指定日志的优先级别Priority、Tag字符串以及Msg字符串,Priority + Tag + Msg三者内容的长度加起来就是记录的有效负载长度了。__pad成员变量是用来对齐结构体的。pid和tid成员变量分别用来记录是哪条进程写入了这条记录。sec和nsec成员变量记录日志写的时间。msg成员变量记录的就有效负载的内容了,它的大小由len成员变量来确定。

接着定义两个宏:

#define LOGGER_ENTRY_MAX_LEN             (4*1024)

#define LOGGER_ENTRY_MAX_PAYLOAD   \

(LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry))

从这两个宏可以看出,每条日志记录的有效负载长度加上结构体logger_entry的长度不能超过4K个字节。

logger.h文件中还定义了其它宏,读者可以自己分析,在下面的分析中,碰到时,我们也会详细解释。

再来看logger.c文件中,其它相关数据结构的定义:

[cpp] view plaincopyprint?
  1. /*
  2. * struct logger_log - represents a specific log, such as 'main' or 'radio'
  3. *
  4. * This structure lives from module insertion until module removal, so it does
  5. * not need additional reference counting. The structure is protected by the
  6. * mutex 'mutex'.
  7. */
  8. struct logger_log {
  9. unsigned char *     buffer; /* the ring buffer itself */
  10. struct miscdevice   misc;   /* misc device representing the log */
  11. wait_queue_head_t   wq; /* wait queue for readers */
  12. struct list_head    readers; /* this log's readers */
  13. struct mutex        mutex;  /* mutex protecting buffer */
  14. size_t          w_off;  /* current write head offset */
  15. size_t          head;   /* new readers start here */
  16. size_t          size;   /* size of the log */
  17. };
  18. /*
  19. * struct logger_reader - a logging device open for reading
  20. *
  21. * This object lives from open to release, so we don't need additional
  22. * reference counting. The structure is protected by log->mutex.
  23. */
  24. struct logger_reader {
  25. struct logger_log * log;    /* associated log */
  26. struct list_head    list;   /* entry in logger_log's list */
  27. size_t          r_off;  /* current read head offset */
  28. };
  29. /* logger_offset - returns index 'n' into the log via (optimized) modulus */
  30. #define logger_offset(n)    ((n) & (log->size - 1))
/*
* struct logger_log - represents a specific log, such as 'main' or 'radio'
*
* This structure lives from module insertion until module removal, so it does
* not need additional reference counting. The structure is protected by the
* mutex 'mutex'.
*/
struct logger_log {
unsigned char *     buffer; /* the ring buffer itself */
struct miscdevice   misc;   /* misc device representing the log */
wait_queue_head_t   wq; /* wait queue for readers */
struct list_head    readers; /* this log's readers */
struct mutex        mutex;  /* mutex protecting buffer */
size_t          w_off;  /* current write head offset */
size_t          head;   /* new readers start here */
size_t          size;   /* size of the log */
};
/*
* struct logger_reader - a logging device open for reading
*
* This object lives from open to release, so we don't need additional
* reference counting. The structure is protected by log->mutex.
*/
struct logger_reader {
struct logger_log * log;    /* associated log */
struct list_head    list;   /* entry in logger_log's list */
size_t          r_off;  /* current read head offset */
};
/* logger_offset - returns index 'n' into the log via (optimized) modulus */
#define logger_offset(n)    ((n) & (log->size - 1))

结构体struct logger_log就是真正用来保存日志的地方了。buffer成员变量变是用保存日志信息的内存缓冲区,它的大小由size成员变量确定。从misc成员变量可以看出,logger驱动程序使用的设备属于misc类型的设备,通过在Android模拟器上执行cat /proc/devices命令(可参考在Ubuntu上下载、编译和安装Android最新内核源代码(Linux Kernel)一文),可以看出,misc类型设备的主设备号是10。关于主设备号的相关知识,可以参考Android学习启动篇一文中提到的Linux Driver Development一书。wq成员变量是一个等待队列,用于保存正在等待读取日志的进程。readers成员变量用来保存当前正在读取日志的进程,正在读取日志的进程由结构体logger_reader来描述。mutex成员变量是一个互斥量,用来保护log的并发访问。可以看出,这里的日志系统的读写问题,其实是一个生产者-消费者的问题,因此,需要互斥量来保护log的并发访问。 w_off成员变量用来记录下一条日志应该从哪里开始写。head成员变量用来表示打开日志文件中,应该从哪一个位置开始读取日志。

结构体struct logger_reader用来表示一个读取日志的进程,log成员变量指向要读取的日志缓冲区。list成员变量用来连接其它读者进程。r_off成员变量表示当前要读取的日志在缓冲区中的位置。

struct logger_log结构体中用于保存日志信息的内存缓冲区buffer是一个循环使用的环形缓冲区,缓冲区中保存的内容是以struct logger_entry为单位的,每个单位的组成为:

struct logger_entry | priority | tag | msg

由于是内存缓冲区buffer是一个循环使用的环形缓冲区,给定一个偏移值,它在buffer中的位置由下logger_offset来确定:

#define logger_offset(n)          ((n) & (log->size - 1))

二. Logger驱动程序模块的初始化过程分析。

继续看logger.c文件,定义了三个日志设备:

[cpp] view plaincopyprint?
  1. /*
  2. * Defines a log structure with name 'NAME' and a size of 'SIZE' bytes, which
  3. * must be a power of two, greater than LOGGER_ENTRY_MAX_LEN, and less than
  4. * LONG_MAX minus LOGGER_ENTRY_MAX_LEN.
  5. */
  6. #define DEFINE_LOGGER_DEVICE(VAR, NAME, SIZE) \
  7. static unsigned char _buf_ ## VAR[SIZE]; \
  8. static struct logger_log VAR = { \
  9. .buffer = _buf_ ## VAR, \
  10. .misc = { \
  11. .minor = MISC_DYNAMIC_MINOR, \
  12. .name = NAME, \
  13. .fops = &logger_fops, \
  14. .parent = NULL, \
  15. }, \
  16. .wq = __WAIT_QUEUE_HEAD_INITIALIZER(VAR .wq), \
  17. .readers = LIST_HEAD_INIT(VAR .readers), \
  18. .mutex = __MUTEX_INITIALIZER(VAR .mutex), \
  19. .w_off = 0, \
  20. .head = 0, \
  21. .size = SIZE, \
  22. };
  23. DEFINE_LOGGER_DEVICE(log_main, LOGGER_LOG_MAIN, 64*1024)
  24. DEFINE_LOGGER_DEVICE(log_events, LOGGER_LOG_EVENTS, 256*1024)
  25. DEFINE_LOGGER_DEVICE(log_radio, LOGGER_LOG_RADIO, 64*1024)
/*
* Defines a log structure with name 'NAME' and a size of 'SIZE' bytes, which
* must be a power of two, greater than LOGGER_ENTRY_MAX_LEN, and less than
* LONG_MAX minus LOGGER_ENTRY_MAX_LEN.
*/
#define DEFINE_LOGGER_DEVICE(VAR, NAME, SIZE) \
static unsigned char _buf_ ## VAR[SIZE]; \
static struct logger_log VAR = { \
.buffer = _buf_ ## VAR, \
.misc = { \
.minor = MISC_DYNAMIC_MINOR, \
.name = NAME, \
.fops = &logger_fops, \
.parent = NULL, \
}, \
.wq = __WAIT_QUEUE_HEAD_INITIALIZER(VAR .wq), \
.readers = LIST_HEAD_INIT(VAR .readers), \
.mutex = __MUTEX_INITIALIZER(VAR .mutex), \
.w_off = 0, \
.head = 0, \
.size = SIZE, \
};
DEFINE_LOGGER_DEVICE(log_main, LOGGER_LOG_MAIN, 64*1024)
DEFINE_LOGGER_DEVICE(log_events, LOGGER_LOG_EVENTS, 256*1024)
DEFINE_LOGGER_DEVICE(log_radio, LOGGER_LOG_RADIO, 64*1024)

分别是log_main、log_events和log_radio,名称分别LOGGER_LOG_MAIN、LOGGER_LOG_EVENTS和LOGGER_LOG_RADIO,它们的次设备号为MISC_DYNAMIC_MINOR,即为在注册时动态分配。在logger.h文件中,有这三个宏的定义:

#define LOGGER_LOG_RADIO "log_radio" /* radio-related messages */
       #define LOGGER_LOG_EVENTS "log_events" /* system/hardware events */
       #define LOGGER_LOG_MAIN "log_main" /* everything else */

注释说明了这三个日志设备的用途。注册的日志设备文件操作方法为logger_fops:

[cpp] view plaincopyprint?
  1. static struct file_operations logger_fops = {
  2. .owner = THIS_MODULE,
  3. .read = logger_read,
  4. .aio_write = logger_aio_write,
  5. .poll = logger_poll,
  6. .unlocked_ioctl = logger_ioctl,
  7. .compat_ioctl = logger_ioctl,
  8. .open = logger_open,
  9. .release = logger_release,
  10. };
static struct file_operations logger_fops = {
.owner = THIS_MODULE,
.read = logger_read,
.aio_write = logger_aio_write,
.poll = logger_poll,
.unlocked_ioctl = logger_ioctl,
.compat_ioctl = logger_ioctl,
.open = logger_open,
.release = logger_release,
};

日志驱动程序模块的初始化函数为logger_init:

[cpp] view plaincopyprint?
  1. static int __init logger_init(void)
  2. {
  3. int ret;
  4. ret = init_log(&log_main);
  5. if (unlikely(ret))
  6. goto out;
  7. ret = init_log(&log_events);
  8. if (unlikely(ret))
  9. goto out;
  10. ret = init_log(&log_radio);
  11. if (unlikely(ret))
  12. goto out;
  13. out:
  14. return ret;
  15. }
  16. device_initcall(logger_init);
static int __init logger_init(void)
{
int ret;
ret = init_log(&log_main);
if (unlikely(ret))
goto out;
ret = init_log(&log_events);
if (unlikely(ret))
goto out;
ret = init_log(&log_radio);
if (unlikely(ret))
goto out;
out:
return ret;
}
device_initcall(logger_init);

logger_init函数通过调用init_log函数来初始化了上述提到的三个日志设备:

[cpp] view plaincopyprint?
  1. static int __init init_log(struct logger_log *log)
  2. {
  3. int ret;
  4. ret = misc_register(&log->misc);
  5. if (unlikely(ret)) {
  6. printk(KERN_ERR "logger: failed to register misc "
  7. "device for log '%s'!\n", log->misc.name);
  8. return ret;
  9. }
  10. printk(KERN_INFO "logger: created %luK log '%s'\n",
  11. (unsigned long) log->size >> 10, log->misc.name);
  12. return 0;
  13. }
static int __init init_log(struct logger_log *log)
{
int ret;
ret = misc_register(&log->misc);
if (unlikely(ret)) {
printk(KERN_ERR "logger: failed to register misc "
"device for log '%s'!\n", log->misc.name);
return ret;
}
printk(KERN_INFO "logger: created %luK log '%s'\n",
(unsigned long) log->size >> 10, log->misc.name);
return 0;
}

init_log函数主要调用了misc_register函数来注册misc设备,misc_register函数定义在kernel/common/drivers/char/misc.c文件中:

[cpp] view plaincopyprint?
  1. /**
  2. *      misc_register   -       register a miscellaneous device
  3. *      @misc: device structure
  4. *
  5. *      Register a miscellaneous device with the kernel. If the minor
  6. *      number is set to %MISC_DYNAMIC_MINOR a minor number is assigned
  7. *      and placed in the minor field of the structure. For other cases
  8. *      the minor number requested is used.
  9. *
  10. *      The structure passed is linked into the kernel and may not be
  11. *      destroyed until it has been unregistered.
  12. *
  13. *      A zero is returned on success and a negative errno code for
  14. *      failure.
  15. */
  16. int misc_register(struct miscdevice * misc)
  17. {
  18. struct miscdevice *c;
  19. dev_t dev;
  20. int err = 0;
  21. INIT_LIST_HEAD(&misc->list);
  22. mutex_lock(&misc_mtx);
  23. list_for_each_entry(c, &misc_list, list) {
  24. if (c->minor == misc->minor) {
  25. mutex_unlock(&misc_mtx);
  26. return -EBUSY;
  27. }
  28. }
  29. if (misc->minor == MISC_DYNAMIC_MINOR) {
  30. int i = DYNAMIC_MINORS;
  31. while (--i >= 0)
  32. if ( (misc_minors[i>>3] & (1 << (i&7))) == 0)
  33. break;
  34. if (i<0) {
  35. mutex_unlock(&misc_mtx);
  36. return -EBUSY;
  37. }
  38. misc->minor = i;
  39. }
  40. if (misc->minor < DYNAMIC_MINORS)
  41. misc_minors[misc->minor >> 3] |= 1 << (misc->minor & 7);
  42. dev = MKDEV(MISC_MAJOR, misc->minor);
  43. misc->this_device = device_create(misc_class, misc->parent, dev, NULL,
  44. "%s", misc->name);
  45. if (IS_ERR(misc->this_device)) {
  46. err = PTR_ERR(misc->this_device);
  47. goto out;
  48. }
  49. /*
  50. * Add it to the front, so that later devices can "override"
  51. * earlier defaults
  52. */
  53. list_add(&misc->list, &misc_list);
  54. out:
  55. mutex_unlock(&misc_mtx);
  56. return err;
  57. }
/**
*      misc_register   -       register a miscellaneous device
*      @misc: device structure
*
*      Register a miscellaneous device with the kernel. If the minor
*      number is set to %MISC_DYNAMIC_MINOR a minor number is assigned
*      and placed in the minor field of the structure. For other cases
*      the minor number requested is used.
*
*      The structure passed is linked into the kernel and may not be
*      destroyed until it has been unregistered.
*
*      A zero is returned on success and a negative errno code for
*      failure.
*/
int misc_register(struct miscdevice * misc)
{
struct miscdevice *c;
dev_t dev;
int err = 0;
INIT_LIST_HEAD(&misc->list);
mutex_lock(&misc_mtx);
list_for_each_entry(c, &misc_list, list) {
if (c->minor == misc->minor) {
mutex_unlock(&misc_mtx);
return -EBUSY;
}
}
if (misc->minor == MISC_DYNAMIC_MINOR) {
int i = DYNAMIC_MINORS;
while (--i >= 0)
if ( (misc_minors[i>>3] & (1 << (i&7))) == 0)
break;
if (i<0) {
mutex_unlock(&misc_mtx);
return -EBUSY;
}
misc->minor = i;
}
if (misc->minor < DYNAMIC_MINORS)
misc_minors[misc->minor >> 3] |= 1 << (misc->minor & 7);
dev = MKDEV(MISC_MAJOR, misc->minor);
misc->this_device = device_create(misc_class, misc->parent, dev, NULL,
"%s", misc->name);
if (IS_ERR(misc->this_device)) {
err = PTR_ERR(misc->this_device);
goto out;
}
/*
* Add it to the front, so that later devices can "override"
* earlier defaults
*/
list_add(&misc->list, &misc_list);
out:
mutex_unlock(&misc_mtx);
return err;
}

注册完成后,通过device_create创建设备文件节点。这里,将创建/dev/log/main、/dev/log/events和/dev/log/radio三个设备文件,这样,用户空间就可以通过读写这三个文件和驱动程序进行交互。

三. Logger驱动程序的日志记录读取过程分析。

继续看logger.c 文件,注册的读取日志设备文件的方法为logger_read:

[cpp] view plaincopyprint?
  1. /*
  2. * logger_read - our log's read() method
  3. *
  4. * Behavior:
  5. *
  6. *  - O_NONBLOCK works
  7. *  - If there are no log entries to read, blocks until log is written to
  8. *  - Atomically reads exactly one log entry
  9. *
  10. * Optimal read size is LOGGER_ENTRY_MAX_LEN. Will set errno to EINVAL if read
  11. * buffer is insufficient to hold next entry.
  12. */
  13. static ssize_t logger_read(struct file *file, char __user *buf,
  14. size_t count, loff_t *pos)
  15. {
  16. struct logger_reader *reader = file->private_data;
  17. struct logger_log *log = reader->log;
  18. ssize_t ret;
  19. DEFINE_WAIT(wait);
  20. start:
  21. while (1) {
  22. prepare_to_wait(&log->wq, &wait, TASK_INTERRUPTIBLE);
  23. mutex_lock(&log->mutex);
  24. ret = (log->w_off == reader->r_off);
  25. mutex_unlock(&log->mutex);
  26. if (!ret)
  27. break;
  28. if (file->f_flags & O_NONBLOCK) {
  29. ret = -EAGAIN;
  30. break;
  31. }
  32. if (signal_pending(current)) {
  33. ret = -EINTR;
  34. break;
  35. }
  36. schedule();
  37. }
  38. finish_wait(&log->wq, &wait);
  39. if (ret)
  40. return ret;
  41. mutex_lock(&log->mutex);
  42. /* is there still something to read or did we race? */
  43. if (unlikely(log->w_off == reader->r_off)) {
  44. mutex_unlock(&log->mutex);
  45. goto start;
  46. }
  47. /* get the size of the next entry */
  48. ret = get_entry_len(log, reader->r_off);
  49. if (count < ret) {
  50. ret = -EINVAL;
  51. goto out;
  52. }
  53. /* get exactly one entry from the log */
  54. ret = do_read_log_to_user(log, reader, buf, ret);
  55. out:
  56. mutex_unlock(&log->mutex);
  57. return ret;
  58. }
/*
* logger_read - our log's read() method
*
* Behavior:
*
*   - O_NONBLOCK works
*   - If there are no log entries to read, blocks until log is written to
*   - Atomically reads exactly one log entry
*
* Optimal read size is LOGGER_ENTRY_MAX_LEN. Will set errno to EINVAL if read
* buffer is insufficient to hold next entry.
*/
static ssize_t logger_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
struct logger_reader *reader = file->private_data;
struct logger_log *log = reader->log;
ssize_t ret;
DEFINE_WAIT(wait);
start:
while (1) {
prepare_to_wait(&log->wq, &wait, TASK_INTERRUPTIBLE);
mutex_lock(&log->mutex);
ret = (log->w_off == reader->r_off);
mutex_unlock(&log->mutex);
if (!ret)
break;
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = -EINTR;
break;
}
schedule();
}
finish_wait(&log->wq, &wait);
if (ret)
return ret;
mutex_lock(&log->mutex);
/* is there still something to read or did we race? */
if (unlikely(log->w_off == reader->r_off)) {
mutex_unlock(&log->mutex);
goto start;
}
/* get the size of the next entry */
ret = get_entry_len(log, reader->r_off);
if (count < ret) {
ret = -EINVAL;
goto out;
}
/* get exactly one entry from the log */
ret = do_read_log_to_user(log, reader, buf, ret);
out:
mutex_unlock(&log->mutex);
return ret;
}

注意,在函数开始的地方,表示读取日志上下文的struct logger_reader是保存在文件指针的private_data成员变量里面的,这是在打开设备文件时设置的,设备文件打开方法为logger_open:

[cpp] view plaincopyprint?
  1. /*
  2. * logger_open - the log's open() file operation
  3. *
  4. * Note how near a no-op this is in the write-only case. Keep it that way!
  5. */
  6. static int logger_open(struct inode *inode, struct file *file)
  7. {
  8. struct logger_log *log;
  9. int ret;
  10. ret = nonseekable_open(inode, file);
  11. if (ret)
  12. return ret;
  13. log = get_log_from_minor(MINOR(inode->i_rdev));
  14. if (!log)
  15. return -ENODEV;
  16. if (file->f_mode & FMODE_READ) {
  17. struct logger_reader *reader;
  18. reader = kmalloc(sizeof(struct logger_reader), GFP_KERNEL);
  19. if (!reader)
  20. return -ENOMEM;
  21. reader->log = log;
  22. INIT_LIST_HEAD(&reader->list);
  23. mutex_lock(&log->mutex);
  24. reader->r_off = log->head;
  25. list_add_tail(&reader->list, &log->readers);
  26. mutex_unlock(&log->mutex);
  27. file->private_data = reader;
  28. } else
  29. file->private_data = log;
  30. return 0;
  31. }
/*
* logger_open - the log's open() file operation
*
* Note how near a no-op this is in the write-only case. Keep it that way!
*/
static int logger_open(struct inode *inode, struct file *file)
{
struct logger_log *log;
int ret;
ret = nonseekable_open(inode, file);
if (ret)
return ret;
log = get_log_from_minor(MINOR(inode->i_rdev));
if (!log)
return -ENODEV;
if (file->f_mode & FMODE_READ) {
struct logger_reader *reader;
reader = kmalloc(sizeof(struct logger_reader), GFP_KERNEL);
if (!reader)
return -ENOMEM;
reader->log = log;
INIT_LIST_HEAD(&reader->list);
mutex_lock(&log->mutex);
reader->r_off = log->head;
list_add_tail(&reader->list, &log->readers);
mutex_unlock(&log->mutex);
file->private_data = reader;
} else
file->private_data = log;
return 0;
}

新打开日志设备文件时,是从log->head位置开始读取日志的,保存在struct logger_reader的成员变量r_off中。

start标号处的while循环是在等待日志可读,如果已经没有新的日志可读了,那么就要读进程就要进入休眠状态,等待新的日志写入后再唤醒,这是通过prepare_wait和schedule两个调用来实现的。如果没有新的日志可读,并且设备文件不是以非阻塞O_NONBLOCK的方式打开或者这时有信号要处理(signal_pending(current)),那么就直接返回,不再等待新的日志写入。判断当前是否有新的日志可读的方法是:

ret = (log->w_off == reader->r_off);

即判断当前缓冲区的写入位置和当前读进程的读取位置是否相等,如果不相等,则说明有新的日志可读。

继续向下看,如果有新的日志可读,那么就,首先通过get_entry_len来获取下一条可读的日志记录的长度,从这里可以看出,日志读取进程是以日志记录为单位进行读取的,一次只读取一条记录。get_entry_len的函数实现如下:

[cpp] view plaincopyprint?
  1. /*
  2. * get_entry_len - Grabs the length of the payload of the next entry starting
  3. * from 'off'.
  4. *
  5. * Caller needs to hold log->mutex.
  6. */
  7. static __u32 get_entry_len(struct logger_log *log, size_t off)
  8. {
  9. __u16 val;
  10. switch (log->size - off) {
  11. case 1:
  12. memcpy(&val, log->buffer + off, 1);
  13. memcpy(((char *) &val) + 1, log->buffer, 1);
  14. break;
  15. default:
  16. memcpy(&val, log->buffer + off, 2);
  17. }
  18. return sizeof(struct logger_entry) + val;
  19. }
/*
* get_entry_len - Grabs the length of the payload of the next entry starting
* from 'off'.
*
* Caller needs to hold log->mutex.
*/
static __u32 get_entry_len(struct logger_log *log, size_t off)
{
__u16 val;
switch (log->size - off) {
case 1:
memcpy(&val, log->buffer + off, 1);
memcpy(((char *) &val) + 1, log->buffer, 1);
break;
default:
memcpy(&val, log->buffer + off, 2);
}
return sizeof(struct logger_entry) + val;
}

上面我们提到,每一条日志记录是由两大部分组成的,一个用于描述这条日志记录的结构体struct logger_entry,另一个是记录体本身,即有效负载。结构体struct logger_entry的长度是固定的,只要知道有效负载的长度,就可以知道整条日志记录的长度了。而有效负载的长度是记录在结构体struct logger_entry的成员变量len中,而len成员变量的地址与struct logger_entry的地址相同,因此,只需要读取记录的开始位置的两个字节就可以了。又由于日志记录缓冲区是循环使用的,这两个节字有可能是第一个字节存放在缓冲区最后一个字节,而第二个字节存放在缓冲区的第一个节,除此之外,这两个字节都是连在一起的。因此,分两种情况来考虑,对于前者,分别通过读取缓冲区最后一个字节和第一个字节来得到日志记录的有效负载长度到本地变量val中,对于后者,直接读取连续两个字节的值到本地变量val中。这两种情况是通过判断日志缓冲区的大小和要读取的日志记录在缓冲区中的位置的差值来区别的,如果相差1,就说明是前一种情况了。最后,把有效负载的长度val加上struct logger_entry的长度就得到了要读取的日志记录的总长度了。

接着往下看,得到了要读取的记录的长度,就调用do_read_log_to_user函数来执行真正的读取动作:

[cpp] view plaincopyprint?
  1. static ssize_t do_read_log_to_user(struct logger_log *log,
  2. struct logger_reader *reader,
  3. char __user *buf,
  4. size_t count)
  5. {
  6. size_t len;
  7. /*
  8. * We read from the log in two disjoint operations. First, we read from
  9. * the current read head offset up to 'count' bytes or to the end of
  10. * the log, whichever comes first.
  11. */
  12. len = min(count, log->size - reader->r_off);
  13. if (copy_to_user(buf, log->buffer + reader->r_off, len))
  14. return -EFAULT;
  15. /*
  16. * Second, we read any remaining bytes, starting back at the head of
  17. * the log.
  18. */
  19. if (count != len)
  20. if (copy_to_user(buf + len, log->buffer, count - len))
  21. return -EFAULT;
  22. reader->r_off = logger_offset(reader->r_off + count);
  23. return count;
  24. }
static ssize_t do_read_log_to_user(struct logger_log *log,
struct logger_reader *reader,
char __user *buf,
size_t count)
{
size_t len;
/*
* We read from the log in two disjoint operations. First, we read from
* the current read head offset up to 'count' bytes or to the end of
* the log, whichever comes first.
*/
len = min(count, log->size - reader->r_off);
if (copy_to_user(buf, log->buffer + reader->r_off, len))
return -EFAULT;
/*
* Second, we read any remaining bytes, starting back at the head of
* the log.
*/
if (count != len)
if (copy_to_user(buf + len, log->buffer, count - len))
return -EFAULT;
reader->r_off = logger_offset(reader->r_off + count);
return count;
}

这个函数简单地调用copy_to_user函数来把位于内核空间的日志缓冲区指定的内容拷贝到用户空间的内存缓冲区就可以了,同时,把当前读取日志进程的上下文信息中的读偏移r_off前进到下一条日志记录的开始的位置上。

四.  Logger驱动程序的日志记录写入过程分析。

继续看logger.c 文件,注册的写入日志设备文件的方法为logger_aio_write:

[cpp] view plaincopyprint?
  1. /*
  2. * logger_aio_write - our write method, implementing support for write(),
  3. * writev(), and aio_write(). Writes are our fast path, and we try to optimize
  4. * them above all else.
  5. */
  6. ssize_t logger_aio_write(struct kiocb *iocb, const struct iovec *iov,
  7. unsigned long nr_segs, loff_t ppos)
  8. {
  9. struct logger_log *log = file_get_log(iocb->ki_filp);
  10. size_t orig = log->w_off;
  11. struct logger_entry header;
  12. struct timespec now;
  13. ssize_t ret = 0;
  14. now = current_kernel_time();
  15. header.pid = current->tgid;
  16. header.tid = current->pid;
  17. header.sec = now.tv_sec;
  18. header.nsec = now.tv_nsec;
  19. header.len = min_t(size_t, iocb->ki_left, LOGGER_ENTRY_MAX_PAYLOAD);
  20. /* null writes succeed, return zero */
  21. if (unlikely(!header.len))
  22. return 0;
  23. mutex_lock(&log->mutex);
  24. /*
  25. * Fix up any readers, pulling them forward to the first readable
  26. * entry after (what will be) the new write offset. We do this now
  27. * because if we partially fail, we can end up with clobbered log
  28. * entries that encroach on readable buffer.
  29. */
  30. fix_up_readers(log, sizeof(struct logger_entry) + header.len);
  31. do_write_log(log, &header, sizeof(struct logger_entry));
  32. while (nr_segs-- > 0) {
  33. size_t len;
  34. ssize_t nr;
  35. /* figure out how much of this vector we can keep */
  36. len = min_t(size_t, iov->iov_len, header.len - ret);
  37. /* write out this segment's payload */
  38. nr = do_write_log_from_user(log, iov->iov_base, len);
  39. if (unlikely(nr < 0)) {
  40. log->w_off = orig;
  41. mutex_unlock(&log->mutex);
  42. return nr;
  43. }
  44. iov++;
  45. ret += nr;
  46. }
  47. mutex_unlock(&log->mutex);
  48. /* wake up any blocked readers */
  49. wake_up_interruptible(&log->wq);
  50. return ret;
  51. }
/*
* logger_aio_write - our write method, implementing support for write(),
* writev(), and aio_write(). Writes are our fast path, and we try to optimize
* them above all else.
*/
ssize_t logger_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t ppos)
{
struct logger_log *log = file_get_log(iocb->ki_filp);
size_t orig = log->w_off;
struct logger_entry header;
struct timespec now;
ssize_t ret = 0;
now = current_kernel_time();
header.pid = current->tgid;
header.tid = current->pid;
header.sec = now.tv_sec;
header.nsec = now.tv_nsec;
header.len = min_t(size_t, iocb->ki_left, LOGGER_ENTRY_MAX_PAYLOAD);
/* null writes succeed, return zero */
if (unlikely(!header.len))
return 0;
mutex_lock(&log->mutex);
/*
* Fix up any readers, pulling them forward to the first readable
* entry after (what will be) the new write offset. We do this now
* because if we partially fail, we can end up with clobbered log
* entries that encroach on readable buffer.
*/
fix_up_readers(log, sizeof(struct logger_entry) + header.len);
do_write_log(log, &header, sizeof(struct logger_entry));
while (nr_segs-- > 0) {
size_t len;
ssize_t nr;
/* figure out how much of this vector we can keep */
len = min_t(size_t, iov->iov_len, header.len - ret);
/* write out this segment's payload */
nr = do_write_log_from_user(log, iov->iov_base, len);
if (unlikely(nr < 0)) {
log->w_off = orig;
mutex_unlock(&log->mutex);
return nr;
}
iov++;
ret += nr;
}
mutex_unlock(&log->mutex);
/* wake up any blocked readers */
wake_up_interruptible(&log->wq);
return ret;
}

输入的参数iocb表示io上下文,iov表示要写入的内容,长度为nr_segs,表示有nr_segs个段的内容要写入。我们知道,每个要写入的日志的结构形式为:

struct logger_entry | priority | tag | msg

其中, priority、tag和msg这三个段的内容是由iov参数从用户空间传递下来的,分别对应iov里面的三个元素。而logger_entry是由内核空间来构造的:

struct logger_entry header;
struct timespec now;

now = current_kernel_time();

header.pid = current->tgid;
header.tid = current->pid;
header.sec = now.tv_sec;
header.nsec = now.tv_nsec;
header.len = min_t(size_t, iocb->ki_left, LOGGER_ENTRY_MAX_PAYLOAD);

然后调用do_write_log首先把logger_entry结构体写入到日志缓冲区中:

[cpp] view plaincopyprint?
  1. /*
  2. * do_write_log - writes 'len' bytes from 'buf' to 'log'
  3. *
  4. * The caller needs to hold log->mutex.
  5. */
  6. static void do_write_log(struct logger_log *log, const void *buf, size_t count)
  7. {
  8. size_t len;
  9. len = min(count, log->size - log->w_off);
  10. memcpy(log->buffer + log->w_off, buf, len);
  11. if (count != len)
  12. memcpy(log->buffer, buf + len, count - len);
  13. log->w_off = logger_offset(log->w_off + count);
  14. }
/*
* do_write_log - writes 'len' bytes from 'buf' to 'log'
*
* The caller needs to hold log->mutex.
*/
static void do_write_log(struct logger_log *log, const void *buf, size_t count)
{
size_t len;
len = min(count, log->size - log->w_off);
memcpy(log->buffer + log->w_off, buf, len);
if (count != len)
memcpy(log->buffer, buf + len, count - len);
log->w_off = logger_offset(log->w_off + count);
}

由于logger_entry是内核堆栈空间分配的,直接用memcpy拷贝就可以了。

接着,通过一个while循环把iov的内容写入到日志缓冲区中,也就是日志的优先级别priority、日志Tag和日志主体Msg:

[cpp] view plaincopyprint?
  1. while (nr_segs-- > 0) {
  2. size_t len;
  3. ssize_t nr;
  4. /* figure out how much of this vector we can keep */
  5. len = min_t(size_t, iov->iov_len, header.len - ret);
  6. /* write out this segment's payload */
  7. nr = do_write_log_from_user(log, iov->iov_base, len);
  8. if (unlikely(nr < 0)) {
  9. log->w_off = orig;
  10. mutex_unlock(&log->mutex);
  11. return nr;
  12. }
  13. iov++;
  14. ret += nr;
  15. }
while (nr_segs-- > 0) {
size_t len;
ssize_t nr;
/* figure out how much of this vector we can keep */
len = min_t(size_t, iov->iov_len, header.len - ret);
/* write out this segment's payload */
nr = do_write_log_from_user(log, iov->iov_base, len);
if (unlikely(nr < 0)) {
log->w_off = orig;
mutex_unlock(&log->mutex);
return nr;
}
iov++;
ret += nr;
}

由于iov的内容是由用户空间传下来的,需要调用do_write_log_from_user来写入:

[cpp] view plaincopyprint?
  1. static ssize_t do_write_log_from_user(struct logger_log *log,
  2. const void __user *buf, size_t count)
  3. {
  4. size_t len;
  5. len = min(count, log->size - log->w_off);
  6. if (len && copy_from_user(log->buffer + log->w_off, buf, len))
  7. return -EFAULT;
  8. if (count != len)
  9. if (copy_from_user(log->buffer, buf + len, count - len))
  10. return -EFAULT;
  11. log->w_off = logger_offset(log->w_off + count);
  12. return count;
  13. }
static ssize_t do_write_log_from_user(struct logger_log *log,
const void __user *buf, size_t count)
{
size_t len;
len = min(count, log->size - log->w_off);
if (len && copy_from_user(log->buffer + log->w_off, buf, len))
return -EFAULT;
if (count != len)
if (copy_from_user(log->buffer, buf + len, count - len))
return -EFAULT;
log->w_off = logger_offset(log->w_off + count);
return count;
}

这里,我们还漏了一个重要的步骤:

[cpp] view plaincopyprint?
  1. /*
  2. * Fix up any readers, pulling them forward to the first readable
  3. * entry after (what will be) the new write offset. We do this now
  4. * because if we partially fail, we can end up with clobbered log
  5. * entries that encroach on readable buffer.
  6. */
  7. fix_up_readers(log, sizeof(struct logger_entry) + header.len);
 /*
* Fix up any readers, pulling them forward to the first readable
* entry after (what will be) the new write offset. We do this now
* because if we partially fail, we can end up with clobbered log
* entries that encroach on readable buffer.
*/
fix_up_readers(log, sizeof(struct logger_entry) + header.len);

为什么要调用fix_up_reader这个函数呢?这个函数又是作什么用的呢?是这样的,由于日志缓冲区是循环使用的,即旧的日志记录如果没有及时读取,而缓冲区的内容又已经用完时,就需要覆盖旧的记录来容纳新的记录。而这部分将要被覆盖的内容,有可能是某些reader的下一次要读取的日志所在的位置,以及为新的reader准备的日志开始读取位置head所在的位置。因此,需要调整这些位置,使它们能够指向一个新的有效的位置。我们来看一下fix_up_reader函数的实现:

[cpp] view plaincopyprint?
  1. /*
  2. * fix_up_readers - walk the list of all readers and "fix up" any who were
  3. * lapped by the writer; also do the same for the default "start head".
  4. * We do this by "pulling forward" the readers and start head to the first
  5. * entry after the new write head.
  6. *
  7. * The caller needs to hold log->mutex.
  8. */
  9. static void fix_up_readers(struct logger_log *log, size_t len)
  10. {
  11. size_t old = log->w_off;
  12. size_t new = logger_offset(old + len);
  13. struct logger_reader *reader;
  14. if (clock_interval(old, new, log->head))
  15. log->head = get_next_entry(log, log->head, len);
  16. list_for_each_entry(reader, &log->readers, list)
  17. if (clock_interval(old, new, reader->r_off))
  18. reader->r_off = get_next_entry(log, reader->r_off, len);
  19. }
/*
* fix_up_readers - walk the list of all readers and "fix up" any who were
* lapped by the writer; also do the same for the default "start head".
* We do this by "pulling forward" the readers and start head to the first
* entry after the new write head.
*
* The caller needs to hold log->mutex.
*/
static void fix_up_readers(struct logger_log *log, size_t len)
{
size_t old = log->w_off;
size_t new = logger_offset(old + len);
struct logger_reader *reader;
if (clock_interval(old, new, log->head))
log->head = get_next_entry(log, log->head, len);
list_for_each_entry(reader, &log->readers, list)
if (clock_interval(old, new, reader->r_off))
reader->r_off = get_next_entry(log, reader->r_off, len);
}

判断log->head和所有读者reader的当前读偏移reader->r_off是否在被覆盖的区域内,如果是,就需要调用get_next_entry来取得下一个有效的记录的起始位置来调整当前位置:

[cpp] view plaincopyprint?
  1. /*
  2. * get_next_entry - return the offset of the first valid entry at least 'len'
  3. * bytes after 'off'.
  4. *
  5. * Caller must hold log->mutex.
  6. */
  7. static size_t get_next_entry(struct logger_log *log, size_t off, size_t len)
  8. {
  9. size_t count = 0;
  10. do {
  11. size_t nr = get_entry_len(log, off);
  12. off = logger_offset(off + nr);
  13. count += nr;
  14. } while (count < len);
  15. return off;
  16. }
/*
* get_next_entry - return the offset of the first valid entry at least 'len'
* bytes after 'off'.
*
* Caller must hold log->mutex.
*/
static size_t get_next_entry(struct logger_log *log, size_t off, size_t len)
{
size_t count = 0;
do {
size_t nr = get_entry_len(log, off);
off = logger_offset(off + nr);
count += nr;
} while (count < len);
return off;
}

而判断log->head和所有读者reader的当前读偏移reader->r_off是否在被覆盖的区域内,是通过clock_interval函数来实现的:

[cpp] view plaincopyprint?
  1. /*
  2. * clock_interval - is a < c < b in mod-space? Put another way, does the line
  3. * from a to b cross c?
  4. */
  5. static inline int clock_interval(size_t a, size_t b, size_t c)
  6. {
  7. if (b < a) {
  8. if (a < c || b >= c)
  9. return 1;
  10. } else {
  11. if (a < c && b >= c)
  12. return 1;
  13. }
  14. return 0;
  15. }
/*
* clock_interval - is a < c < b in mod-space? Put another way, does the line
* from a to b cross c?
*/
static inline int clock_interval(size_t a, size_t b, size_t c)
{
if (b < a) {
if (a < c || b >= c)
return 1;
} else {
if (a < c && b >= c)
return 1;
}
return 0;
}

最后,日志写入完毕,还需要唤醒正在等待新日志的reader进程:

/* wake up any blocked readers */
wake_up_interruptible(&log->wq);

至此, Logger驱动程序的主要逻辑就分析完成了,还有其它的一些接口,如logger_poll、 logger_ioctl和logger_release函数,比较简单,读取可以自行分析。这里还需要提到的一点是,由于Logger驱动程序模块在退出系统时,是不会卸载的,所以这个模块没有module_exit函数,而对于模块里面定义的对象,也没有用对引用计数技术。

这篇文章着重介绍了Android日志系统在内核空间的实现,在下一篇文章中,我们将接着介绍在用户空间中,提供给Android应用程序使用的Java和C/C++ LOG调用接口的实现过程,敬请关注

Android应用程序框架层和系统运行库层日志系统源代码分析

在开发Android应用程序时,少不了使用Log来监控和调试程序的执行。在上一篇文章Android日志系统驱动程序Logger源代码分析中,我们分析了驱动程序Logger的源代码,在前面的文章浅谈Android系统开发中Log的使用一文,我们也简单介绍在应用程序中使Log的方法,在这篇文章中,我们将详细介绍Android应用程序框架层和系统运行库存层日志系统的源代码,使得我们可以更好地理解Android的日志系统的实现。

我们在Android应用程序,一般是调用应用程序框架层的Java接口(android.util.Log)来使用日志系统,这个Java接口通过JNI方法和系统运行库最终调用内核驱动程序Logger把Log写到内核空间中。按照这个调用过程,我们一步步介绍Android应用程序框架层日志系统的源代码。学习完这个过程之后,我们可以很好地理解Android系统的架构,即应用程序层(Application)的接口是如何一步一步地调用到内核空间的。

一. 应用程序框架层日志系统Java接口的实现。

在浅谈Android系统开发中Log的使用一文中,我们曾经介绍过Android应用程序框架层日志系统的源代码接口。这里,为了描述方便和文章的完整性,我们重新贴一下这部份的代码,在frameworks/base/core/java/android/util/Log.java文件中,实现日志系统的Java接口:

[java] view plaincopyprint?
  1. ................................................
  2. public final class Log {
  3. ................................................
  4. /**
  5. * Priority constant for the println method; use Log.v.
  6. */
  7. public static final int VERBOSE = 2;
  8. /**
  9. * Priority constant for the println method; use Log.d.
  10. */
  11. public static final int DEBUG = 3;
  12. /**
  13. * Priority constant for the println method; use Log.i.
  14. */
  15. public static final int INFO = 4;
  16. /**
  17. * Priority constant for the println method; use Log.w.
  18. */
  19. public static final int WARN = 5;
  20. /**
  21. * Priority constant for the println method; use Log.e.
  22. */
  23. public static final int ERROR = 6;
  24. /**
  25. * Priority constant for the println method.
  26. */
  27. public static final int ASSERT = 7;
  28. .....................................................
  29. public static int v(String tag, String msg) {
  30. return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
  31. }
  32. public static int v(String tag, String msg, Throwable tr) {
  33. return println_native(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
  34. }
  35. public static int d(String tag, String msg) {
  36. return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
  37. }
  38. public static int d(String tag, String msg, Throwable tr) {
  39. return println_native(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr));
  40. }
  41. public static int i(String tag, String msg) {
  42. return println_native(LOG_ID_MAIN, INFO, tag, msg);
  43. }
  44. public static int i(String tag, String msg, Throwable tr) {
  45. return println_native(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr));
  46. }
  47. public static int w(String tag, String msg) {
  48. return println_native(LOG_ID_MAIN, WARN, tag, msg);
  49. }
  50. public static int w(String tag, String msg, Throwable tr) {
  51. return println_native(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr));
  52. }
  53. public static int w(String tag, Throwable tr) {
  54. return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
  55. }
  56. public static int e(String tag, String msg) {
  57. return println_native(LOG_ID_MAIN, ERROR, tag, msg);
  58. }
  59. public static int e(String tag, String msg, Throwable tr) {
  60. return println_native(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr));
  61. }
  62. ..................................................................
  63. /** @hide */ public static native int LOG_ID_MAIN = 0;
  64. /** @hide */ public static native int LOG_ID_RADIO = 1;
  65. /** @hide */ public static native int LOG_ID_EVENTS = 2;
  66. /** @hide */ public static native int LOG_ID_SYSTEM = 3;
  67. /** @hide */ public static native int println_native(int bufID,
  68. int priority, String tag, String msg);
  69. }
................................................
public final class Log {
................................................
/**
* Priority constant for the println method; use Log.v.
*/
public static final int VERBOSE = 2;
/**
* Priority constant for the println method; use Log.d.
*/
public static final int DEBUG = 3;
/**
* Priority constant for the println method; use Log.i.
*/
public static final int INFO = 4;
/**
* Priority constant for the println method; use Log.w.
*/
public static final int WARN = 5;
/**
* Priority constant for the println method; use Log.e.
*/
public static final int ERROR = 6;
/**
* Priority constant for the println method.
*/
public static final int ASSERT = 7;
.....................................................
public static int v(String tag, String msg) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
}
public static int v(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
}
public static int d(String tag, String msg) {
return println_native(LOG_ID_MAIN, DEBUG, tag, msg);
}
public static int d(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr));
}
public static int i(String tag, String msg) {
return println_native(LOG_ID_MAIN, INFO, tag, msg);
}
public static int i(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr));
}
public static int w(String tag, String msg) {
return println_native(LOG_ID_MAIN, WARN, tag, msg);
}
public static int w(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr));
}
public static int w(String tag, Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
}
public static int e(String tag, String msg) {
return println_native(LOG_ID_MAIN, ERROR, tag, msg);
}
public static int e(String tag, String msg, Throwable tr) {
return println_native(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr));
}
..................................................................
/** @hide */ public static native int LOG_ID_MAIN = 0;
/** @hide */ public static native int LOG_ID_RADIO = 1;
/** @hide */ public static native int LOG_ID_EVENTS = 2;
/** @hide */ public static native int LOG_ID_SYSTEM = 3;
/** @hide */ public static native int println_native(int bufID,
int priority, String tag, String msg);
}

定义了2~7一共6个日志优先级别ID和4个日志缓冲区ID。回忆一下Android日志系统驱动程序Logger源代码分析一文,在Logger驱动程序模块中,定义了log_main、log_events和log_radio三个日志缓冲区,分别对应三个设备文件/dev/log/main、/dev/log/events和/dev/log/radio。这里的4个日志缓冲区的前面3个ID就是对应这三个设备文件的文件描述符了,在下面的章节中,我们将看到这三个文件描述符是如何创建的。在下载下来的Android内核源代码中,第4个日志缓冲区LOG_ID_SYSTEM并没有对应的设备文件,在这种情况下,它和LOG_ID_MAIN对应同一个缓冲区ID,在下面的章节中,我们同样可以看到这两个ID是如何对应到同一个设备文件的。

在整个Log接口中,最关键的地方声明了println_native本地方法,所有的Log接口都是通过调用这个本地方法来实现Log的定入。下面我们就继续分析这个本地方法println_native。

二. 应用程序框架层日志系统JNI方法的实现。

在frameworks/base/core/jni/android_util_Log.cpp文件中,实现JNI方法println_native:

[cpp] view plaincopyprint?
  1. /* //device/libs/android_runtime/android_util_Log.cpp
  2. **
  3. ** Copyright 2006, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. **     http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #define LOG_NAMESPACE "log.tag."
  18. #define LOG_TAG "Log_println"
  19. #include <assert.h>
  20. #include <cutils/properties.h>
  21. #include <utils/Log.h>
  22. #include <utils/String8.h>
  23. #include "jni.h"
  24. #include "utils/misc.h"
  25. #include "android_runtime/AndroidRuntime.h"
  26. #define MIN(a,b) ((a<b)?a:b)
  27. namespace android {
  28. struct levels_t {
  29. jint verbose;
  30. jint debug;
  31. jint info;
  32. jint warn;
  33. jint error;
  34. jint assert;
  35. };
  36. static levels_t levels;
  37. static int toLevel(const char* value)
  38. {
  39. switch (value[0]) {
  40. case 'V': return levels.verbose;
  41. case 'D': return levels.debug;
  42. case 'I': return levels.info;
  43. case 'W': return levels.warn;
  44. case 'E': return levels.error;
  45. case 'A': return levels.assert;
  46. case 'S': return -1; // SUPPRESS
  47. }
  48. return levels.info;
  49. }
  50. static jboolean android_util_Log_isLoggable(JNIEnv* env, jobject clazz, jstring tag, jint level)
  51. {
  52. #ifndef HAVE_ANDROID_OS
  53. return false;
  54. #else /* HAVE_ANDROID_OS */
  55. int len;
  56. char key[PROPERTY_KEY_MAX];
  57. char buf[PROPERTY_VALUE_MAX];
  58. if (tag == NULL) {
  59. return false;
  60. }
  61. jboolean result = false;
  62. const char* chars = env->GetStringUTFChars(tag, NULL);
  63. if ((strlen(chars)+sizeof(LOG_NAMESPACE)) > PROPERTY_KEY_MAX) {
  64. jclass clazz = env->FindClass("java/lang/IllegalArgumentException");
  65. char buf2[200];
  66. snprintf(buf2, sizeof(buf2), "Log tag \"%s\" exceeds limit of %d characters\n",
  67. chars, PROPERTY_KEY_MAX - sizeof(LOG_NAMESPACE));
  68. // release the chars!
  69. env->ReleaseStringUTFChars(tag, chars);
  70. env->ThrowNew(clazz, buf2);
  71. return false;
  72. } else {
  73. strncpy(key, LOG_NAMESPACE, sizeof(LOG_NAMESPACE)-1);
  74. strcpy(key + sizeof(LOG_NAMESPACE) - 1, chars);
  75. }
  76. env->ReleaseStringUTFChars(tag, chars);
  77. len = property_get(key, buf, "");
  78. int logLevel = toLevel(buf);
  79. return (logLevel >= 0 && level >= logLevel) ? true : false;
  80. #endif /* HAVE_ANDROID_OS */
  81. }
  82. /*
  83. * In class android.util.Log:
  84. *  public static native int println_native(int buffer, int priority, String tag, String msg)
  85. */
  86. static jint android_util_Log_println_native(JNIEnv* env, jobject clazz,
  87. jint bufID, jint priority, jstring tagObj, jstring msgObj)
  88. {
  89. const char* tag = NULL;
  90. const char* msg = NULL;
  91. if (msgObj == NULL) {
  92. jclass npeClazz;
  93. npeClazz = env->FindClass("java/lang/NullPointerException");
  94. assert(npeClazz != NULL);
  95. env->ThrowNew(npeClazz, "println needs a message");
  96. return -1;
  97. }
  98. if (bufID < 0 || bufID >= LOG_ID_MAX) {
  99. jclass npeClazz;
  100. npeClazz = env->FindClass("java/lang/NullPointerException");
  101. assert(npeClazz != NULL);
  102. env->ThrowNew(npeClazz, "bad bufID");
  103. return -1;
  104. }
  105. if (tagObj != NULL)
  106. tag = env->GetStringUTFChars(tagObj, NULL);
  107. msg = env->GetStringUTFChars(msgObj, NULL);
  108. int res = __android_log_buf_write(bufID, (android_LogPriority)priority, tag, msg);
  109. if (tag != NULL)
  110. env->ReleaseStringUTFChars(tagObj, tag);
  111. env->ReleaseStringUTFChars(msgObj, msg);
  112. return res;
  113. }
  114. /*
  115. * JNI registration.
  116. */
  117. static JNINativeMethod gMethods[] = {
  118. /* name, signature, funcPtr */
  119. { "isLoggable",      "(Ljava/lang/String;I)Z", (void*) android_util_Log_isLoggable },
  120. { "println_native",  "(IILjava/lang/String;Ljava/lang/String;)I", (void*) android_util_Log_println_native },
  121. };
  122. int register_android_util_Log(JNIEnv* env)
  123. {
  124. jclass clazz = env->FindClass("android/util/Log");
  125. if (clazz == NULL) {
  126. LOGE("Can't find android/util/Log");
  127. return -1;
  128. }
  129. levels.verbose = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "VERBOSE", "I"));
  130. levels.debug = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "DEBUG", "I"));
  131. levels.info = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "INFO", "I"));
  132. levels.warn = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "WARN", "I"));
  133. levels.error = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ERROR", "I"));
  134. levels.assert = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ASSERT", "I"));
  135. return AndroidRuntime::registerNativeMethods(env, "android/util/Log", gMethods, NELEM(gMethods));
  136. }
  137. }; // namespace android
/* //device/libs/android_runtime/android_util_Log.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#define LOG_NAMESPACE "log.tag."
#define LOG_TAG "Log_println"
#include <assert.h>
#include <cutils/properties.h>
#include <utils/Log.h>
#include <utils/String8.h>
#include "jni.h"
#include "utils/misc.h"
#include "android_runtime/AndroidRuntime.h"
#define MIN(a,b) ((a<b)?a:b)
namespace android {
struct levels_t {
jint verbose;
jint debug;
jint info;
jint warn;
jint error;
jint assert;
};
static levels_t levels;
static int toLevel(const char* value)
{
switch (value[0]) {
case 'V': return levels.verbose;
case 'D': return levels.debug;
case 'I': return levels.info;
case 'W': return levels.warn;
case 'E': return levels.error;
case 'A': return levels.assert;
case 'S': return -1; // SUPPRESS
}
return levels.info;
}
static jboolean android_util_Log_isLoggable(JNIEnv* env, jobject clazz, jstring tag, jint level)
{
#ifndef HAVE_ANDROID_OS
return false;
#else /* HAVE_ANDROID_OS */
int len;
char key[PROPERTY_KEY_MAX];
char buf[PROPERTY_VALUE_MAX];
if (tag == NULL) {
return false;
}
jboolean result = false;
const char* chars = env->GetStringUTFChars(tag, NULL);
if ((strlen(chars)+sizeof(LOG_NAMESPACE)) > PROPERTY_KEY_MAX) {
jclass clazz = env->FindClass("java/lang/IllegalArgumentException");
char buf2[200];
snprintf(buf2, sizeof(buf2), "Log tag \"%s\" exceeds limit of %d characters\n",
chars, PROPERTY_KEY_MAX - sizeof(LOG_NAMESPACE));
// release the chars!
env->ReleaseStringUTFChars(tag, chars);
env->ThrowNew(clazz, buf2);
return false;
} else {
strncpy(key, LOG_NAMESPACE, sizeof(LOG_NAMESPACE)-1);
strcpy(key + sizeof(LOG_NAMESPACE) - 1, chars);
}
env->ReleaseStringUTFChars(tag, chars);
len = property_get(key, buf, "");
int logLevel = toLevel(buf);
return (logLevel >= 0 && level >= logLevel) ? true : false;
#endif /* HAVE_ANDROID_OS */
}
/*
* In class android.util.Log:
*  public static native int println_native(int buffer, int priority, String tag, String msg)
*/
static jint android_util_Log_println_native(JNIEnv* env, jobject clazz,
jint bufID, jint priority, jstring tagObj, jstring msgObj)
{
const char* tag = NULL;
const char* msg = NULL;
if (msgObj == NULL) {
jclass npeClazz;
npeClazz = env->FindClass("java/lang/NullPointerException");
assert(npeClazz != NULL);
env->ThrowNew(npeClazz, "println needs a message");
return -1;
}
if (bufID < 0 || bufID >= LOG_ID_MAX) {
jclass npeClazz;
npeClazz = env->FindClass("java/lang/NullPointerException");
assert(npeClazz != NULL);
env->ThrowNew(npeClazz, "bad bufID");
return -1;
}
if (tagObj != NULL)
tag = env->GetStringUTFChars(tagObj, NULL);
msg = env->GetStringUTFChars(msgObj, NULL);
int res = __android_log_buf_write(bufID, (android_LogPriority)priority, tag, msg);
if (tag != NULL)
env->ReleaseStringUTFChars(tagObj, tag);
env->ReleaseStringUTFChars(msgObj, msg);
return res;
}
/*
* JNI registration.
*/
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "isLoggable",      "(Ljava/lang/String;I)Z", (void*) android_util_Log_isLoggable },
{ "println_native",  "(IILjava/lang/String;Ljava/lang/String;)I", (void*) android_util_Log_println_native },
};
int register_android_util_Log(JNIEnv* env)
{
jclass clazz = env->FindClass("android/util/Log");
if (clazz == NULL) {
LOGE("Can't find android/util/Log");
return -1;
}
levels.verbose = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "VERBOSE", "I"));
levels.debug = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "DEBUG", "I"));
levels.info = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "INFO", "I"));
levels.warn = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "WARN", "I"));
levels.error = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ERROR", "I"));
levels.assert = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ASSERT", "I"));
return AndroidRuntime::registerNativeMethods(env, "android/util/Log", gMethods, NELEM(gMethods));
}
}; // namespace android

在gMethods变量中,定义了println_native本地方法对应的函数调用是android_util_Log_println_native。在android_util_Log_println_native函数中,通过了各项参数验证正确后,就调用运行时库函数__android_log_buf_write来实现Log的写入操作。__android_log_buf_write函实实现在liblog库中,它有4个参数,分别缓冲区ID、优先级别ID、Tag字符串和Msg字符串。下面运行时库liblog中的__android_log_buf_write的实现。

三. 系统运行库层日志系统的实现。

在系统运行库层liblog库的实现中,内容比较多,这里,我们只关注日志写入操作__android_log_buf_write的相关实现:

[cpp] view plaincopyprint?
  1. int __android_log_buf_write(int bufID, int prio, const char *tag, const char *msg)
  2. {
  3. struct iovec vec[3];
  4. if (!tag)
  5. tag = "";
  6. /* XXX: This needs to go! */
  7. if (!strcmp(tag, "HTC_RIL") ||
  8. !strncmp(tag, "RIL", 3) || /* Any log tag with "RIL" as the prefix */
  9. !strcmp(tag, "AT") ||
  10. !strcmp(tag, "GSM") ||
  11. !strcmp(tag, "STK") ||
  12. !strcmp(tag, "CDMA") ||
  13. !strcmp(tag, "PHONE") ||
  14. !strcmp(tag, "SMS"))
  15. bufID = LOG_ID_RADIO;
  16. vec[0].iov_base   = (unsigned char *) &prio;
  17. vec[0].iov_len    = 1;
  18. vec[1].iov_base   = (void *) tag;
  19. vec[1].iov_len    = strlen(tag) + 1;
  20. vec[2].iov_base   = (void *) msg;
  21. vec[2].iov_len    = strlen(msg) + 1;
  22. return write_to_log(bufID, vec, 3);
  23. }
int __android_log_buf_write(int bufID, int prio, const char *tag, const char *msg)
{
struct iovec vec[3];
if (!tag)
tag = "";
/* XXX: This needs to go! */
if (!strcmp(tag, "HTC_RIL") ||
!strncmp(tag, "RIL", 3) || /* Any log tag with "RIL" as the prefix */
!strcmp(tag, "AT") ||
!strcmp(tag, "GSM") ||
!strcmp(tag, "STK") ||
!strcmp(tag, "CDMA") ||
!strcmp(tag, "PHONE") ||
!strcmp(tag, "SMS"))
bufID = LOG_ID_RADIO;
vec[0].iov_base   = (unsigned char *) &prio;
vec[0].iov_len    = 1;
vec[1].iov_base   = (void *) tag;
vec[1].iov_len    = strlen(tag) + 1;
vec[2].iov_base   = (void *) msg;
vec[2].iov_len    = strlen(msg) + 1;
return write_to_log(bufID, vec, 3);
}

函数首先是检查传进来的tag参数是否是为HTC_RIL、RIL、AT、GSM、STK、CDMA、PHONE和SMS中的一个,如果是,就无条件地使用ID为LOG_ID_RADIO的日志缓冲区作为写入缓冲区,接着,把传进来的参数prio、tag和msg分别存放在一个向量数组中,调用write_to_log函数来进入下一步操作。write_to_log是一个函数指针,定义在文件开始的位置上:

[cpp] view plaincopyprint?
  1. static int __write_to_log_init(log_id_t, struct iovec *vec, size_t nr);
  2. static int (*write_to_log)(log_id_t, struct iovec *vec, size_t nr) = __write_to_log_init;
static int __write_to_log_init(log_id_t, struct iovec *vec, size_t nr);
static int (*write_to_log)(log_id_t, struct iovec *vec, size_t nr) = __write_to_log_init;

并且初始化为__write_to_log_init函数:

[cpp] view plaincopyprint?
  1. static int __write_to_log_init(log_id_t log_id, struct iovec *vec, size_t nr)
  2. {
  3. #ifdef HAVE_PTHREADS
  4. pthread_mutex_lock(&log_init_lock);
  5. #endif
  6. if (write_to_log == __write_to_log_init) {
  7. log_fds[LOG_ID_MAIN] = log_open("/dev/"LOGGER_LOG_MAIN, O_WRONLY);
  8. log_fds[LOG_ID_RADIO] = log_open("/dev/"LOGGER_LOG_RADIO, O_WRONLY);
  9. log_fds[LOG_ID_EVENTS] = log_open("/dev/"LOGGER_LOG_EVENTS, O_WRONLY);
  10. log_fds[LOG_ID_SYSTEM] = log_open("/dev/"LOGGER_LOG_SYSTEM, O_WRONLY);
  11. write_to_log = __write_to_log_kernel;
  12. if (log_fds[LOG_ID_MAIN] < 0 || log_fds[LOG_ID_RADIO] < 0 ||
  13. log_fds[LOG_ID_EVENTS] < 0) {
  14. log_close(log_fds[LOG_ID_MAIN]);
  15. log_close(log_fds[LOG_ID_RADIO]);
  16. log_close(log_fds[LOG_ID_EVENTS]);
  17. log_fds[LOG_ID_MAIN] = -1;
  18. log_fds[LOG_ID_RADIO] = -1;
  19. log_fds[LOG_ID_EVENTS] = -1;
  20. write_to_log = __write_to_log_null;
  21. }
  22. if (log_fds[LOG_ID_SYSTEM] < 0) {
  23. log_fds[LOG_ID_SYSTEM] = log_fds[LOG_ID_MAIN];
  24. }
  25. }
  26. #ifdef HAVE_PTHREADS
  27. pthread_mutex_unlock(&log_init_lock);
  28. #endif
  29. return write_to_log(log_id, vec, nr);
  30. }
static int __write_to_log_init(log_id_t log_id, struct iovec *vec, size_t nr)
{
#ifdef HAVE_PTHREADS
pthread_mutex_lock(&log_init_lock);
#endif
if (write_to_log == __write_to_log_init) {
log_fds[LOG_ID_MAIN] = log_open("/dev/"LOGGER_LOG_MAIN, O_WRONLY);
log_fds[LOG_ID_RADIO] = log_open("/dev/"LOGGER_LOG_RADIO, O_WRONLY);
log_fds[LOG_ID_EVENTS] = log_open("/dev/"LOGGER_LOG_EVENTS, O_WRONLY);
log_fds[LOG_ID_SYSTEM] = log_open("/dev/"LOGGER_LOG_SYSTEM, O_WRONLY);
write_to_log = __write_to_log_kernel;
if (log_fds[LOG_ID_MAIN] < 0 || log_fds[LOG_ID_RADIO] < 0 ||
log_fds[LOG_ID_EVENTS] < 0) {
log_close(log_fds[LOG_ID_MAIN]);
log_close(log_fds[LOG_ID_RADIO]);
log_close(log_fds[LOG_ID_EVENTS]);
log_fds[LOG_ID_MAIN] = -1;
log_fds[LOG_ID_RADIO] = -1;
log_fds[LOG_ID_EVENTS] = -1;
write_to_log = __write_to_log_null;
}
if (log_fds[LOG_ID_SYSTEM] < 0) {
log_fds[LOG_ID_SYSTEM] = log_fds[LOG_ID_MAIN];
}
}
#ifdef HAVE_PTHREADS
pthread_mutex_unlock(&log_init_lock);
#endif
return write_to_log(log_id, vec, nr);
}

这里我们可以看到,如果是第一次调write_to_log函数,write_to_log == __write_to_log_init判断语句就会true,于是执行log_open函数打开设备文件,并把文件描述符保存在log_fds数组中。如果打开/dev/LOGGER_LOG_SYSTEM文件失败,即log_fds[LOG_ID_SYSTEM] < 0,就把log_fds[LOG_ID_SYSTEM]设置为log_fds[LOG_ID_MAIN],这就是我们上面描述的如果不存在ID为LOG_ID_SYSTEM的日志缓冲区,就把LOG_ID_SYSTEM设置为和LOG_ID_MAIN对应的日志缓冲区了。LOGGER_LOG_MAIN、LOGGER_LOG_RADIO、LOGGER_LOG_EVENTS和LOGGER_LOG_SYSTEM四个宏定义在system/core/include/cutils/logger.h文件中:

[cpp] view plaincopyprint?
  1. #define LOGGER_LOG_MAIN     "log/main"
  2. #define LOGGER_LOG_RADIO    "log/radio"
  3. #define LOGGER_LOG_EVENTS   "log/events"
  4. #define LOGGER_LOG_SYSTEM   "log/system"
#define LOGGER_LOG_MAIN      "log/main"
#define LOGGER_LOG_RADIO    "log/radio"
#define LOGGER_LOG_EVENTS   "log/events"
#define LOGGER_LOG_SYSTEM   "log/system"

接着,把write_to_log函数指针指向__write_to_log_kernel函数:

[cpp] view plaincopyprint?
  1. static int __write_to_log_kernel(log_id_t log_id, struct iovec *vec, size_t nr)
  2. {
  3. ssize_t ret;
  4. int log_fd;
  5. if (/*(int)log_id >= 0 &&*/ (int)log_id < (int)LOG_ID_MAX) {
  6. log_fd = log_fds[(int)log_id];
  7. } else {
  8. return EBADF;
  9. }
  10. do {
  11. ret = log_writev(log_fd, vec, nr);
  12. } while (ret < 0 && errno == EINTR);
  13. return ret;
  14. }
static int __write_to_log_kernel(log_id_t log_id, struct iovec *vec, size_t nr)
{
ssize_t ret;
int log_fd;
if (/*(int)log_id >= 0 &&*/ (int)log_id < (int)LOG_ID_MAX) {
log_fd = log_fds[(int)log_id];
} else {
return EBADF;
}
do {
ret = log_writev(log_fd, vec, nr);
} while (ret < 0 && errno == EINTR);
return ret;
}

函数调用log_writev来实现Log的写入,注意,这里通过一个循环来写入Log,直到写入成功为止。这里log_writev是一个宏,在文件开始的地方定义为:

[cpp] view plaincopyprint?
  1. #if FAKE_LOG_DEVICE
  2. // This will be defined when building for the host.
  3. #define log_open(pathname, flags) fakeLogOpen(pathname, flags)
  4. #define log_writev(filedes, vector, count) fakeLogWritev(filedes, vector, count)
  5. #define log_close(filedes) fakeLogClose(filedes)
  6. #else
  7. #define log_open(pathname, flags) open(pathname, flags)
  8. #define log_writev(filedes, vector, count) writev(filedes, vector, count)
  9. #define log_close(filedes) close(filedes)
  10. #endif
#if FAKE_LOG_DEVICE
// This will be defined when building for the host.
#define log_open(pathname, flags) fakeLogOpen(pathname, flags)
#define log_writev(filedes, vector, count) fakeLogWritev(filedes, vector, count)
#define log_close(filedes) fakeLogClose(filedes)
#else
#define log_open(pathname, flags) open(pathname, flags)
#define log_writev(filedes, vector, count) writev(filedes, vector, count)
#define log_close(filedes) close(filedes)
#endif

这里,我们看到,一般情况下,log_writev就是writev了,这是个常见的批量文件写入函数,就不多说了。

至些,整个调用过程就结束了。总结一下,首先是从应用程序层调用应用程序框架层的Java接口,应用程序框架层的Java接口通过调用本层的JNI方法进入到系统运行库层的C接口,系统运行库层的C接口通过设备文件来访问内核空间层的Logger驱动程序。这是一个典型的调用过程,很好地诠释Android的系统架构,希望读者好好领会

Android日志系统Logcat源代码简要分析

在前面两篇文章Android日志系统驱动程序Logger源代码分析和Android应用程序框架层和系统运行库层日志系统源代码中,介绍了Android内核空间层、系统运行库层和应用程序框架层日志系统相关的源代码,其中,后一篇文章着重介绍了日志的写入操作。为了描述完整性,这篇文章着重介绍日志的读取操作,这就是我们在开发Android应用程序时,经常要用到日志查看工具Logcat了。

Logcat工具内置在Android系统中,可以在主机上通过adb logcat命令来查看模拟机上日志信息。Logcat工具的用法很丰富,因此,源代码也比较多,本文并不打算完整地介绍整个Logcat工具的源代码,主要是介绍Logcat读取日志的主线,即从打开日志设备文件到读取日志设备文件的日志记录到输出日志记录的主要过程,希望能起到一个抛砖引玉的作用。

Logcat工具源代码位于system/core/logcat目录下,只有一个源代码文件logcat.cpp,编译后生成的可执行文件位于out/target/product/generic/system/bin目录下,在模拟机中,可以在/system/bin目录下看到logcat工具。下面我们就分段来阅读logcat.cpp源代码文件。

一.  Logcat工具的相关数据结构。

这些数据结构是用来保存从日志设备文件读出来的日志记录:

[cpp] view plaincopyprint?
  1. struct queued_entry_t {
  2. union {
  3. unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
  4. struct logger_entry entry __attribute__((aligned(4)));
  5. };
  6. queued_entry_t* next;
  7. queued_entry_t() {
  8. next = NULL;
  9. }
  10. };
  11. struct log_device_t {
  12. char* device;
  13. bool binary;
  14. int fd;
  15. bool printed;
  16. char label;
  17. queued_entry_t* queue;
  18. log_device_t* next;
  19. log_device_t(char* d, bool b, char l) {
  20. device = d;
  21. binary = b;
  22. label = l;
  23. queue = NULL;
  24. next = NULL;
  25. printed = false;
  26. }
  27. void enqueue(queued_entry_t* entry) {
  28. if (this->queue == NULL) {
  29. this->queue = entry;
  30. } else {
  31. queued_entry_t** e = &this->queue;
  32. while (*e && cmp(entry, *e) >= 0) {
  33. e = &((*e)->next);
  34. }
  35. entry->next = *e;
  36. *e = entry;
  37. }
  38. }
  39. };
struct queued_entry_t {
union {
unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
struct logger_entry entry __attribute__((aligned(4)));
};
queued_entry_t* next;
queued_entry_t() {
next = NULL;
}
};
struct log_device_t {
char* device;
bool binary;
int fd;
bool printed;
char label;
queued_entry_t* queue;
log_device_t* next;
log_device_t(char* d, bool b, char l) {
device = d;
binary = b;
label = l;
queue = NULL;
next = NULL;
printed = false;
}
void enqueue(queued_entry_t* entry) {
if (this->queue == NULL) {
this->queue = entry;
} else {
queued_entry_t** e = &this->queue;
while (*e && cmp(entry, *e) >= 0) {
e = &((*e)->next);
}
entry->next = *e;
*e = entry;
}
}
};

其中,宏LOGGER_ENTRY_MAX_LEN和struct logger_entry定义在system/core/include/cutils/logger.h文件中,在Android应用程序框架层和系统运行库层日志系统源代码分析一文有提到,为了方便描述,这里列出这个宏和结构体的定义:

[cpp] view plaincopyprint?
  1. struct logger_entry {
  2. __u16       len;    /* length of the payload */
  3. __u16       __pad;  /* no matter what, we get 2 bytes of padding */
  4. __s32       pid;    /* generating process's pid */
  5. __s32       tid;    /* generating process's tid */
  6. __s32       sec;    /* seconds since Epoch */
  7. __s32       nsec;   /* nanoseconds */
  8. char        msg[0]; /* the entry's payload */
  9. };
  10. #define LOGGER_ENTRY_MAX_LEN        (4*1024)
struct logger_entry {
__u16       len;    /* length of the payload */
__u16       __pad;  /* no matter what, we get 2 bytes of padding */
__s32       pid;    /* generating process's pid */
__s32       tid;    /* generating process's tid */
__s32       sec;    /* seconds since Epoch */
__s32       nsec;   /* nanoseconds */
char        msg[0]; /* the entry's payload */
};
#define LOGGER_ENTRY_MAX_LEN        (4*1024)

从结构体struct queued_entry_t和struct log_device_t的定义可以看出,每一个log_device_t都包含有一个queued_entry_t队列,queued_entry_t就是对应从日志设备文件读取出来的一条日志记录了,而log_device_t则是对应一个日志设备文件上下文。在Android日志系统驱动程序Logger源代码分析一文中,我们曾提到,Android日志系统有三个日志设备文件,分别是/dev/log/main、/dev/log/events和/dev/log/radio。

每个日志设备上下文通过其next成员指针连接起来,每个设备文件上下文的日志记录也是通过next指针连接起来。日志记录队例是按时间戳从小到大排列的,这个log_device_t::enqueue函数可以看出,当要插入一条日志记录的时候,先队列头开始查找,直到找到一个时间戳比当前要插入的日志记录的时间戳大的日志记录的位置,然后插入当前日志记录。比较函数cmp的定义如下:

[cpp] view plaincopyprint?
  1. static int cmp(queued_entry_t* a, queued_entry_t* b) {
  2. int n = a->entry.sec - b->entry.sec;
  3. if (n != 0) {
  4. return n;
  5. }
  6. return a->entry.nsec - b->entry.nsec;
  7. }
static int cmp(queued_entry_t* a, queued_entry_t* b) {
int n = a->entry.sec - b->entry.sec;
if (n != 0) {
return n;
}
return a->entry.nsec - b->entry.nsec;
}

为什么日志记录要按照时间戳从小到大排序呢?原来,Logcat在使用时,可以指定一个参数-t <count>,可以指定只显示最新count条记录,超过count的记录将被丢弃,在这里的实现中,就是要把排在队列前面的多余日记记录丢弃了,因为排在前面的日志记录是最旧的,默认是显示所有的日志记录。在下面的代码中,我们还会继续分析这个过程。
        二. 打开日志设备文件。

Logcat工具的入口函数main,打开日志设备文件和一些初始化的工作也是在这里进行。main函数的内容也比较多,前面的逻辑都是解析命令行参数。这里假设我们使用logcat工具时,不带任何参数。这不会影响我们分析logcat读取日志的主线,有兴趣的读取可以自行分析解析命令行参数的逻辑。

分析完命令行参数以后,就开始要创建日志设备文件上下文结构体struct log_device_t了:

[cpp] view plaincopyprint?
  1. if (!devices) {
  2. devices = new log_device_t(strdup("/dev/"LOGGER_LOG_MAIN), false, 'm');
  3. android::g_devCount = 1;
  4. int accessmode =
  5. (mode & O_RDONLY) ? R_OK : 0
  6. | (mode & O_WRONLY) ? W_OK : 0;
  7. // only add this if it's available
  8. if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
  9. devices->next = new log_device_t(strdup("/dev/"LOGGER_LOG_SYSTEM), false, 's');
  10. android::g_devCount++;
  11. }
  12. }
    if (!devices) {
devices = new log_device_t(strdup("/dev/"LOGGER_LOG_MAIN), false, 'm');
android::g_devCount = 1;
int accessmode =
(mode & O_RDONLY) ? R_OK : 0
| (mode & O_WRONLY) ? W_OK : 0;
// only add this if it's available
if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
devices->next = new log_device_t(strdup("/dev/"LOGGER_LOG_SYSTEM), false, 's');
android::g_devCount++;
}
}

由于我们假设使用logcat时,不带任何命令行参数,这里的devices变量为NULL,因此,就会默认创建/dev/log/main设备上下文结构体,如果存在/dev/log/system设备文件,也会一并创建。宏LOGGER_LOG_MAIN和LOGGER_LOG_SYSTEM也是定义在system/core/include/cutils/logger.h文件中:

[cpp] view plaincopyprint?
  1. #define LOGGER_LOG_MAIN     "log/main"
  2. #define LOGGER_LOG_SYSTEM   "log/system"
#define LOGGER_LOG_MAIN      "log/main"
#define LOGGER_LOG_SYSTEM   "log/system"

我们在Android日志系统驱动程序Logger源代码分析一文中看到,在Android日志系统驱动程序Logger中,默认是不创建/dev/log/system设备文件的。

往下看,调用setupOutput()函数来初始化输出文件:

[cpp] view plaincopyprint?
  1. android::setupOutput();
    android::setupOutput();

setupOutput()函数定义如下:

[cpp] view plaincopyprint?
  1. static void setupOutput()
  2. {
  3. if (g_outputFileName == NULL) {
  4. g_outFD = STDOUT_FILENO;
  5. } else {
  6. struct stat statbuf;
  7. g_outFD = openLogFile (g_outputFileName);
  8. if (g_outFD < 0) {
  9. perror ("couldn't open output file");
  10. exit(-1);
  11. }
  12. fstat(g_outFD, &statbuf);
  13. g_outByteCount = statbuf.st_size;
  14. }
  15. }
static void setupOutput()
{
if (g_outputFileName == NULL) {
g_outFD = STDOUT_FILENO;
} else {
struct stat statbuf;
g_outFD = openLogFile (g_outputFileName);
if (g_outFD < 0) {
perror ("couldn't open output file");
exit(-1);
}
fstat(g_outFD, &statbuf);
g_outByteCount = statbuf.st_size;
}
}

如果我们在执行logcat命令时,指定了-f  <filename>选项,日志内容就输出到filename文件中,否则,就输出到标准输出控制台去了。

再接下来,就是打开日志设备文件了:

[cpp] view plaincopyprint?
  1. dev = devices;
  2. while (dev) {
  3. dev->fd = open(dev->device, mode);
  4. if (dev->fd < 0) {
  5. fprintf(stderr, "Unable to open log device '%s': %s\n",
  6. dev->device, strerror(errno));
  7. exit(EXIT_FAILURE);
  8. }
  9. if (clearLog) {
  10. int ret;
  11. ret = android::clearLog(dev->fd);
  12. if (ret) {
  13. perror("ioctl");
  14. exit(EXIT_FAILURE);
  15. }
  16. }
  17. if (getLogSize) {
  18. int size, readable;
  19. size = android::getLogSize(dev->fd);
  20. if (size < 0) {
  21. perror("ioctl");
  22. exit(EXIT_FAILURE);
  23. }
  24. readable = android::getLogReadableSize(dev->fd);
  25. if (readable < 0) {
  26. perror("ioctl");
  27. exit(EXIT_FAILURE);
  28. }
  29. printf("%s: ring buffer is %dKb (%dKb consumed), "
  30. "max entry is %db, max payload is %db\n", dev->device,
  31. size / 1024, readable / 1024,
  32. (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
  33. }
  34. dev = dev->next;
  35. }
    dev = devices;
while (dev) {
dev->fd = open(dev->device, mode);
if (dev->fd < 0) {
fprintf(stderr, "Unable to open log device '%s': %s\n",
dev->device, strerror(errno));
exit(EXIT_FAILURE);
}
if (clearLog) {
int ret;
ret = android::clearLog(dev->fd);
if (ret) {
perror("ioctl");
exit(EXIT_FAILURE);
}
}
if (getLogSize) {
int size, readable;
size = android::getLogSize(dev->fd);
if (size < 0) {
perror("ioctl");
exit(EXIT_FAILURE);
}
readable = android::getLogReadableSize(dev->fd);
if (readable < 0) {
perror("ioctl");
exit(EXIT_FAILURE);
}
printf("%s: ring buffer is %dKb (%dKb consumed), "
"max entry is %db, max payload is %db\n", dev->device,
size / 1024, readable / 1024,
(int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
}
dev = dev->next;
}

如果执行logcat命令的目的是清空日志,即clearLog为true,则调用android::clearLog函数来执行清空日志操作:

[cpp] view plaincopyprint?
  1. static int clearLog(int logfd)
  2. {
  3. return ioctl(logfd, LOGGER_FLUSH_LOG);
  4. }
static int clearLog(int logfd)
{
return ioctl(logfd, LOGGER_FLUSH_LOG);
}

这里是通过标准的文件函数ioctl函数来执行日志清空操作,具体可以参考logger驱动程序的实现。

如果执行logcat命令的目的是获取日志内存缓冲区的大小,即getLogSize为true,通过调用android::getLogSize函数实现:

[cpp] view plaincopyprint?
  1. /* returns the total size of the log's ring buffer */
  2. static int getLogSize(int logfd)
  3. {
  4. return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
  5. }
/* returns the total size of the log's ring buffer */
static int getLogSize(int logfd)
{
return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
}

如果为负数,即size < 0,就表示出错了,退出程序。

接着验证日志缓冲区可读内容的大小,即调用android::getLogReadableSize函数:

[cpp] view plaincopyprint?
  1. /* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
  2. static int getLogReadableSize(int logfd)
  3. {
  4. return ioctl(logfd, LOGGER_GET_LOG_LEN);
  5. }
/* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
static int getLogReadableSize(int logfd)
{
return ioctl(logfd, LOGGER_GET_LOG_LEN);
}

如果返回负数,即readable < 0,也表示出错了,退出程序。

接下去的printf语句,就是输出日志缓冲区的大小以及可读日志的大小到控制台去了。

继续看下看代码,如果执行logcat命令的目的是清空日志或者获取日志的大小信息,则现在就完成使命了,可以退出程序了:

[cpp] view plaincopyprint?
  1. if (getLogSize) {
  2. return 0;
  3. }
  4. if (clearLog) {
  5. return 0;
  6. }
    if (getLogSize) {
return 0;
}
if (clearLog) {
return 0;
}

否则,就要开始读取设备文件的日志记录了:

[html] view plaincopyprint?
  1. android::readLogLines(devices);
    android::readLogLines(devices);

至此日志设备文件就打开并且初始化好了,下面,我们继续分析从日志设备文件读取日志记录的操作,即readLogLines函数。

三. 读取日志设备文件。

读取日志设备文件内容的函数是readLogLines函数:

[cpp] view plaincopyprint?
  1. static void readLogLines(log_device_t* devices)
  2. {
  3. log_device_t* dev;
  4. int max = 0;
  5. int ret;
  6. int queued_lines = 0;
  7. bool sleep = true;
  8. int result;
  9. fd_set readset;
  10. for (dev=devices; dev; dev = dev->next) {
  11. if (dev->fd > max) {
  12. max = dev->fd;
  13. }
  14. }
  15. while (1) {
  16. do {
  17. timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
  18. FD_ZERO(&readset);
  19. for (dev=devices; dev; dev = dev->next) {
  20. FD_SET(dev->fd, &readset);
  21. }
  22. result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
  23. } while (result == -1 && errno == EINTR);
  24. if (result >= 0) {
  25. for (dev=devices; dev; dev = dev->next) {
  26. if (FD_ISSET(dev->fd, &readset)) {
  27. queued_entry_t* entry = new queued_entry_t();
  28. /* NOTE: driver guarantees we read exactly one full entry */
  29. ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
  30. if (ret < 0) {
  31. if (errno == EINTR) {
  32. delete entry;
  33. goto next;
  34. }
  35. if (errno == EAGAIN) {
  36. delete entry;
  37. break;
  38. }
  39. perror("logcat read");
  40. exit(EXIT_FAILURE);
  41. }
  42. else if (!ret) {
  43. fprintf(stderr, "read: Unexpected EOF!\n");
  44. exit(EXIT_FAILURE);
  45. }
  46. entry->entry.msg[entry->entry.len] = '\0';
  47. dev->enqueue(entry);
  48. ++queued_lines;
  49. }
  50. }
  51. if (result == 0) {
  52. // we did our short timeout trick and there's nothing new
  53. // print everything we have and wait for more data
  54. sleep = true;
  55. while (true) {
  56. chooseFirst(devices, &dev);
  57. if (dev == NULL) {
  58. break;
  59. }
  60. if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
  61. printNextEntry(dev);
  62. } else {
  63. skipNextEntry(dev);
  64. }
  65. --queued_lines;
  66. }
  67. // the caller requested to just dump the log and exit
  68. if (g_nonblock) {
  69. exit(0);
  70. }
  71. } else {
  72. // print all that aren't the last in their list
  73. sleep = false;
  74. while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
  75. chooseFirst(devices, &dev);
  76. if (dev == NULL || dev->queue->next == NULL) {
  77. break;
  78. }
  79. if (g_tail_lines == 0) {
  80. printNextEntry(dev);
  81. } else {
  82. skipNextEntry(dev);
  83. }
  84. --queued_lines;
  85. }
  86. }
  87. }
  88. next:
  89. ;
  90. }
  91. }
static void readLogLines(log_device_t* devices)
{
log_device_t* dev;
int max = 0;
int ret;
int queued_lines = 0;
bool sleep = true;
int result;
fd_set readset;
for (dev=devices; dev; dev = dev->next) {
if (dev->fd > max) {
max = dev->fd;
}
}
while (1) {
do {
timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
FD_ZERO(&readset);
for (dev=devices; dev; dev = dev->next) {
FD_SET(dev->fd, &readset);
}
result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
} while (result == -1 && errno == EINTR);
if (result >= 0) {
for (dev=devices; dev; dev = dev->next) {
if (FD_ISSET(dev->fd, &readset)) {
queued_entry_t* entry = new queued_entry_t();
/* NOTE: driver guarantees we read exactly one full entry */
ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
if (ret < 0) {
if (errno == EINTR) {
delete entry;
goto next;
}
if (errno == EAGAIN) {
delete entry;
break;
}
perror("logcat read");
exit(EXIT_FAILURE);
}
else if (!ret) {
fprintf(stderr, "read: Unexpected EOF!\n");
exit(EXIT_FAILURE);
}
entry->entry.msg[entry->entry.len] = '\0';
dev->enqueue(entry);
++queued_lines;
}
}
if (result == 0) {
// we did our short timeout trick and there's nothing new
// print everything we have and wait for more data
sleep = true;
while (true) {
chooseFirst(devices, &dev);
if (dev == NULL) {
break;
}
if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}
--queued_lines;
}
// the caller requested to just dump the log and exit
if (g_nonblock) {
exit(0);
}
} else {
// print all that aren't the last in their list
sleep = false;
while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
chooseFirst(devices, &dev);
if (dev == NULL || dev->queue->next == NULL) {
break;
}
if (g_tail_lines == 0) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}
--queued_lines;
}
}
}
next:
;
}
}

由于可能同时打开了多个日志设备文件,这里使用select函数来同时监控哪个文件当前可读:

[cpp] view plaincopyprint?
  1. do {
  2. timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
  3. FD_ZERO(&readset);
  4. for (dev=devices; dev; dev = dev->next) {
  5. FD_SET(dev->fd, &readset);
  6. }
  7. result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
  8. } while (result == -1 && errno == EINTR);
    do {
timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
FD_ZERO(&readset);
for (dev=devices; dev; dev = dev->next) {
FD_SET(dev->fd, &readset);
}
result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
} while (result == -1 && errno == EINTR);

如果result >= 0,就表示有日志设备文件可读或者超时。接着,用一个for语句检查哪个设备文件可读,即FD_ISSET(dev->fd, &readset)是否为true,如果为true,表明可读,就要进一步通过read函数将日志读出,注意,每次只读出一条日志记录:

[cpp] view plaincopyprint?
  1. for (dev=devices; dev; dev = dev->next) {
  2. if (FD_ISSET(dev->fd, &readset)) {
  3. queued_entry_t* entry = new queued_entry_t();
  4. /* NOTE: driver guarantees we read exactly one full entry */
  5. ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
  6. if (ret < 0) {
  7. if (errno == EINTR) {
  8. delete entry;
  9. goto next;
  10. }
  11. if (errno == EAGAIN) {
  12. delete entry;
  13. break;
  14. }
  15. perror("logcat read");
  16. exit(EXIT_FAILURE);
  17. }
  18. else if (!ret) {
  19. fprintf(stderr, "read: Unexpected EOF!\n");
  20. exit(EXIT_FAILURE);
  21. }
  22. entry->entry.msg[entry->entry.len] = '\0';
  23. dev->enqueue(entry);
  24. ++queued_lines;
  25. }
  26. }
     for (dev=devices; dev; dev = dev->next) {
if (FD_ISSET(dev->fd, &readset)) {
queued_entry_t* entry = new queued_entry_t();
/* NOTE: driver guarantees we read exactly one full entry */
ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
if (ret < 0) {
if (errno == EINTR) {
delete entry;
goto next;
}
if (errno == EAGAIN) {
delete entry;
break;
}
perror("logcat read");
exit(EXIT_FAILURE);
}
else if (!ret) {
fprintf(stderr, "read: Unexpected EOF!\n");
exit(EXIT_FAILURE);
}
entry->entry.msg[entry->entry.len] = '\0';
dev->enqueue(entry);
++queued_lines;
}
}

调用read函数之前,先创建一个日志记录项entry,接着调用read函数将日志读到entry->buf中,最后调用dev->enqueue(entry)将日志记录加入到日志队例中去。同时,把当前的日志记录数保存在queued_lines变量中。

继续进一步处理日志:

[cpp] view plaincopyprint?
  1. if (result == 0) {
  2. // we did our short timeout trick and there's nothing new
  3. // print everything we have and wait for more data
  4. sleep = true;
  5. while (true) {
  6. chooseFirst(devices, &dev);
  7. if (dev == NULL) {
  8. break;
  9. }
  10. if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
  11. printNextEntry(dev);
  12. } else {
  13. skipNextEntry(dev);
  14. }
  15. --queued_lines;
  16. }
  17. // the caller requested to just dump the log and exit
  18. if (g_nonblock) {
  19. exit(0);
  20. }
  21. } else {
  22. // print all that aren't the last in their list
  23. sleep = false;
  24. while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
  25. chooseFirst(devices, &dev);
  26. if (dev == NULL || dev->queue->next == NULL) {
  27. break;
  28. }
  29. if (g_tail_lines == 0) {
  30. printNextEntry(dev);
  31. } else {
  32. skipNextEntry(dev);
  33. }
  34. --queued_lines;
  35. }
  36. }
            if (result == 0) {
// we did our short timeout trick and there's nothing new
// print everything we have and wait for more data
sleep = true;
while (true) {
chooseFirst(devices, &dev);
if (dev == NULL) {
break;
}
if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}
--queued_lines;
}
// the caller requested to just dump the log and exit
if (g_nonblock) {
exit(0);
}
} else {
// print all that aren't the last in their list
sleep = false;
while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
chooseFirst(devices, &dev);
if (dev == NULL || dev->queue->next == NULL) {
break;
}
if (g_tail_lines == 0) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}
--queued_lines;
}
}

如果result == 0,表明是等待超时了,目前没有新的日志可读,这时候就要先处理之前已经读出来的日志。调用chooseFirst选择日志队列不为空,且日志队列中的第一个日志记录的时间戳为最小的设备,即先输出最旧的日志:

[cpp] view plaincopyprint?
  1. static void chooseFirst(log_device_t* dev, log_device_t** firstdev) {
  2. for (*firstdev = NULL; dev != NULL; dev = dev->next) {
  3. if (dev->queue != NULL && (*firstdev == NULL || cmp(dev->queue, (*firstdev)->queue) < 0)) {
  4. *firstdev = dev;
  5. }
  6. }
  7. }
static void chooseFirst(log_device_t* dev, log_device_t** firstdev) {
for (*firstdev = NULL; dev != NULL; dev = dev->next) {
if (dev->queue != NULL && (*firstdev == NULL || cmp(dev->queue, (*firstdev)->queue) < 0)) {
*firstdev = dev;
}
}
}

如果存在这样的日志设备,接着判断日志记录是应该丢弃还是输出。前面我们说过,如果执行logcat命令时,指定了参数-t <count>,那么就会只显示最新的count条记录,其它的旧记录将被丢弃:

[cpp] view plaincopyprint?
  1. if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
  2. printNextEntry(dev);
  3. } else {
  4. skipNextEntry(dev);
  5. }
    if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}

g_tail_lines表示显示最新记录的条数,如果为0,就表示全部显示。如果g_tail_lines == 0或者queued_lines <= g_tail_lines,就表示这条日志记录应该输出,否则就要丢弃了。每处理完一条日志记录,queued_lines就减1,这样,最新的g_tail_lines就可以输出出来了。

如果result > 0,表明有新的日志可读,这时候的处理方式与result == 0的情况不同,因为这时候还有新的日志可读,所以就不能先急着处理之前已经读出来的日志。这里,分两种情况考虑,如果能设置了只显示最新的g_tail_lines条记录,并且当前已经读出来的日志记录条数已经超过g_tail_lines,就要丢弃,剩下的先不处理,等到下次再来处理;如果没有设备显示最新的g_tail_lines条记录,即g_tail_lines == 0,这种情况就和result  == 0的情况处理方式一样,先处理所有已经读出的日志记录,再进入下一次循环。希望读者可以好好体会这段代码:

[cpp] view plaincopyprint?
  1. while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
  2. chooseFirst(devices, &dev);
  3. if (dev == NULL || dev->queue->next == NULL) {
  4. break;
  5. }
  6. if (g_tail_lines == 0) {
  7. printNextEntry(dev);
  8. } else {
  9. skipNextEntry(dev);
  10. }
  11. --queued_lines;
  12. }
    while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
chooseFirst(devices, &dev);
if (dev == NULL || dev->queue->next == NULL) {
break;
}
if (g_tail_lines == 0) {
printNextEntry(dev);
} else {
skipNextEntry(dev);
}
--queued_lines;
}

丢弃日志记录的函数skipNextEntry实现如下:

[cpp] view plaincopyprint?
  1. static void skipNextEntry(log_device_t* dev) {
  2. maybePrintStart(dev);
  3. queued_entry_t* entry = dev->queue;
  4. dev->queue = entry->next;
  5. delete entry;
  6. }
static void skipNextEntry(log_device_t* dev) {
maybePrintStart(dev);
queued_entry_t* entry = dev->queue;
dev->queue = entry->next;
delete entry;
}

这里只是简单地跳过日志队列头,这样就把最旧的日志丢弃了。

printNextEntry函数处理日志输出,下一节中继续分析。

四. 输出日志设备文件的内容。

从前面的分析中看出,最终日志设备文件内容的输出是通过printNextEntry函数进行的:

[cpp] view plaincopyprint?
  1. static void printNextEntry(log_device_t* dev) {
  2. maybePrintStart(dev);
  3. if (g_printBinary) {
  4. printBinary(&dev->queue->entry);
  5. } else {
  6. processBuffer(dev, &dev->queue->entry);
  7. }
  8. skipNextEntry(dev);
  9. }
static void printNextEntry(log_device_t* dev) {
maybePrintStart(dev);
if (g_printBinary) {
printBinary(&dev->queue->entry);
} else {
processBuffer(dev, &dev->queue->entry);
}
skipNextEntry(dev);
}

g_printBinary为true时,以二进制方式输出日志内容到指定的文件中:

[cpp] view plaincopyprint?
  1. void printBinary(struct logger_entry *buf)
  2. {
  3. size_t size = sizeof(logger_entry) + buf->len;
  4. int ret;
  5. do {
  6. ret = write(g_outFD, buf, size);
  7. } while (ret < 0 && errno == EINTR);
  8. }
void printBinary(struct logger_entry *buf)
{
size_t size = sizeof(logger_entry) + buf->len;
int ret;
do {
ret = write(g_outFD, buf, size);
} while (ret < 0 && errno == EINTR);
}

我们关注g_printBinary为false的情况,调用processBuffer进一步处理:

[cpp] view plaincopyprint?
  1. static void processBuffer(log_device_t* dev, struct logger_entry *buf)
  2. {
  3. int bytesWritten = 0;
  4. int err;
  5. AndroidLogEntry entry;
  6. char binaryMsgBuf[1024];
  7. if (dev->binary) {
  8. err = android_log_processBinaryLogBuffer(buf, &entry, g_eventTagMap,
  9. binaryMsgBuf, sizeof(binaryMsgBuf));
  10. //printf(">>> pri=%d len=%d msg='%s'\n",
  11. //    entry.priority, entry.messageLen, entry.message);
  12. } else {
  13. err = android_log_processLogBuffer(buf, &entry);
  14. }
  15. if (err < 0) {
  16. goto error;
  17. }
  18. if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
  19. if (false && g_devCount > 1) {
  20. binaryMsgBuf[0] = dev->label;
  21. binaryMsgBuf[1] = ' ';
  22. bytesWritten = write(g_outFD, binaryMsgBuf, 2);
  23. if (bytesWritten < 0) {
  24. perror("output error");
  25. exit(-1);
  26. }
  27. }
  28. bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
  29. if (bytesWritten < 0) {
  30. perror("output error");
  31. exit(-1);
  32. }
  33. }
  34. g_outByteCount += bytesWritten;
  35. if (g_logRotateSizeKBytes > 0
  36. && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
  37. ) {
  38. rotateLogs();
  39. }
  40. error:
  41. //fprintf (stderr, "Error processing record\n");
  42. return;
  43. }
static void processBuffer(log_device_t* dev, struct logger_entry *buf)
{
int bytesWritten = 0;
int err;
AndroidLogEntry entry;
char binaryMsgBuf[1024];
if (dev->binary) {
err = android_log_processBinaryLogBuffer(buf, &entry, g_eventTagMap,
binaryMsgBuf, sizeof(binaryMsgBuf));
//printf(">>> pri=%d len=%d msg='%s'\n",
//    entry.priority, entry.messageLen, entry.message);
} else {
err = android_log_processLogBuffer(buf, &entry);
}
if (err < 0) {
goto error;
}
if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
if (false && g_devCount > 1) {
binaryMsgBuf[0] = dev->label;
binaryMsgBuf[1] = ' ';
bytesWritten = write(g_outFD, binaryMsgBuf, 2);
if (bytesWritten < 0) {
perror("output error");
exit(-1);
}
}
bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
if (bytesWritten < 0) {
perror("output error");
exit(-1);
}
}
g_outByteCount += bytesWritten;
if (g_logRotateSizeKBytes > 0
&& (g_outByteCount / 1024) >= g_logRotateSizeKBytes
) {
rotateLogs();
}
error:
//fprintf (stderr, "Error processing record\n");
return;
}

当dev->binary为true,日志记录项是二进制形式,不同于我们在Android日志系统驱动程序Logger源代码分析一文中提到的常规格式:

struct logger_entry | priority | tag | msg
        这里我们不关注这种情况,有兴趣的读者可以自已分析,android_log_processBinaryLogBuffer函数定义在system/core/liblog/logprint.c文件中,它的作用是将一条二进制形式的日志记录转换为ASCII形式,并保存在entry参数中,它的原型为:

[cpp] view plaincopyprint?
  1. /**
  2. * Convert a binary log entry to ASCII form.
  3. *
  4. * For convenience we mimic the processLogBuffer API.  There is no
  5. * pre-defined output length for the binary data, since we're free to format
  6. * it however we choose, which means we can't really use a fixed-size buffer
  7. * here.
  8. */
  9. int android_log_processBinaryLogBuffer(struct logger_entry *buf,
  10. AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
  11. int messageBufLen);
/**
* Convert a binary log entry to ASCII form.
*
* For convenience we mimic the processLogBuffer API.  There is no
* pre-defined output length for the binary data, since we're free to format
* it however we choose, which means we can't really use a fixed-size buffer
* here.
*/
int android_log_processBinaryLogBuffer(struct logger_entry *buf,
AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
int messageBufLen);

通常情况下,dev->binary为false,调用android_log_processLogBuffer函数将日志记录由logger_entry格式转换为AndroidLogEntry格式。logger_entry格式在在Android日志系统驱动程序Logger源代码分析一文中已经有详细描述,这里不述;AndroidLogEntry结构体定义在system/core/include/cutils/logprint.h中:

[cpp] view plaincopyprint?
  1. typedef struct AndroidLogEntry_t {
  2. time_t tv_sec;
  3. long tv_nsec;
  4. android_LogPriority priority;
  5. pid_t pid;
  6. pthread_t tid;
  7. const char * tag;
  8. size_t messageLen;
  9. const char * message;
  10. } AndroidLogEntry;
typedef struct AndroidLogEntry_t {
time_t tv_sec;
long tv_nsec;
android_LogPriority priority;
pid_t pid;
pthread_t tid;
const char * tag;
size_t messageLen;
const char * message;
} AndroidLogEntry;

android_LogPriority是一个枚举类型,定义在system/core/include/android/log.h文件中:

[cpp] view plaincopyprint?
  1. /*
  2. * Android log priority values, in ascending priority order.
  3. */
  4. typedef enum android_LogPriority {
  5. ANDROID_LOG_UNKNOWN = 0,
  6. ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
  7. ANDROID_LOG_VERBOSE,
  8. ANDROID_LOG_DEBUG,
  9. ANDROID_LOG_INFO,
  10. ANDROID_LOG_WARN,
  11. ANDROID_LOG_ERROR,
  12. ANDROID_LOG_FATAL,
  13. ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
  14. } android_LogPriority;
/*
* Android log priority values, in ascending priority order.
*/
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
} android_LogPriority;

android_log_processLogBuffer定义在system/core/liblog/logprint.c文件中:

[cpp] view plaincopyprint?
  1. /**
  2. * Splits a wire-format buffer into an AndroidLogEntry
  3. * entry allocated by caller. Pointers will point directly into buf
  4. *
  5. * Returns 0 on success and -1 on invalid wire format (entry will be
  6. * in unspecified state)
  7. */
  8. int android_log_processLogBuffer(struct logger_entry *buf,
  9. AndroidLogEntry *entry)
  10. {
  11. size_t tag_len;
  12. entry->tv_sec = buf->sec;
  13. entry->tv_nsec = buf->nsec;
  14. entry->priority = buf->msg[0];
  15. entry->pid = buf->pid;
  16. entry->tid = buf->tid;
  17. entry->tag = buf->msg + 1;
  18. tag_len = strlen(entry->tag);
  19. entry->messageLen = buf->len - tag_len - 3;
  20. entry->message = entry->tag + tag_len + 1;
  21. return 0;
  22. }
/**
* Splits a wire-format buffer into an AndroidLogEntry
* entry allocated by caller. Pointers will point directly into buf
*
* Returns 0 on success and -1 on invalid wire format (entry will be
* in unspecified state)
*/
int android_log_processLogBuffer(struct logger_entry *buf,
AndroidLogEntry *entry)
{
size_t tag_len;
entry->tv_sec = buf->sec;
entry->tv_nsec = buf->nsec;
entry->priority = buf->msg[0];
entry->pid = buf->pid;
entry->tid = buf->tid;
entry->tag = buf->msg + 1;
tag_len = strlen(entry->tag);
entry->messageLen = buf->len - tag_len - 3;
entry->message = entry->tag + tag_len + 1;
return 0;
}

结合logger_entry结构体中日志项的格式定义(struct logger_entry | priority | tag | msg),这个函数很直观,不再累述。

调用完android_log_processLogBuffer函数后,日志记录的具体信息就保存在本地变量entry中了,接着调用android_log_shouldPrintLine函数来判断这条日志记录是否应该输出。

在分析android_log_shouldPrintLine函数之前,我们先了解数据结构AndroidLogFormat,这个结构体定义在system/core/liblog/logprint.c文件中:

[cpp] view plaincopyprint?
  1. struct AndroidLogFormat_t {
  2. android_LogPriority global_pri;
  3. FilterInfo *filters;
  4. AndroidLogPrintFormat format;
  5. };
struct AndroidLogFormat_t {
android_LogPriority global_pri;
FilterInfo *filters;
AndroidLogPrintFormat format;
};

AndroidLogPrintFormat也是定义在system/core/liblog/logprint.c文件中:

[cpp] view plaincopyprint?
  1. typedef struct FilterInfo_t {
  2. char *mTag;
  3. android_LogPriority mPri;
  4. struct FilterInfo_t *p_next;
  5. } FilterInfo;
typedef struct FilterInfo_t {
char *mTag;
android_LogPriority mPri;
struct FilterInfo_t *p_next;
} FilterInfo;

因此,可以看出,AndroidLogFormat结构体定义了日志过滤规范。在logcat.c文件中,定义了变量

[cpp] view plaincopyprint?
  1. static AndroidLogFormat * g_logformat;
static AndroidLogFormat * g_logformat;

这个变量是在main函数里面进行分配的:

[cpp] view plaincopyprint?
  1. g_logformat = android_log_format_new();
g_logformat = android_log_format_new();

在main函数里面,在分析logcat命令行参数时,会将g_logformat进行初始化,有兴趣的读者可以自行分析。

回到android_log_shouldPrintLine函数中,它定义在system/core/liblog/logprint.c文件中:

[cpp] view plaincopyprint?
  1. /**
  2. * returns 1 if this log line should be printed based on its priority
  3. * and tag, and 0 if it should not
  4. */
  5. int android_log_shouldPrintLine (
  6. AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
  7. {
  8. return pri >= filterPriForTag(p_format, tag);
  9. }
/**
* returns 1 if this log line should be printed based on its priority
* and tag, and 0 if it should not
*/
int android_log_shouldPrintLine (
AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
{
return pri >= filterPriForTag(p_format, tag);
}

这个函数判断在p_format中根据tag值,找到对应的pri值,如果返回来的pri值小于等于参数传进来的pri值,那么就表示这条日志记录可以输出。我们来看filterPriForTag函数的实现:

[cpp] view plaincopyprint?
  1. static android_LogPriority filterPriForTag(
  2. AndroidLogFormat *p_format, const char *tag)
  3. {
  4. FilterInfo *p_curFilter;
  5. for (p_curFilter = p_format->filters
  6. ; p_curFilter != NULL
  7. ; p_curFilter = p_curFilter->p_next
  8. ) {
  9. if (0 == strcmp(tag, p_curFilter->mTag)) {
  10. if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
  11. return p_format->global_pri;
  12. } else {
  13. return p_curFilter->mPri;
  14. }
  15. }
  16. }
  17. return p_format->global_pri;
  18. }
static android_LogPriority filterPriForTag(
AndroidLogFormat *p_format, const char *tag)
{
FilterInfo *p_curFilter;
for (p_curFilter = p_format->filters
; p_curFilter != NULL
; p_curFilter = p_curFilter->p_next
) {
if (0 == strcmp(tag, p_curFilter->mTag)) {
if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
return p_format->global_pri;
} else {
return p_curFilter->mPri;
}
}
}
return p_format->global_pri;
}

如果在p_format中找到与tag值对应的filter,并且该filter的mPri不等于ANDROID_LOG_DEFAULT,那么就返回该filter的成员变量mPri的值;其它情况下,返回p_format->global_pri的值。

回到processBuffer函数中,如果执行完android_log_shouldPrintLine函数后,表明当前日志记录应当输出,则调用android_log_printLogLine函数来输出日志记录到文件fd中, 这个函数也是定义在system/core/liblog/logprint.c文件中:

[cpp] view plaincopyprint?
  1. int android_log_printLogLine(
  2. AndroidLogFormat *p_format,
  3. int fd,
  4. const AndroidLogEntry *entry)
  5. {
  6. int ret;
  7. char defaultBuffer[512];
  8. char *outBuffer = NULL;
  9. size_t totalLen;
  10. outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
  11. sizeof(defaultBuffer), entry, &totalLen);
  12. if (!outBuffer)
  13. return -1;
  14. do {
  15. ret = write(fd, outBuffer, totalLen);
  16. } while (ret < 0 && errno == EINTR);
  17. if (ret < 0) {
  18. fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
  19. ret = 0;
  20. goto done;
  21. }
  22. if (((size_t)ret) < totalLen) {
  23. fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
  24. (int)totalLen);
  25. goto done;
  26. }
  27. done:
  28. if (outBuffer != defaultBuffer) {
  29. free(outBuffer);
  30. }
  31. return ret;
  32. }
int android_log_printLogLine(
AndroidLogFormat *p_format,
int fd,
const AndroidLogEntry *entry)
{
int ret;
char defaultBuffer[512];
char *outBuffer = NULL;
size_t totalLen;
outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
sizeof(defaultBuffer), entry, &totalLen);
if (!outBuffer)
return -1;
do {
ret = write(fd, outBuffer, totalLen);
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
ret = 0;
goto done;
}
if (((size_t)ret) < totalLen) {
fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
(int)totalLen);
goto done;
}
done:
if (outBuffer != defaultBuffer) {
free(outBuffer);
}
return ret;
}

这个函数的作用就是把AndroidLogEntry格式的日志记录按照指定的格式AndroidLogFormat进行输出了,这里,不再进一步分析这个函数。

processBuffer函数的最后,还有一个rotateLogs的操作:

[cpp] view plaincopyprint?
  1. static void rotateLogs()
  2. {
  3. int err;
  4. // Can't rotate logs if we're not outputting to a file
  5. if (g_outputFileName == NULL) {
  6. return;
  7. }
  8. close(g_outFD);
  9. for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
  10. char *file0, *file1;
  11. asprintf(&file1, "%s.%d", g_outputFileName, i);
  12. if (i - 1 == 0) {
  13. asprintf(&file0, "%s", g_outputFileName);
  14. } else {
  15. asprintf(&file0, "%s.%d", g_outputFileName, i - 1);
  16. }
  17. err = rename (file0, file1);
  18. if (err < 0 && errno != ENOENT) {
  19. perror("while rotating log files");
  20. }
  21. free(file1);
  22. free(file0);
  23. }
  24. g_outFD = openLogFile (g_outputFileName);
  25. if (g_outFD < 0) {
  26. perror ("couldn't open output file");
  27. exit(-1);
  28. }
  29. g_outByteCount = 0;
  30. }
static void rotateLogs()
{
int err;
// Can't rotate logs if we're not outputting to a file
if (g_outputFileName == NULL) {
return;
}
close(g_outFD);
for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
char *file0, *file1;
asprintf(&file1, "%s.%d", g_outputFileName, i);
if (i - 1 == 0) {
asprintf(&file0, "%s", g_outputFileName);
} else {
asprintf(&file0, "%s.%d", g_outputFileName, i - 1);
}
err = rename (file0, file1);
if (err < 0 && errno != ENOENT) {
perror("while rotating log files");
}
free(file1);
free(file0);
}
g_outFD = openLogFile (g_outputFileName);
if (g_outFD < 0) {
perror ("couldn't open output file");
exit(-1);
}
g_outByteCount = 0;
}

这个函数只有在执行logcat命令时,指定了-f <filename>参数时,即g_outputFileName不为NULL时才起作用。它的作用是在将日志记录循环输出到一组文件中。例如,指定-f参数为logfile,g_maxRotatedLogs为3,则这组文件分别为:

logfile,logfile.1,logfile.2,logfile.3

当当前输入到logfile文件的日志记录大小g_outByteCount大于等于g_logRotateSizeKBytes时,就要将logfile.2的内容移至logfile.3中,同时将logfile.1的内容移至logfile.2中,同时logfle的内容移至logfile.1中,再重新打开logfile文件进入后续输入。这样做的作用是不至于使得日志文件变得越来越来大,以至于占用过多的磁盘空间,而是只在磁盘上保存一定量的最新的日志记录。这样,旧的日志记录就会可能被新的日志记录所覆盖。

至此,关于Android日志系统源代码,我们就完整地分析完了,其中包括位于内核空间的驱动程序Logger源代码分析,还有位于应用程序框架层和系统运行库层的日志写入操作接口源代码分析和用于日志读取的工具Logcat源代码分析,希望能够帮助读者对Android的日志系统有一个清晰的认识

android log系统相关推荐

  1. Android LOG系统原理剖析

    引言 在我们android的开发过程中,最不可少的就是加Log,打印Log的操作. 这样可以帮助我们去查看各个变量,理清楚代码的逻辑. 而Android系统,提供了不同维度,不同层面,不同模块的Log ...

  2. android log机制——输出log

    转自: http://my.oschina.net/wolfcs/blog/164624 android log系统. 在android Java code中输出log android系统有4种类型. ...

  3. AndroidT(13) Log 系统 -- C 语言格式的LOG输出(一)

    1.概览   c语言中的printf我想大家都非常的熟悉了,他的基本格式如下 int printf(const char *format, ...);   前半部分 format 指向的字符串用于描述 ...

  4. AndroidT(13) Log 系统 -- C plus plus 语言格式的LOG输出(二)

    1.概览   上一章提到的是在Android系统中,以C语言格式方式进行log输出.本章就来讲讲c++语言格式的. std::cout<<"This is a c++ log&q ...

  5. Android Log系统介绍 (基于Android N)

    原文使用有道云笔记创作, 看这个: http://note.youdao.com/noteshare?id=82f88b1c82652b80c27d54aad55af035 ``` 引言 > A ...

  6. android core log,Android 日志系统(Logcat)的实现分析

    这篇说一下Android 日志系统的实现: 1. Android中的打印分为4个缓冲区和6个打印等级,在frameworks\base\core\java\android\util\Log.java中 ...

  7. 深入理解Android消息处理系统——Looper、Handler、Thread

    引用自:http://my.unix-center.net/~Simon_fu/?p=652 熟悉Windows编程的朋友可能知道Windows程序是消息驱动的,并且有全局的消息循环系统.而Andro ...

  8. Android消息处理系统——Looper、Handler、Thread(转载)

    熟悉Windows编程的朋友可能知道Windows程序是消息驱动的,并且有全局的消息循环系统.而Android应用程序也是消息驱动的,按道理来说也应该提供消息循环机制.实际上谷歌参考了Windows的 ...

  9. android log丢失(一)使用logd丢失log原理

    之前我们分析过关于Android log机制,在这里我们再详细说下,log丢失的原理. 一.统计log logd监听了logdw的socket来保存从log打印函数通过logdw socket传过来的 ...

最新文章

  1. numpy.random.choice用法
  2. C# 3.0入门系列
  3. 超强整理!PCB设计之电流与线宽的关系
  4. mysql int zerofill_Mysql 中int[M]—zerofill-阿里云开发者社区
  5. 编辑器-Vim常用命令
  6. 荧光共定位定量分析,单通道散点图剖析
  7. Java开发必会的反编译知识
  8. 是谁干的 linux找嫌疑人
  9. 【算法】赫夫曼编码 解码 实际应用 文件的编码 解码
  10. SAP License:SAP中的权限与破解
  11. 微软发布紧急更新,修复了多个 Windows Server 身份验证问题
  12. github emoji 表情列表 1
  13. 关于配置文件的节点内容加密(备忘)
  14. [C++ primer]优化内存分配
  15. Java面试之爱立信
  16. matlab怎么训练神经网络,matlab神经网络训练方法
  17. BoundsChecker教程
  18. leetcode 热点——排列组合问题
  19. python 3 12306余票查询脚本
  20. 解决易语言出现死循环代码错误提示

热门文章

  1. java中父子类同名变量
  2. 多语种翻译互译,批量小语种翻译互译
  3. 如何在树莓派上安装 Fedora 25
  4. [028量化交易] python joinquant获取行情数据
  5. Node.js 学习 ——nodemon 运行报错解决
  6. html设置内容居中,设置div内容居中
  7. 感觉犹太人最有名的这十句话也挺有感悟的!不妨你来看看!
  8. 如何将 Spotify 音乐添加到 djay Pro
  9. java静态方法调用非静态变量_[java]静态方法访问非静态方法的方法
  10. 手把手教你安装Modelsim SE 6.5g