44ceea7 ยท 1 month ago 7 commits
 1#define _POSIX_C_SOURCE 199506L
 2#include <errno.h>
 3#include <stdarg.h>
 4#include <stdio.h>
 5#include <stdlib.h>
 6#include <string.h>
 7#include <time.h>
 8#include <unistd.h>
 9#include "log.h"
10
11static enum log_importance log_importance = LOG_ERROR;
12
13static const char *verbosity_colors[] = {
14	[LOG_SILENT] = "",
15	[LOG_ERROR ] = "\x1B[1;31m",
16	[LOG_INFO  ] = "\x1B[1;34m",
17	[LOG_DEBUG ] = "\x1B[1;30m",
18	[LOG_TRACE ] = "\x1B[1;32m",
19};
20
21void swaylock_log_init(enum log_importance verbosity) {
22	if (verbosity < LOG_IMPORTANCE_LAST) {
23		log_importance = verbosity;
24	}
25}
26
27void _swaylock_log(enum log_importance verbosity, const char *fmt, ...) {
28	if (verbosity > log_importance) {
29		return;
30	}
31
32	va_list args;
33	va_start(args, fmt);
34
35	// prefix the time to the log message
36	struct tm result;
37	time_t t = time(NULL);
38	struct tm *tm_info = localtime_r(&t, &result);
39	char buffer[26];
40
41	// generate time prefix
42	strftime(buffer, sizeof(buffer), "%F %T - ", tm_info);
43	fprintf(stderr, "%s", buffer);
44
45	unsigned c = (verbosity < LOG_IMPORTANCE_LAST)
46		? verbosity : LOG_IMPORTANCE_LAST - 1;
47
48	if (isatty(STDERR_FILENO)) {
49		fprintf(stderr, "%s", verbosity_colors[c]);
50	}
51
52	vfprintf(stderr, fmt, args);
53
54	if (isatty(STDERR_FILENO)) {
55		fprintf(stderr, "\x1B[0m");
56	}
57	fprintf(stderr, "\n");
58
59	va_end(args);
60}
61
62// This is mainly here for performance.
63// Don't want to do _swaylock_strip_path every event if we're not tracing.
64void _swaylock_trace(const char *file, int line, const char *func) {
65	if (LOG_TRACE > log_importance) {
66		return;
67	}
68
69	_swaylock_log(LOG_TRACE, "[%s:%d]: trace: %s",
70			_swaylock_strip_path(file), line, func);
71}
72
73const char *_swaylock_strip_path(const char *filepath) {
74	if (*filepath == '.') {
75		while (*filepath == '.' || *filepath == '/') {
76			++filepath;
77		}
78	}
79	return filepath;
80 }