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