From 18e86fbee105f594beaacf00069dc43a6551b428 Mon Sep 17 00:00:00 2001 From: Timo Kokkonen Date: Fri, 30 Nov 2012 18:11:01 +0200 Subject: [PATCH] debug: Add support for log files A new command line argument --logfile or -l is now supported for logging purposes. Signed-off-by: Timo Kokkonen --- debug.c | 37 +++++++++++++++++++++++++++++++++++-- debug.h | 2 ++ main.c | 7 ++++++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/debug.c b/debug.c index 6c7042e..55fdd14 100644 --- a/debug.c +++ b/debug.c @@ -1,3 +1,6 @@ +#include +#include +#include #include #include #include @@ -18,6 +21,7 @@ const char normal_color[] = { }; int trace_level = 1; +int logfile_fd = STDERR_FILENO; static const char *assign_color(int color) { @@ -38,7 +42,9 @@ void print_trace(const char *file, int line, int color, int l, time_t t = time(0); char time[32]; char trace[1024]; + char all_trace[1538]; const char *color_str = assign_color(color); + int ret; if (l > trace_level) return; @@ -49,9 +55,36 @@ void print_trace(const char *file, int line, int color, int l, strftime(time, sizeof(time), "%d.%m.%Y %T", localtime(&t)); - fprintf(stderr, "%s%s [%5d.%d] %s:%d %s %s", + ret = snprintf(all_trace, sizeof(all_trace), + "%s%s [%5d.%d] %s:%d %s %s", color_str, time, getpid(), get_parent_count(), file, line, normal_color, trace); - fflush(stderr); + + ret = write(logfile_fd, all_trace, ret); + /* + * If write failed, well, not much point in trying to print a + * trace about it.. So we just ignore the return value + */ +} + +int open_log_file(const char *logfile) +{ + int fd; + + pr_info("Switching logging to file: %s\n", logfile); + + fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0666); + if (fd < 0) { + pr_err("Failed to open logfile %s: %m\n", logfile); + return fd; + } + + if (logfile_fd != STDERR_FILENO) + close(logfile_fd); + logfile_fd = fd; + + pr_info("Opened file %s for logging\n", logfile); + + return 0; } diff --git a/debug.h b/debug.h index 54e81a2..1dd11f9 100644 --- a/debug.h +++ b/debug.h @@ -12,4 +12,6 @@ print_trace(const char *file, int line, int color, int l, #define pr_err(arg...) print_trace(__FILE__, __LINE__, 1, 0, arg) #define pr_info(arg...) print_trace(__FILE__, __LINE__, 2, 1, arg) +int open_log_file(const char *logfile); + #endif diff --git a/main.c b/main.c index 75eddf3..55e1ef3 100644 --- a/main.c +++ b/main.c @@ -25,9 +25,10 @@ int read_args(int argc, char *argv[], struct user_options *opts) static struct option long_options[] = { { .val = 'j', .has_arg = 1, .name = "jobs", }, { .val = 'c', .has_arg = 1, .name = "config", }, + { .val = 'l', .has_arg = 1, .name = "log-file", }, { }, }; - char short_options[] = "j:c:"; + char short_options[] = "j:c:l:"; while (1) { c = getopt_long(argc, argv, short_options, long_options, @@ -45,6 +46,10 @@ int read_args(int argc, char *argv[], struct user_options *opts) opts->config_file = optarg; break; + case 'l': + open_log_file(optarg); + break; + case '?': return -1; } -- 2.44.0