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