]> git.sur5r.net Git - i3/i3/blob - src/log.c
Merge branch 'master' into next
[i3/i3] / src / log.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * log.c: Setting of loglevels, logging functions.
8  *
9  */
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdbool.h>
14 #include <stdlib.h>
15 #include <sys/time.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <sys/mman.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21
22 #include "util.h"
23 #include "log.h"
24 #include "i3.h"
25 #include "libi3.h"
26
27 /* loglevels.h is autogenerated at make time */
28 #include "loglevels.h"
29
30 static uint64_t loglevel = 0;
31 static bool verbose = false;
32 static FILE *errorfile;
33 char *errorfilename;
34
35 /* SHM logging variables */
36
37 /* The name for the SHM (/i3-log-%pid). Will end up on /dev/shm on most
38  * systems. Global so that we can clean up at exit. */
39 char *shmlogname = "";
40 /* Size limit for the SHM log, by default 25 MiB. Can be overwritten using the
41  * flag --shmlog-size. */
42 int shmlog_size = 0;
43 /* If enabled, logbuffer will point to a memory mapping of the i3 SHM log. */
44 static char *logbuffer;
45 /* A pointer (within logbuffer) where data will be written to next. */
46 static char *logwalk;
47 /* A pointer to the byte where we last wrapped. Necessary to not print the
48  * left-overs at the end of the ringbuffer. */
49 static char *loglastwrap;
50 /* Size (in bytes) of the i3 SHM log. */
51 static int logbuffer_size;
52 /* File descriptor for shm_open. */
53 static int logbuffer_shm;
54
55 /*
56  * Initializes logging by creating an error logfile in /tmp (or
57  * XDG_RUNTIME_DIR, see get_process_filename()).
58  *
59  * Will be called twice if --shmlog-size is specified.
60  *
61  */
62 void init_logging() {
63     if (!errorfilename) {
64         if (!(errorfilename = get_process_filename("errorlog")))
65             ELOG("Could not initialize errorlog\n");
66         else {
67             errorfile = fopen(errorfilename, "w");
68             if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
69                 ELOG("Could not set close-on-exec flag\n");
70             }
71         }
72     }
73
74     /* If this is a debug build (not a release version), we will enable SHM
75      * logging by default, unless the user turned it off explicitly. */
76     if (logbuffer == NULL && shmlog_size > 0) {
77         /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
78          * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
79          * At the moment (2011-12-10), no testcase leads to an i3 log
80          * of more than ~ 600 KiB. */
81         long long physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
82                                                   sysconf(_SC_PAGESIZE);
83         logbuffer_size = min(physical_mem_bytes * 0.01, shmlog_size);
84         sasprintf(&shmlogname, "/i3-log-%d", getpid());
85         logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE);
86         if (logbuffer_shm == -1) {
87             ELOG("Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
88             return;
89         }
90
91         if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
92             close(logbuffer_shm);
93             shm_unlink("/i3-log-");
94             ELOG("Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
95             return;
96         }
97
98         logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
99         if (logbuffer == MAP_FAILED) {
100             close(logbuffer_shm);
101             shm_unlink("/i3-log-");
102             ELOG("Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
103             logbuffer = NULL;
104             return;
105         }
106         logwalk = logbuffer;
107         loglastwrap = logbuffer + logbuffer_size;
108     }
109 }
110
111 /*
112  * Set verbosity of i3. If verbose is set to true, informative messages will
113  * be printed to stdout. If verbose is set to false, only errors will be
114  * printed.
115  *
116  */
117 void set_verbosity(bool _verbose) {
118     verbose = _verbose;
119 }
120
121 /*
122  * Enables the given loglevel.
123  *
124  */
125 void add_loglevel(const char *level) {
126     /* Handle the special loglevel "all" */
127     if (strcasecmp(level, "all") == 0) {
128         loglevel = UINT64_MAX;
129         return;
130     }
131
132     for (int i = 0; i < sizeof(loglevels) / sizeof(char*); i++) {
133         if (strcasecmp(loglevels[i], level) != 0)
134             continue;
135
136         /* The position in the array (plus one) is the amount of times
137          * which we need to shift 1 to the left to get our bitmask for
138          * the specific loglevel. */
139         loglevel |= (1 << (i+1));
140         break;
141     }
142 }
143
144 /*
145  * Returns the offsets for the next write and for the last wrap.
146  * Necessary to print the i3 SHM log in the correct order.
147  *
148  */
149 void get_log_markers(int *offset_next_write, int *offset_last_wrap, int *size) {
150     *offset_next_write = (logwalk - logbuffer);
151     *offset_last_wrap = (loglastwrap - logbuffer);
152     *size = logbuffer_size;
153 }
154
155 /*
156  * Logs the given message to stdout (if print is true) while prefixing the
157  * current time to it. Additionally, the message will be saved in the i3 SHM
158  * log if enabled.
159  * This is to be called by *LOG() which includes filename/linenumber/function.
160  *
161  */
162 static void vlog(const bool print, const char *fmt, va_list args) {
163     /* Precisely one page to not consume too much memory but to hold enough
164      * data to be useful. */
165     static char message[4096];
166     static struct tm result;
167     static time_t t;
168     static struct tm *tmp;
169     static size_t len;
170
171     /* Get current time */
172     t = time(NULL);
173     /* Convert time to local time (determined by the locale) */
174     tmp = localtime_r(&t, &result);
175     /* Generate time prefix */
176     len = strftime(message, sizeof(message), "%x %X - ", tmp);
177
178     /*
179      * logbuffer  print
180      * ----------------
181      *  true      true   format message, save, print
182      *  true      false  format message, save
183      *  false     true   print message only
184      *  false     false  INVALID, never called
185      */
186     if (!logbuffer) {
187 #ifdef DEBUG_TIMING
188         struct timeval tv;
189         gettimeofday(&tv, NULL);
190         printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
191 #else
192         printf("%s", message);
193 #endif
194         vprintf(fmt, args);
195     } else {
196         len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
197         if (len == sizeof(message)) {
198             fprintf(stderr, "BUG: single log message > 4k\n");
199         }
200         /* If there is no space for the current message (plus trailing
201          * nullbyte) in the ringbuffer, we need to wrap and write to the
202          * beginning again. */
203         if ((len+1) >= (logbuffer_size - (logwalk - logbuffer))) {
204             loglastwrap = logwalk;
205             logwalk = logbuffer;
206         }
207
208         /* Copy the buffer, terminate it, move the write pointer to the byte after
209          * our current message. */
210         strncpy(logwalk, message, len);
211         logwalk[len] = '\0';
212         logwalk += len + 1;
213
214         if (print)
215             fwrite(message, len, 1, stdout);
216     }
217 }
218
219 /*
220  * Logs the given message to stdout while prefixing the current time to it,
221  * but only if verbose mode is activated.
222  *
223  */
224 void verboselog(char *fmt, ...) {
225     va_list args;
226
227     if (!logbuffer && !verbose)
228         return;
229
230     va_start(args, fmt);
231     vlog(verbose, fmt, args);
232     va_end(args);
233 }
234
235 /*
236  * Logs the given message to stdout while prefixing the current time to it.
237  *
238  */
239 void errorlog(char *fmt, ...) {
240     va_list args;
241
242     va_start(args, fmt);
243     vlog(true, fmt, args);
244     va_end(args);
245
246     /* also log to the error logfile, if opened */
247     va_start(args, fmt);
248     vfprintf(errorfile, fmt, args);
249     fflush(errorfile);
250     va_end(args);
251 }
252
253 /*
254  * Logs the given message to stdout while prefixing the current time to it,
255  * but only if the corresponding debug loglevel was activated.
256  * This is to be called by DLOG() which includes filename/linenumber
257  *
258  */
259 void debuglog(uint64_t lev, char *fmt, ...) {
260     va_list args;
261
262     if (!logbuffer && !(loglevel & lev))
263         return;
264
265     va_start(args, fmt);
266     vlog((loglevel & lev), fmt, args);
267     va_end(args);
268 }