summaryrefslogtreecommitdiffstats
path: root/src/log.c
blob: 21c5e7da3714aac10007adcef6a2a8f509833f67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef SC_LOGLEVEL
#define SC_LOGLEVEL "SC_LOG_ERROR SC_LOG_WARNING SC_LOG_INFO SC_LOG_DEBUG"
#endif
const char * sc_log_str (SC_OPT_TYPE t) {
	switch (t & SC_LOG_MASK) {
		case SC_LOG_ERROR:
			return "SC_LOG_ERROR";
		case SC_LOG_WARNING:
			return "SC_LOG_WARNING";
		case SC_LOG_INFO:
			return "SC_LOG_INFO";
		case SC_LOG_DEBUG:
			return "SC_LOG_DEBUG";
		default:
			return "SC_LOG_UNKNOWN";
	}
	/* interestingly, gcc figures out there's no way for code to reach this section, therefore there's no warning "-Wreturn-type" */
}
#ifdef SC_LOGMEM
int sc_logentry_free (struct sc_logentry * l) {
	free(l->message); l->message = NULL;
	free(l);
	return 1;
}
struct sc_logentry * sc_logentry_init () {
	struct sc_logentry * l = calloc(1, sizeof(struct sc_logentry));
	return l;
}
#endif
int sc_push_log (SC_OPT_TYPE t, struct sc_cache * c, const char * ca, char * f, size_t l, unsigned short int isf, char * m, ...) {
#define SC_PLL c->logentries[c->logentries_length-1]
	char * compiled_message = NULL;
	if (!strstr(getenv("SC_LOGLEVEL") ? getenv("SC_LOGLEVEL") : SC_LOGLEVEL, sc_log_str(t)))
		return 0;
#ifdef SC_LOGMEM
	if (!c)
		return -1;
	pthread_rwlock_t * lock = c->logentries_lock;
	if (!lock)
		return -2;
	if (pthread_rwlock_wrlock(lock))
		return -3;
	if (c->logentries_sizeof <= c->logentries_length)
		SC_BIGGER_ARRAY(c->logentries, sc_logentry, 1);
	c->logentries_length++;
#endif
	size_t strlenm = strlen(m);
	size_t va_count = parse_printf_format(m, 0, NULL);
	if (isf && va_count > 0) {
		va_list ap, ap2;
		va_start(ap, m);
		va_copy(ap2, ap);
		strlenm = vsnprintf(NULL, 0, m, ap);
		compiled_message = malloc(sizeof(char)*strlenm+1);
		vsnprintf(compiled_message, strlenm+1, m, ap2);
		va_end(ap);
		va_end(ap2);
	} else {
		compiled_message = malloc(sizeof(char)*strlenm+1);
		strcpy(compiled_message, m);
	}
#ifdef SC_LOGMEM
	SC_PLL->file = f;
	SC_PLL->line = l;
	SC_PLL->function = ca;
	SC_PLL->time = time(NULL);
	SC_PLL->type = t;
	SC_PLL->message = compiled_message;
#endif
	fprintf(stderr, "[sear.c] %s %s()@%s:%zu: %s\n", sc_log_str(t), ca, f, l, compiled_message); /* in posix, this is thread safe */
#ifdef SC_LOGMEM
	if (lock && pthread_rwlock_unlock(lock))
		return -4;
#endif
#ifndef SC_LOGMEM
	free(compiled_message);
#endif
	return 1;
}