2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
7 * log.c: Logging functions.
23 #if !defined(__OpenBSD__)
33 #if defined(__APPLE__)
34 #include <sys/sysctl.h>
37 static bool debug_logging = false;
38 static bool verbose = false;
39 static FILE *errorfile;
42 /* SHM logging variables */
44 /* The name for the SHM (/i3-log-%pid). Will end up on /dev/shm on most
45 * systems. Global so that we can clean up at exit. */
46 char *shmlogname = "";
47 /* Size limit for the SHM log, by default 25 MiB. Can be overwritten using the
48 * flag --shmlog-size. */
50 /* If enabled, logbuffer will point to a memory mapping of the i3 SHM log. */
51 static char *logbuffer;
52 /* A pointer (within logbuffer) where data will be written to next. */
54 /* A pointer to the shmlog header */
55 static i3_shmlog_header *header;
56 /* A pointer to the byte where we last wrapped. Necessary to not print the
57 * left-overs at the end of the ringbuffer. */
58 static char *loglastwrap;
59 /* Size (in bytes) of the i3 SHM log. */
60 static int logbuffer_size;
61 /* File descriptor for shm_open. */
62 static int logbuffer_shm;
63 /* Size (in bytes) of physical memory */
64 static long long physical_mem_bytes;
67 * Writes the offsets for the next write and for the last wrap to the
69 * Necessary to print the i3 SHM log in the correct order.
72 static void store_log_markers(void) {
73 header->offset_next_write = (logwalk - logbuffer);
74 header->offset_last_wrap = (loglastwrap - logbuffer);
75 header->size = logbuffer_size;
79 * Initializes logging by creating an error logfile in /tmp (or
80 * XDG_RUNTIME_DIR, see get_process_filename()).
82 * Will be called twice if --shmlog-size is specified.
85 void init_logging(void) {
87 if (!(errorfilename = get_process_filename("errorlog")))
88 fprintf(stderr, "Could not initialize errorlog\n");
90 errorfile = fopen(errorfilename, "w");
92 fprintf(stderr, "Could not initialize errorlog on %s: %s\n",
93 errorfilename, strerror(errno));
95 if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
96 fprintf(stderr, "Could not set close-on-exec flag\n");
101 if (physical_mem_bytes == 0) {
102 #if defined(__APPLE__)
103 int mib[2] = {CTL_HW, HW_MEMSIZE};
104 size_t length = sizeof(long long);
105 sysctl(mib, 2, &physical_mem_bytes, &length, NULL, 0);
107 physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
108 sysconf(_SC_PAGESIZE);
111 /* Start SHM logging if shmlog_size is > 0. shmlog_size is SHMLOG_SIZE by
112 * default on development versions, and 0 on release versions. If it is
113 * not > 0, the user has turned it off, so let's close the logbuffer. */
114 if (shmlog_size > 0 && logbuffer == NULL)
116 else if (shmlog_size <= 0 && logbuffer)
118 atexit(purge_zerobyte_logfile);
122 * Opens the logbuffer.
125 void open_logbuffer(void) {
126 /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
127 * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
128 * At the moment (2011-12-10), no testcase leads to an i3 log
129 * of more than ~ 600 KiB. */
130 logbuffer_size = min(physical_mem_bytes * 0.01, shmlog_size);
131 #if defined(__FreeBSD__)
132 sasprintf(&shmlogname, "/tmp/i3-log-%d", getpid());
134 sasprintf(&shmlogname, "/i3-log-%d", getpid());
136 logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
137 if (logbuffer_shm == -1) {
138 fprintf(stderr, "Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
142 #if defined(__OpenBSD__) || defined(__APPLE__)
143 if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
144 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
147 if ((ret = posix_fallocate(logbuffer_shm, 0, logbuffer_size)) != 0) {
148 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(ret));
150 close(logbuffer_shm);
151 shm_unlink(shmlogname);
155 logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
156 if (logbuffer == MAP_FAILED) {
158 fprintf(stderr, "Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
162 /* Initialize with 0-bytes, just to be sure… */
163 memset(logbuffer, '\0', logbuffer_size);
165 header = (i3_shmlog_header *)logbuffer;
167 #if !defined(__OpenBSD__)
168 pthread_condattr_t cond_attr;
169 pthread_condattr_init(&cond_attr);
170 if (pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED) != 0)
171 fprintf(stderr, "pthread_condattr_setpshared() failed, i3-dump-log -f will not work!\n");
172 pthread_cond_init(&(header->condvar), &cond_attr);
175 logwalk = logbuffer + sizeof(i3_shmlog_header);
176 loglastwrap = logbuffer + logbuffer_size;
181 * Closes the logbuffer.
184 void close_logbuffer(void) {
185 close(logbuffer_shm);
186 shm_unlink(shmlogname);
193 * Set verbosity of i3. If verbose is set to true, informative messages will
194 * be printed to stdout. If verbose is set to false, only errors will be
198 void set_verbosity(bool _verbose) {
206 bool get_debug_logging(void) {
207 return debug_logging;
214 void set_debug_logging(const bool _debug_logging) {
215 debug_logging = _debug_logging;
219 * Logs the given message to stdout (if print is true) while prefixing the
220 * current time to it. Additionally, the message will be saved in the i3 SHM
222 * This is to be called by *LOG() which includes filename/linenumber/function.
225 static void vlog(const bool print, const char *fmt, va_list args) {
226 /* Precisely one page to not consume too much memory but to hold enough
227 * data to be useful. */
228 static char message[4096];
229 static struct tm result;
231 static struct tm *tmp;
234 /* Get current time */
236 /* Convert time to local time (determined by the locale) */
237 tmp = localtime_r(&t, &result);
238 /* Generate time prefix */
239 len = strftime(message, sizeof(message), "%x %X - ", tmp);
244 * true true format message, save, print
245 * true false format message, save
246 * false true print message only
247 * false false INVALID, never called
252 gettimeofday(&tv, NULL);
253 printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
255 printf("%s", message);
259 len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
260 if (len >= sizeof(message)) {
261 fprintf(stderr, "BUG: single log message > 4k\n");
263 /* vsnprintf returns the number of bytes that *would have been written*,
264 * not the actual amount written. Thus, limit len to sizeof(message) to avoid
265 * memory corruption and outputting garbage later. */
266 len = sizeof(message);
268 /* Punch in a newline so the next log message is not dangling at
269 * the end of the truncated message. */
270 message[len - 2] = '\n';
273 /* If there is no space for the current message in the ringbuffer, we
274 * need to wrap and write to the beginning again. */
275 if (len >= (size_t)(logbuffer_size - (logwalk - logbuffer))) {
276 loglastwrap = logwalk;
277 logwalk = logbuffer + sizeof(i3_shmlog_header);
279 header->wrap_count++;
282 /* Copy the buffer, move the write pointer to the byte after our
283 * current message. */
284 strncpy(logwalk, message, len);
289 #if !defined(__OpenBSD__)
290 /* Wake up all (i3-dump-log) processes waiting for condvar. */
291 pthread_cond_broadcast(&(header->condvar));
295 fwrite(message, len, 1, stdout);
300 * Logs the given message to stdout while prefixing the current time to it,
301 * but only if verbose mode is activated.
304 void verboselog(char *fmt, ...) {
307 if (!logbuffer && !verbose)
311 vlog(verbose, fmt, args);
316 * Logs the given message to stdout while prefixing the current time to it.
319 void errorlog(char *fmt, ...) {
323 vlog(true, fmt, args);
326 /* also log to the error logfile, if opened */
328 vfprintf(errorfile, fmt, args);
334 * Logs the given message to stdout while prefixing the current time to it,
335 * but only if debug logging was activated.
336 * This is to be called by DLOG() which includes filename/linenumber
339 void debuglog(char *fmt, ...) {
342 if (!logbuffer && !(debug_logging))
346 vlog(debug_logging, fmt, args);
351 * Deletes the unused log files. Useful if i3 exits immediately, eg.
352 * because --get-socketpath was called. We don't care for syscall
353 * failures. This function is invoked automatically when exiting.
355 void purge_zerobyte_logfile(void) {
362 /* don't delete the log file if it contains something */
363 if ((stat(errorfilename, &st)) == -1 || st.st_size > 0)
366 if (unlink(errorfilename) == -1)
369 if ((slash = strrchr(errorfilename, '/')) != NULL) {
371 /* possibly fails with ENOTEMPTY if there are files (or
373 rmdir(errorfilename);