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