2 * Copyright (c) 2005-2008, The Android Open Source Project
3 * Copyright (c) 2009-2013, Samsung Electronics Co., Ltd. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
32 #include <arpa/inet.h>
38 #define DEFAULT_LOG_ROTATE_SIZE_KBYTES 16
39 #define DEFAULT_MAX_ROTATED_LOGS 4
41 #define LOG_FILE_DIR "/dev/log_"
43 static log_format* g_logformat;
44 static bool g_nonblock = false;
45 static int g_tail_lines = 0;
47 static const char * g_output_filename = NULL;
48 static int g_log_rotate_size_kbytes = 0; // 0 means "no log rotation"
49 static int g_max_rotated_logs = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded"
50 static int g_outfd = -1;
51 static off_t g_out_byte_count = 0;
52 static int g_dev_count = 0;
54 struct queued_entry_t {
56 unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
57 struct logger_entry entry __attribute__((aligned(4)));
59 struct queued_entry_t* next;
62 static int cmp(struct queued_entry_t* a, struct queued_entry_t* b)
64 int n = a->entry.sec - b->entry.sec;
69 return a->entry.nsec - b->entry.nsec;
77 struct queued_entry_t* queue;
78 struct log_device_t* next;
81 static void enqueue(struct log_device_t* device, struct queued_entry_t* entry)
83 if( device->queue == NULL)
85 device->queue = entry;
89 struct queued_entry_t** e = &device->queue;
90 while(*e && cmp(entry, *e) >= 0 )
99 static int open_logfile (const char *pathname)
101 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
104 static void rotate_logs()
111 // Can't rotate logs if we're not outputting to a file
112 if (g_output_filename == NULL) {
118 for (i = g_max_rotated_logs ; i > 0 ; i--)
120 snprintf(file1, 255, "%s.%d", g_output_filename, i);
123 snprintf(file0, 255, "%s", g_output_filename);
125 snprintf(file0, 255, "%s.%d", g_output_filename, i - 1);
128 err = rename (file0, file1);
130 if (err < 0 && errno != ENOENT) {
131 perror("while rotating log files");
135 g_outfd = open_logfile (g_output_filename);
138 perror ("couldn't open output file");
142 g_out_byte_count = 0;
147 static void processBuffer(struct log_device_t* dev, struct logger_entry *buf)
149 int bytes_written = 0;
154 err = log_process_log_buffer(buf, &entry);
160 if (log_should_print_line(g_logformat, entry.tag, entry.priority)) {
161 if (false && g_dev_count > 1) {
163 mgs_buf[0] = dev->device[0];
165 bytes_written = write(g_outfd, mgs_buf, 2);
166 if (bytes_written < 0)
168 perror("output error");
173 bytes_written = log_print_log_line(g_logformat, g_outfd, &entry);
175 if (bytes_written < 0)
177 perror("output error");
182 g_out_byte_count += bytes_written;
184 if (g_log_rotate_size_kbytes > 0 && (g_out_byte_count / 1024) >= g_log_rotate_size_kbytes)
190 //fprintf (stderr, "Error processing record\n");
194 static void chooseFirst(struct log_device_t* dev, struct log_device_t** firstdev)
196 for (*firstdev = NULL; dev != NULL; dev = dev->next) {
197 if (dev->queue != NULL && (*firstdev == NULL || cmp(dev->queue, (*firstdev)->queue) < 0))
204 static void maybePrintStart(struct log_device_t* dev) {
207 if (g_dev_count > 1 ) {
209 snprintf(buf, sizeof(buf), "--------- beginning of %s\n", dev->device);
210 if (write(g_outfd, buf, strlen(buf)) < 0) {
211 perror("output error");
218 static void skipNextEntry(struct log_device_t* dev) {
219 maybePrintStart(dev);
220 struct queued_entry_t* entry = dev->queue;
221 dev->queue = entry->next;
225 static void printNextEntry(struct log_device_t* dev)
227 maybePrintStart(dev);
228 processBuffer(dev, &dev->queue->entry);
233 static void read_log_lines(struct log_device_t* devices)
235 struct log_device_t* dev;
238 int queued_lines = 0;
239 bool sleep = false; // for exit immediately when log buffer is empty and g_nonblock value is true.
244 for (dev=devices; dev; dev = dev->next) {
252 struct timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
254 for (dev=devices; dev; dev = dev->next) {
255 FD_SET(dev->fd, &readset);
257 result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
258 } while (result == -1 && errno == EINTR);
261 for (dev=devices; dev; dev = dev->next) {
262 if (FD_ISSET(dev->fd, &readset)) {
263 struct queued_entry_t* entry = (struct queued_entry_t *)malloc(sizeof( struct queued_entry_t));
265 fprintf(stderr,"Can't malloc queued_entry\n");
270 /* NOTE: driver guarantees we read exactly one full entry */
271 ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
273 if (errno == EINTR) {
277 if (errno == EAGAIN) {
281 perror("dlogutil read");
286 fprintf(stderr, "read: Unexpected EOF!\n");
289 else if (entry->entry.len != ret - sizeof(struct logger_entry)) {
291 fprintf(stderr, "read: unexpected length. Expected %d, got %d\n",
292 entry->entry.len, ret - sizeof(struct logger_entry));
295 entry->entry.msg[entry->entry.len] = '\0';
303 // we did our short timeout trick and there's nothing new
304 // print everything we have and wait for more data
307 chooseFirst(devices, &dev);
311 if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
319 // the caller requested to just dump the log and exit
324 // print all that aren't the last in their list
326 while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
327 chooseFirst(devices, &dev);
328 if (dev == NULL || dev->queue->next == NULL) {
331 if (g_tail_lines == 0) {
346 static int clear_log(int logfd)
348 return ioctl(logfd, LOGGER_FLUSH_LOG);
351 /* returns the total size of the log's ring buffer */
352 static int get_log_size(int logfd)
354 return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
357 /* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
358 static int get_log_readable_size(int logfd)
360 return ioctl(logfd, LOGGER_GET_LOG_LEN);
363 static void setup_output()
366 if (g_output_filename == NULL) {
367 g_outfd = STDOUT_FILENO;
372 g_outfd = open_logfile (g_output_filename);
375 perror ("couldn't open output file");
378 if (fstat(g_outfd, &statbuf) == -1)
379 g_out_byte_count = 0;
381 g_out_byte_count = statbuf.st_size;
385 static int set_log_format(const char * formatString)
387 static log_print_format format;
389 format = log_format_from_string(formatString);
391 if (format == FORMAT_OFF) {
392 // FORMAT_OFF means invalid string
396 log_set_print_format(g_logformat, format);
401 static void show_help(const char *cmd)
403 fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
405 fprintf(stderr, "options include:\n"
406 " -s Set default filter to silent.\n"
407 " Like specifying filterspec '*:s'\n"
408 " -f <filename> Log to file. Default to stdout\n"
409 " -r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f\n"
410 " -n <count> Sets max number of rotated logs to <count>, default 4\n"
411 " -v <format> Sets the log print format, where <format> is one of:\n\n"
412 " brief(by default) process tag thread raw time threadtime long\n\n"
413 " -c clear (flush) the entire log and exit, conflicts with '-g'\n"
414 " -d dump the log and then exit (don't block)\n"
415 " -t <count> print only the most recent <count> lines (implies -d)\n"
416 " -g get the size of the log's ring buffer and exit, conflicts with '-c'\n"
417 " -b <buffer> request alternate ring buffer\n"
418 " ('main' (default), 'radio', 'system')");
421 fprintf(stderr,"\nfilterspecs are a series of \n"
422 " <tag>[:priority]\n\n"
423 "where <tag> is a log component tag (or * for all) and priority is:\n"
430 " S Silent (supress all output)\n"
431 "\n'*' means '*:D' and <tag> by itself means <tag>:V\n"
432 "If no filterspec is found, filter defaults to '*:I'\n\n");
437 * free one log_device_t and it doesn't take care of chain so it
438 * may break the chain list
440 static void log_devices_free(struct log_device_t *dev)
449 while (dev->queue->next) {
450 struct queued_entry_t *tmp = dev->queue->next;
451 dev->queue->next = tmp->next;
463 * free all the nodes after the "dev" and includes itself
465 static void log_devices_chain_free(struct log_device_t *dev)
471 struct log_device_t *tmp = dev->next;
472 dev->next = tmp->next;
473 log_devices_free(tmp);
476 log_devices_free(dev);
482 * create a new log_device_t instance but don't care about
483 * the device node accessable or not
485 static struct log_device_t *log_devices_new(const char *path)
487 struct log_device_t *new;
489 if (!path || strlen(path) <= 0)
492 new = malloc(sizeof(*new));
494 fprintf(stderr, "out of memory\n");
498 new->device = strdup(path);
500 new->printed = false;
509 * add a new device to the tail of chain
511 static int log_devices_add_to_tail(struct log_device_t *devices, struct log_device_t *new)
513 struct log_device_t *tail = devices;
515 if (!devices || !new)
527 int main(int argc, char **argv)
530 int has_set_log_format = 0;
531 int is_clear_log = 0;
535 // const char *forceFilters = NULL;
536 struct log_device_t* devices = NULL;
537 struct log_device_t* dev;
539 g_logformat = (log_format *)log_format_new();
541 if (argc == 2 && 0 == strcmp(argv[1], "--test")) {
542 logprint_run_tests();
546 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
554 ret = getopt(argc, argv, "cdt:gsf:r:n:v:b:D");
562 // default to all silent
563 log_add_filter_rule(g_logformat, "*:s");
577 g_tail_lines = atoi(optarg);
587 if (asprintf(&buf, LOG_FILE_DIR "%s", optarg) == -1) {
588 asprintf(stderr,"Can't malloc LOG_FILE_DIR\n");
592 dev = log_devices_new(buf);
594 fprintf(stderr,"Can't add log device: %s\n", buf);
598 if (log_devices_add_to_tail(devices, dev)) {
599 fprintf(stderr, "Open log device %s failed\n", buf);
610 // redirect output to a file
612 g_output_filename = optarg;
617 // if (optarg == NULL) {
618 // fprintf(stderr,"optarg == null\n");
619 // g_log_rotate_size_kbytes = DEFAULT_LOG_ROTATE_SIZE_KBYTES;
621 //long logRotateSize;
624 if (!isdigit(optarg[0])) {
625 fprintf(stderr,"Invalid parameter to -r\n");
629 g_log_rotate_size_kbytes = atoi(optarg);
634 if (!isdigit(optarg[0])) {
635 fprintf(stderr,"Invalid parameter to -r\n");
640 g_max_rotated_logs = atoi(optarg);
644 err = set_log_format (optarg);
646 fprintf(stderr,"Invalid parameter to -v\n");
651 has_set_log_format = 1;
655 fprintf(stderr,"Unrecognized Option\n");
662 /* get log size conflicts with write mode */
663 if (getLogSize && mode != O_RDONLY) {
669 devices = log_devices_new("/dev/"LOGGER_LOG_MAIN);
670 if (devices == NULL) {
671 fprintf(stderr,"Can't add log device: %s\n", LOGGER_LOG_MAIN);
677 (mode == O_RDONLY) ? R_OK : 0
678 | (mode == O_WRONLY) ? W_OK : 0;
680 // only add this if it's available
681 if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
682 if (log_devices_add_to_tail(devices, log_devices_new("/dev/"LOGGER_LOG_SYSTEM))) {
683 fprintf(stderr,"Can't add log device: %s\n", LOGGER_LOG_SYSTEM);
688 if (0 == access("/dev/"LOGGER_LOG_APPS, accessmode)) {
689 if (log_devices_add_to_tail(devices, log_devices_new("/dev/"LOGGER_LOG_APPS))) {
690 fprintf(stderr,"Can't add log device: %s\n", LOGGER_LOG_APPS);
695 // only add this if it's available
697 if ((fd = open("/dev/"LOGGER_LOG_SYSTEM, mode)) != -1) {
698 devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
699 devices->next->device = strdup("/dev/"LOGGER_LOG_SYSTEM);
700 devices->next->fd = -1;
701 devices->next->printed = false;
702 devices->next->queue = NULL;
703 devices->next->next = NULL;
711 if (g_log_rotate_size_kbytes != 0 && g_output_filename == NULL)
713 fprintf(stderr,"-r requires -f as well\n");
721 if (has_set_log_format == 0) {
722 err = set_log_format("brief");
725 const char* logFormat = getenv("DLOG_PRINTF_LOG");
727 if (logFormat != NULL) {
728 err = set_log_format("brief");
731 fprintf(stderr, "invalid format in DLOG_PRINTF_LOG '%s'\n", logFormat);
736 err = log_add_filter_string(g_logformat, forceFilters);
738 fprintf (stderr, "Invalid filter expression in -logcat option\n");
741 } else if (argc == optind) {
742 // Add from environment variable
743 char *env_tags_orig = getenv("DLOG_LOG_TAGS");
745 if (env_tags_orig != NULL) {
746 err = log_add_filter_string(g_logformat, env_tags_orig);
749 fprintf(stderr, "Invalid filter expression in DLOG_LOG_TAGS\n");
755 // Add from commandline
757 fprintf(stderr,"arc = %d, optind = %d ,Kb %d, rotate %d\n", argc, optind,g_log_rotate_size_kbytes,g_max_rotated_logs);
761 // Add from environment variable
762 //char *env_tags_orig = getenv("DLOG_TAGS");
763 log_add_filter_string(g_logformat, "*:d");
768 for (i = optind ; i < argc ; i++) {
769 err = log_add_filter_string(g_logformat, argv[i]);
772 fprintf (stderr, "Invalid filter expression '%s'\n", argv[i]);
783 dev->fd = open(dev->device, mode);
785 fprintf(stderr, "Unable to open log device '%s': %s\n",
786 dev->device, strerror(errno));
792 ret = clear_log(dev->fd);
802 size = get_log_size(dev->fd);
808 readable = get_log_readable_size(dev->fd);
814 printf("%s: ring buffer is %dKb (%dKb consumed), "
815 "max entry is %db, max payload is %db\n", dev->device,
816 size / 1024, readable / 1024,
817 (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
831 read_log_lines(devices);
833 log_devices_chain_free(devices);