-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.c
More file actions
77 lines (60 loc) · 1.26 KB
/
debug.c
File metadata and controls
77 lines (60 loc) · 1.26 KB
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
#include <stdarg.h>
#include <stdlib.h>
#include "debug.h"
#define DEBUG_MSG_BUFSIZE 256
int debug_init(dbg_desc_t *d, int level, const char *filename)
{
if (!d)
return -1;
d->buf = malloc(DEBUG_MSG_BUFSIZE);
if (!d->buf)
goto error;
d->file=0;
if (filename) {
d->file = fopen(filename, "at+");
if (!d->file) {
fprintf(stderr, "Can't open log file: '%s'!!!\n", filename);
goto error;
}
} else
d->file = stdout;
d->level = level;
d->bufsize = DEBUG_MSG_BUFSIZE;
pthread_mutex_init(&d->mtx, 0);
return 0;
error:
debug_free(d);
return -1;
}
void debug_free(dbg_desc_t *d)
{
if (!d)
return;
if ((d->file) && (d->file!=stdout)) {
fflush(d->file);
fclose(d->file);
d->file=0;
}
if (d->buf) {
free(d->buf);
d->buf=0;
}
pthread_mutex_destroy(&d->mtx);
}
void debug_print(dbg_desc_t *d, int mlevel, const char *format, ...)
{
va_list args;
if (!d)
return;
if ( !((d) && (d->buf) && (d->file)) )
return;
pthread_mutex_lock(&d->mtx);
if ( d->level >= mlevel) {
va_start( args, format );
vsnprintf(d->buf, DEBUG_MSG_BUFSIZE, format, args );
va_end (args);
fprintf(d->file, "%s", d->buf);
fflush(d->file);
}
pthread_mutex_unlock(&d->mtx);
}