当前位置:   article > 正文

android/mydroid/system/core/logcat/logcat.cpp

android/mydroid/system/core/logcat/logcat.cpp
  1. // Copyright 2006 The Android Open Source Project
  2. #include <utils/misc.h>
  3. #include <utils/logger.h>
  4. #include <cutils/logd.h>
  5. #include <cutils/sockets.h>
  6. #include <cutils/logprint.h>
  7. #include <cutils/event_tag_map.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <stdarg.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. #include <time.h>
  15. #include <errno.h>
  16. #include <assert.h>
  17. #include <ctype.h>
  18. #include <sys/socket.h>
  19. #include <sys/stat.h>
  20. #include <arpa/inet.h>
  21. #define DEFAULT_LOG_ROTATE_SIZE_KBYTES 16
  22. #define DEFAULT_MAX_ROTATED_LOGS 4
  23. static AndroidLogFormat * g_logformat;
  24. /* logd prefixes records with a length field */
  25. #define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
  26. #define LOG_FILE_DIR "/dev/log/"
  27. namespace android {
  28. /* Global Variables */
  29. static const char * g_outputFileName = NULL;
  30. static int g_logRotateSizeKBytes = 0; // 0 means "no log rotation"
  31. static int g_maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded"
  32. static int g_outFD = -1;
  33. static off_t g_outByteCount = 0;
  34. static int g_isBinary = 0;
  35. static int g_printBinary = 0;
  36. static EventTagMap* g_eventTagMap = NULL;
  37. static int openLogFile (const char *pathname)
  38. {
  39. return open(g_outputFileName, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  40. }
  41. static void rotateLogs()
  42. {
  43. int err;
  44. // Can't rotate logs if we're not outputting to a file
  45. if (g_outputFileName == NULL) {
  46. return;
  47. }
  48. close(g_outFD);
  49. for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
  50. char *file0, *file1;
  51. asprintf(&file1, "%s.%d", g_outputFileName, i);
  52. if (i - 1 == 0) {
  53. asprintf(&file0, "%s", g_outputFileName);
  54. } else {
  55. asprintf(&file0, "%s.%d", g_outputFileName, i - 1);
  56. }
  57. err = rename (file0, file1);
  58. if (err < 0 && errno != ENOENT) {
  59. perror("while rotating log files");
  60. }
  61. free(file1);
  62. free(file0);
  63. }
  64. g_outFD = openLogFile (g_outputFileName);
  65. if (g_outFD < 0) {
  66. perror ("couldn't open output file");
  67. exit(-1);
  68. }
  69. g_outByteCount = 0;
  70. }
  71. void printBinary(struct logger_entry *buf)
  72. {
  73. size_t size = sizeof(logger_entry) + buf->len;
  74. int ret;
  75. do {
  76. ret = write(g_outFD, buf, size);
  77. } while (ret < 0 && errno == EINTR);
  78. }
  79. static void processBuffer(struct logger_entry *buf)
  80. {
  81. int bytesWritten;
  82. int err;
  83. AndroidLogEntry entry;
  84. char binaryMsgBuf[1024];
  85. if (g_isBinary) {
  86. err = android_log_processBinaryLogBuffer(buf, &entry, g_eventTagMap,
  87. binaryMsgBuf, sizeof(binaryMsgBuf));
  88. //printf(">>> pri=%d len=%d msg='%s'\n",
  89. // entry.priority, entry.messageLen, entry.message);
  90. } else {
  91. err = android_log_processLogBuffer(buf, &entry);
  92. }
  93. if (err < 0)
  94. goto error;
  95. bytesWritten = android_log_filterAndPrintLogLine(
  96. g_logformat, g_outFD, &entry);
  97. if (bytesWritten < 0) {
  98. perror("output error");
  99. exit(-1);
  100. }
  101. g_outByteCount += bytesWritten;
  102. if (g_logRotateSizeKBytes > 0
  103. && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
  104. ) {
  105. rotateLogs();
  106. }
  107. error:
  108. //fprintf (stderr, "Error processing record\n");
  109. return;
  110. }
  111. static void readLogLines(int logfd)
  112. {
  113. while (1) {
  114. unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
  115. struct logger_entry *entry = (struct logger_entry *) buf;
  116. int ret;
  117. ret = read(logfd, entry, LOGGER_ENTRY_MAX_LEN);
  118. if (ret < 0) {
  119. if (errno == EINTR)
  120. continue;
  121. if (errno == EAGAIN)
  122. break;
  123. perror("logcat read");
  124. exit(EXIT_FAILURE);
  125. }
  126. else if (!ret) {
  127. fprintf(stderr, "read: Unexpected EOF!\n");
  128. exit(EXIT_FAILURE);
  129. }
  130. /* NOTE: driver guarantees we read exactly one full entry */
  131. entry->msg[entry->len] = '\0';
  132. if (g_printBinary) {
  133. printBinary(entry);
  134. } else {
  135. (void) processBuffer(entry);
  136. }
  137. }
  138. }
  139. static int clearLog(int logfd)
  140. {
  141. return ioctl(logfd, LOGGER_FLUSH_LOG);
  142. }
  143. /* returns the total size of the log's ring buffer */
  144. static int getLogSize(int logfd)
  145. {
  146. return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
  147. }
  148. /* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
  149. static int getLogReadableSize(int logfd)
  150. {
  151. return ioctl(logfd, LOGGER_GET_LOG_LEN);
  152. }
  153. static void setupOutput()
  154. {
  155. if (g_outputFileName == NULL) {
  156. g_outFD = STDOUT_FILENO;
  157. } else {
  158. struct stat statbuf;
  159. g_outFD = openLogFile (g_outputFileName);
  160. if (g_outFD < 0) {
  161. perror ("couldn't open output file");
  162. exit(-1);
  163. }
  164. fstat(g_outFD, &statbuf);
  165. g_outByteCount = statbuf.st_size;
  166. }
  167. }
  168. static void show_help(const char *cmd)
  169. {
  170. fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
  171. fprintf(stderr, "options include:\n"
  172. " -s Set default filter to silent.\n"
  173. " Like specifying filterspec '*:s'\n"
  174. " -f <filename> Log to file. Default to stdout\n"
  175. " -r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f\n"
  176. " -n <count> Sets max number of rotated logs to <count>, default 4\n"
  177. " -v <format> Sets the log print format, where <format> is one of:\n\n"
  178. " brief process tag thread raw time threadtime long\n\n"
  179. " -c clear (flush) the entire log and exit\n"
  180. " -d dump the log and then exit (don't block)\n"
  181. " -g get the size of the log's ring buffer and exit\n"
  182. " -b <buffer> request alternate ring buffer\n"
  183. " ('main' (default), 'radio', 'events')\n"
  184. " -B output the log in binary");
  185. fprintf(stderr,"\nfilterspecs are a series of \n"
  186. " <tag>[:priority]\n\n"
  187. "where <tag> is a log component tag (or * for all) and priority is:\n"
  188. " V Verbose\n"
  189. " D Debug\n"
  190. " I Info\n"
  191. " W Warn\n"
  192. " E Error\n"
  193. " F Fatal\n"
  194. " S Silent (supress all output)\n"
  195. "\n'*' means '*:d' and <tag> by itself means <tag>:v\n"
  196. "\nIf not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.\n"
  197. "If no filterspec is found, filter defaults to '*:I'\n"
  198. "\nIf not specified with -v, format is set from ANDROID_PRINTF_LOG\n"
  199. "or defaults to \"brief\"\n\n");
  200. }
  201. } /* namespace android */
  202. static int setLogFormat(const char * formatString)
  203. {
  204. static AndroidLogPrintFormat format;
  205. format = android_log_formatFromString(formatString);
  206. if (format == FORMAT_OFF) {
  207. // FORMAT_OFF means invalid string
  208. return -1;
  209. }
  210. android_log_setPrintFormat(g_logformat, format);
  211. return 0;
  212. }
  213. extern "C" void logprint_run_tests(void);
  214. int main (int argc, char **argv)
  215. {
  216. int logfd;
  217. int err;
  218. int hasSetLogFormat = 0;
  219. int clearLog = 0;
  220. int getLogSize = 0;
  221. int mode = O_RDONLY;
  222. char *log_device = strdup("/dev/"LOGGER_LOG_MAIN);
  223. const char *forceFilters = NULL;
  224. g_logformat = android_log_format_new();
  225. if (argc == 2 && 0 == strcmp(argv[1], "--test")) {
  226. logprint_run_tests();
  227. exit(0);
  228. }
  229. if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
  230. android::show_help(argv[0]);
  231. exit(0);
  232. }
  233. for (;;) {
  234. int ret;
  235. ret = getopt(argc, argv, "cdgsQf:r::n:v:b:B");
  236. if (ret < 0) {
  237. break;
  238. }
  239. switch(ret) {
  240. case 's':
  241. // default to all silent
  242. android_log_addFilterRule(g_logformat, "*:s");
  243. break;
  244. case 'c':
  245. clearLog = 1;
  246. mode = O_WRONLY;
  247. break;
  248. case 'd':
  249. mode |= O_NONBLOCK;
  250. break;
  251. case 'g':
  252. getLogSize = 1;
  253. break;
  254. case 'b':
  255. free(log_device);
  256. log_device =
  257. (char*) malloc(strlen(LOG_FILE_DIR) + strlen(optarg) + 1);
  258. strcpy(log_device, LOG_FILE_DIR);
  259. strcat(log_device, optarg);
  260. android::g_isBinary = (strcmp(optarg, "events") == 0);
  261. break;
  262. case 'B':
  263. android::g_printBinary = 1;
  264. break;
  265. case 'f':
  266. // redirect output to a file
  267. android::g_outputFileName = optarg;
  268. break;
  269. case 'r':
  270. if (optarg == NULL) {
  271. android::g_logRotateSizeKBytes
  272. = DEFAULT_LOG_ROTATE_SIZE_KBYTES;
  273. } else {
  274. long logRotateSize;
  275. char *lastDigit;
  276. if (!isdigit(optarg[0])) {
  277. fprintf(stderr,"Invalid parameter to -r\n");
  278. android::show_help(argv[0]);
  279. exit(-1);
  280. }
  281. android::g_logRotateSizeKBytes = atoi(optarg);
  282. }
  283. break;
  284. case 'n':
  285. if (!isdigit(optarg[0])) {
  286. fprintf(stderr,"Invalid parameter to -r\n");
  287. android::show_help(argv[0]);
  288. exit(-1);
  289. }
  290. android::g_maxRotatedLogs = atoi(optarg);
  291. break;
  292. case 'v':
  293. err = setLogFormat (optarg);
  294. if (err < 0) {
  295. fprintf(stderr,"Invalid parameter to -v\n");
  296. android::show_help(argv[0]);
  297. exit(-1);
  298. }
  299. hasSetLogFormat = 1;
  300. break;
  301. case 'Q':
  302. /* this is a *hidden* option used to start a version of logcat */
  303. /* in an emulated device only. it basically looks for androidboot.logcat= */
  304. /* on the kernel command line. If something is found, it extracts a log filter */
  305. /* and uses it to run the program. If nothing is found, the program should */
  306. /* quit immediately */
  307. #define KERNEL_OPTION "androidboot.logcat="
  308. #define CONSOLE_OPTION "androidboot.console="
  309. {
  310. int fd;
  311. char* logcat;
  312. char* console;
  313. int force_exit = 1;
  314. static char cmdline[1024];
  315. fd = open("/proc/cmdline", O_RDONLY);
  316. if (fd >= 0) {
  317. int n = read(fd, cmdline, sizeof(cmdline)-1 );
  318. if (n < 0) n = 0;
  319. cmdline[n] = 0;
  320. close(fd);
  321. } else {
  322. cmdline[0] = 0;
  323. }
  324. logcat = strstr( cmdline, KERNEL_OPTION );
  325. console = strstr( cmdline, CONSOLE_OPTION );
  326. if (logcat != NULL) {
  327. char* p = logcat + sizeof(KERNEL_OPTION)-1;;
  328. char* q = strpbrk( p, " \t\n\r" );;
  329. if (q != NULL)
  330. *q = 0;
  331. forceFilters = p;
  332. force_exit = 0;
  333. }
  334. /* if nothing found or invalid filters, exit quietly */
  335. if (force_exit)
  336. exit(0);
  337. /* redirect our output to the emulator console */
  338. if (console) {
  339. char* p = console + sizeof(CONSOLE_OPTION)-1;
  340. char* q = strpbrk( p, " \t\n\r" );
  341. char devname[64];
  342. int len;
  343. if (q != NULL) {
  344. len = q - p;
  345. } else
  346. len = strlen(p);
  347. len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
  348. fprintf(stderr, "logcat using %s (%d)\n", devname, len);
  349. if (len < (int)sizeof(devname)) {
  350. fd = open( devname, O_WRONLY );
  351. if (fd >= 0) {
  352. dup2(fd, 1);
  353. dup2(fd, 2);
  354. close(fd);
  355. }
  356. }
  357. }
  358. }
  359. break;
  360. default:
  361. fprintf(stderr,"Unrecognized Option\n");
  362. android::show_help(argv[0]);
  363. exit(-1);
  364. break;
  365. }
  366. }
  367. if (android::g_logRotateSizeKBytes != 0
  368. && android::g_outputFileName == NULL
  369. ) {
  370. fprintf(stderr,"-r requires -f as well\n");
  371. android::show_help(argv[0]);
  372. exit(-1);
  373. }
  374. android::setupOutput();
  375. if (hasSetLogFormat == 0) {
  376. const char* logFormat = getenv("ANDROID_PRINTF_LOG");
  377. if (logFormat != NULL) {
  378. err = setLogFormat(logFormat);
  379. if (err < 0) {
  380. fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
  381. logFormat);
  382. }
  383. }
  384. }
  385. if (forceFilters) {
  386. err = android_log_addFilterString(g_logformat, forceFilters);
  387. if (err < 0) {
  388. fprintf (stderr, "Invalid filter expression in -logcat option\n");
  389. exit(0);
  390. }
  391. } else if (argc == optind) {
  392. // Add from environment variable
  393. char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
  394. if (env_tags_orig != NULL) {
  395. err = android_log_addFilterString(g_logformat, env_tags_orig);
  396. if (err < 0) {
  397. fprintf(stderr, "Invalid filter expression in"
  398. " ANDROID_LOG_TAGS\n");
  399. android::show_help(argv[0]);
  400. exit(-1);
  401. }
  402. }
  403. } else {
  404. // Add from commandline
  405. for (int i = optind ; i < argc ; i++) {
  406. err = android_log_addFilterString(g_logformat, argv[i]);
  407. if (err < 0) {
  408. fprintf (stderr, "Invalid filter expression '%s'\n", argv[i]);
  409. android::show_help(argv[0]);
  410. exit(-1);
  411. }
  412. }
  413. }
  414. logfd = open(log_device, mode);
  415. if (logfd < 0) {
  416. fprintf(stderr, "Unable to open log device '%s': %s\n",
  417. log_device, strerror(errno));
  418. exit(EXIT_FAILURE);
  419. }
  420. if (clearLog) {
  421. int ret;
  422. ret = android::clearLog(logfd);
  423. if (ret) {
  424. perror("ioctl");
  425. exit(EXIT_FAILURE);
  426. }
  427. return 0;
  428. }
  429. if (getLogSize) {
  430. int size, readable;
  431. size = android::getLogSize(logfd);
  432. if (size < 0) {
  433. perror("ioctl");
  434. exit(EXIT_FAILURE);
  435. }
  436. readable = android::getLogReadableSize(logfd);
  437. if (readable < 0) {
  438. perror("ioctl");
  439. exit(EXIT_FAILURE);
  440. }
  441. printf("ring buffer is %dKb (%dKb consumed), "
  442. "max entry is %db, max payload is %db\n",
  443. size / 1024, readable / 1024,
  444. (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
  445. return 0;
  446. }
  447. //LOG_EVENT_INT(10, 12345);
  448. //LOG_EVENT_LONG(11, 0x1122334455667788LL);
  449. //LOG_EVENT_STRING(0, "whassup, doc?");
  450. if (android::g_isBinary)
  451. android::g_eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
  452. android::readLogLines(logfd);
  453. return 0;
  454. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/674529
推荐阅读
相关标签
  

闽ICP备14008679号