summaryrefslogtreecommitdiff
path: root/src/trace.c
blob: f4994c8f854cb6a1eee61e58c405f98aacd2e3d6 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <s.h>

#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "logerr.h"
#include "trace.h"



static pthread_key_t
LEVEL_KEY;

static pthread_key_t
STREAM_KEY;

static pthread_once_t
ONCE = PTHREAD_ONCE_INIT;



static void
init(void) {
	assert(pthread_key_create(&LEVEL_KEY,  NULL) == 0);
	assert(pthread_key_create(&STREAM_KEY, NULL) == 0);
	assert(pthread_setspecific(LEVEL_KEY, (void *)TraceLevel_INFO) == 0);
	assert(pthread_setspecific(LEVEL_KEY, stderr) == 0);
}

void
vftracef(
	const char *const file,
	const char *const function,
	const int lineno,
	FILE *restrict stream,
	const enum TraceLevel level,
	const char *restrict format,
	va_list args
) {
	assert(pthread_once(&ONCE, init) == 0);

	const enum TraceLevel current_level = (enum TraceLevel)(intptr_t)pthread_getspecific(LEVEL_KEY);
	if (level > current_level) {
		return;
	}

	if (fprintf(stream, "%s:%s:%d: ", file, function, lineno) < 0) {
		logerr("fprintf() < 0: %s", strerror(errno));
	}

	if (vfprintf(stream, format, args) < 0) {
		perror(__FILE__ ":vtrace(): vfprintf() < 0");
	}

	if (fprintf(stream, "\n") < 0) {
		perror(__FILE__ ":vtrace(): fprintf() < 0");
	}
}

void
ftracef(
	const char *const file,
	const char *const function,
	const int lineno,
	FILE *restrict stream,
	const enum TraceLevel level,
	const char *restrict format,
	...
) {
	va_list args;
	va_start(args, format);
	vftracef(file, function, lineno, stream, level, format, args);
	va_end(args);
}

void
tracef(
	const char *const file,
	const char *const function,
	const int lineno,
	const enum TraceLevel level,
	const char *restrict format,
	...
) {
	assert(pthread_once(&ONCE, init) == 0);

	va_list args;
	va_start(args, format);
	vftracef(file, function, lineno, pthread_getspecific(STREAM_KEY), level, format, args);
	va_end(args);
}

int
trace_set_stream(FILE *stream) {
	return pthread_setspecific(STREAM_KEY, stream);
}

int
trace_set_level(const enum TraceLevel level) {
	assert(level >= TraceLevel_NONE);
	assert(level <= TraceLevel_DEBUG);
	return pthread_setspecific(LEVEL_KEY, (void *)(intptr_t)level);
}