2 #define I3__FILE__ "log.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
9 * log.c: Logging functions.
24 #if defined(__APPLE__)
25 #include <sys/types.h>
26 #include <sys/sysctl.h>
35 static bool debug_logging = false;
36 static bool verbose = false;
37 static FILE *errorfile;
40 /* SHM logging variables */
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. */
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. */
52 /* A pointer to the shmlog header */
53 static i3_shmlog_header *header;
54 /* A pointer to the byte where we last wrapped. Necessary to not print the
55 * left-overs at the end of the ringbuffer. */
56 static char *loglastwrap;
57 /* Size (in bytes) of the i3 SHM log. */
58 static int logbuffer_size;
59 /* File descriptor for shm_open. */
60 static int logbuffer_shm;
63 * Writes the offsets for the next write and for the last wrap to the
65 * Necessary to print the i3 SHM log in the correct order.
68 static void store_log_markers(void) {
69 header->offset_next_write = (logwalk - logbuffer);
70 header->offset_last_wrap = (loglastwrap - logbuffer);
71 header->size = logbuffer_size;
75 * Initializes logging by creating an error logfile in /tmp (or
76 * XDG_RUNTIME_DIR, see get_process_filename()).
78 * Will be called twice if --shmlog-size is specified.
81 void init_logging(void) {
83 if (!(errorfilename = get_process_filename("errorlog")))
84 fprintf(stderr, "Could not initialize errorlog\n");
86 errorfile = fopen(errorfilename, "w");
87 if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
88 fprintf(stderr, "Could not set close-on-exec flag\n");
92 /* Start SHM logging if shmlog_size is > 0. shmlog_size is SHMLOG_SIZE by
93 * default on development versions, and 0 on release versions. If it is
94 * not > 0, the user has turned it off, so let's close the logbuffer. */
95 if (shmlog_size > 0 && logbuffer == NULL)
97 else if (shmlog_size <= 0 && logbuffer)
99 atexit(purge_zerobyte_logfile);
103 * Opens the logbuffer.
106 void open_logbuffer(void) {
107 /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
108 * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
109 * At the moment (2011-12-10), no testcase leads to an i3 log
110 * of more than ~ 600 KiB. */
111 long long physical_mem_bytes;
112 #if defined(__APPLE__)
113 int mib[2] = { CTL_HW, HW_MEMSIZE };
114 size_t length = sizeof(long long);
115 sysctl(mib, 2, &physical_mem_bytes, &length, NULL, 0);
117 physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
118 sysconf(_SC_PAGESIZE);
120 logbuffer_size = min(physical_mem_bytes * 0.01, shmlog_size);
121 #if defined(__FreeBSD__)
122 sasprintf(&shmlogname, "/tmp/i3-log-%d", getpid());
124 sasprintf(&shmlogname, "/i3-log-%d", getpid());
126 logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
127 if (logbuffer_shm == -1) {
128 fprintf(stderr, "Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
132 if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
133 close(logbuffer_shm);
134 shm_unlink(shmlogname);
135 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
139 logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
140 if (logbuffer == MAP_FAILED) {
142 fprintf(stderr, "Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
146 /* Initialize with 0-bytes, just to be sure… */
147 memset(logbuffer, '\0', logbuffer_size);
149 header = (i3_shmlog_header*)logbuffer;
151 pthread_condattr_t cond_attr;
152 pthread_condattr_init(&cond_attr);
153 if (pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED) != 0)
154 fprintf(stderr, "pthread_condattr_setpshared() failed, i3-dump-log -f will not work!\n");
155 pthread_cond_init(&(header->condvar), &cond_attr);
157 logwalk = logbuffer + sizeof(i3_shmlog_header);
158 loglastwrap = logbuffer + logbuffer_size;
163 * Closes the logbuffer.
166 void close_logbuffer(void) {
167 close(logbuffer_shm);
168 shm_unlink(shmlogname);
174 * Set verbosity of i3. If verbose is set to true, informative messages will
175 * be printed to stdout. If verbose is set to false, only errors will be
179 void set_verbosity(bool _verbose) {
187 void set_debug_logging(const bool _debug_logging) {
188 debug_logging = _debug_logging;
192 * Logs the given message to stdout (if print is true) while prefixing the
193 * current time to it. Additionally, the message will be saved in the i3 SHM
195 * This is to be called by *LOG() which includes filename/linenumber/function.
198 static void vlog(const bool print, const char *fmt, va_list args) {
199 /* Precisely one page to not consume too much memory but to hold enough
200 * data to be useful. */
201 static char message[4096];
202 static struct tm result;
204 static struct tm *tmp;
207 /* Get current time */
209 /* Convert time to local time (determined by the locale) */
210 tmp = localtime_r(&t, &result);
211 /* Generate time prefix */
212 len = strftime(message, sizeof(message), "%x %X - ", tmp);
217 * true true format message, save, print
218 * true false format message, save
219 * false true print message only
220 * false false INVALID, never called
225 gettimeofday(&tv, NULL);
226 printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
228 printf("%s", message);
232 len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
233 if (len >= sizeof(message)) {
234 fprintf(stderr, "BUG: single log message > 4k\n");
237 /* If there is no space for the current message in the ringbuffer, we
238 * need to wrap and write to the beginning again. */
239 if (len >= (logbuffer_size - (logwalk - logbuffer))) {
240 loglastwrap = logwalk;
241 logwalk = logbuffer + sizeof(i3_shmlog_header);
243 header->wrap_count++;
246 /* Copy the buffer, move the write pointer to the byte after our
247 * current message. */
248 strncpy(logwalk, message, len);
253 /* Wake up all (i3-dump-log) processes waiting for condvar. */
254 pthread_cond_broadcast(&(header->condvar));
257 fwrite(message, len, 1, stdout);
262 * Logs the given message to stdout while prefixing the current time to it,
263 * but only if verbose mode is activated.
266 void verboselog(char *fmt, ...) {
269 if (!logbuffer && !verbose)
273 vlog(verbose, fmt, args);
278 * Logs the given message to stdout while prefixing the current time to it.
281 void errorlog(char *fmt, ...) {
285 vlog(true, fmt, args);
288 /* also log to the error logfile, if opened */
290 vfprintf(errorfile, fmt, args);
296 * Logs the given message to stdout while prefixing the current time to it,
297 * but only if debug logging was activated.
298 * This is to be called by DLOG() which includes filename/linenumber
301 void debuglog(char *fmt, ...) {
304 if (!logbuffer && !(debug_logging))
308 vlog(debug_logging, fmt, args);
313 * Deletes the unused log files. Useful if i3 exits immediately, eg.
314 * because --get-socketpath was called. We don't care for syscall
315 * failures. This function is invoked automatically when exiting.
317 void purge_zerobyte_logfile(void) {
324 /* don't delete the log file if it contains something */
325 if ((stat(errorfilename, &st)) == -1 || st.st_size > 0)
328 if (unlink(errorfilename) == -1)
331 if ((slash = strrchr(errorfilename, '/')) != NULL) {
333 /* possibly fails with ENOTEMPTY if there are files (or
335 rmdir(errorfilename);