]> git.itanic.dy.fi Git - rrdd/blob - debug.c
fe0fc9b139ba661d1c42df4adf7966f47020c985
[rrdd] / debug.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <time.h>
5 #include <unistd.h>
6 #include <stdarg.h>
7 #include <pthread.h>
8
9 #include "process.h"
10 #include "debug.h"
11
12 const char red_color[] = {
13         0x1b, 0x5b, 0x30, 0x3b, 0x33, 0x31, 0x3b, 0x34, 0x30, 0x6d, 0x0,
14 };
15
16 const char green_color[] = {
17         0x1b, 0x5b, 0x30, 0x3b, 0x33, 0x32, 0x3b, 0x34, 0x30, 0x6d, 0x0,
18 };
19
20 const char normal_color[] = {
21         0x1b, 0x5b, 0x30, 0x3b, 0x33, 0x37, 0x3b, 0x34, 0x30, 0x6d, 0x0,
22 };
23
24 int trace_level = TRACE_INFO;
25 static int logfile_fd = STDERR_FILENO;
26
27 static const char *assign_color(int color)
28 {
29         switch (color) {
30         case 1:
31                 return red_color;
32         case 2:
33                 return green_color;
34         default:
35         return normal_color;
36         }
37 }
38
39 void print_trace(const char *file, int line, int color, int l,
40                 const char *fmt, ...)
41 {
42         va_list args;
43         time_t t = time(0);
44         char time[32];
45         char trace[1024];
46         char all_trace[1538];
47         char thread_name[16];
48         const char *color_str = assign_color(color);
49         int ret;
50
51         if (l > trace_level)
52                 return;
53
54         va_start(args, fmt);
55         vsnprintf(trace, sizeof(trace), fmt, args);
56         va_end(args);
57
58         strftime(time, sizeof(time), "%d.%m.%Y %T", localtime(&t));
59
60         pthread_getname_np(pthread_self(), thread_name, sizeof(thread_name));
61
62         ret = snprintf(all_trace, sizeof(all_trace),
63                 "%s%s [%5d.%d] %s %s:%d %s %s",
64                 color_str, time,
65                 getpid(), get_parent_count(),
66                 thread_name,
67                 file, line, normal_color, trace);
68
69         ret = write(logfile_fd, all_trace, ret);
70         /*
71          * If write failed, well, not much point in trying to print a
72          * trace about it.. So we just ignore the return value
73          */
74 }
75
76 int open_log_file(const char *logfile)
77 {
78         int fd;
79
80         pr_info("Switching logging to file: %s\n", logfile);
81
82         fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0666);
83         if (fd < 0) {
84                 pr_err("Failed to open logfile %s: %m\n", logfile);
85                 return fd;
86         }
87
88         if (logfile_fd != STDERR_FILENO)
89                 close(logfile_fd);
90         logfile_fd = fd;
91
92         pr_info("Opened file %s for logging\n", logfile);
93
94         return 0;
95 }