-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsole.c
65 lines (51 loc) · 1.16 KB
/
console.c
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
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <stdbool.h>
#include <glib.h>
#include "types.h"
#include "console.h"
int console_outfd = 1;
static GString *tstamp(void)
{
char stamp[sizeof "HH:MM:SS "];
time_t now = time(NULL);
struct tm *tm = localtime(&now);
strftime(stamp, sizeof stamp, "%H:%M:%S ", tm);
return g_string_new(stamp);
}
static inline void log_vput(GString *prefix, char *fmt, va_list ap)
{
g_string_append_vprintf(prefix, fmt, ap);
g_string_append_c(prefix, '\n');
struct buffer buf = { prefix->len, (unsigned char *) prefix->str };
while (buf.len > 0)
{
ssize_t wrote = write(console_outfd, buf.data, buf.len);
if (wrote < 0 && errno == EINTR)
continue;
else if (wrote < 0)
break; /* give up outputting anything */
ADVANCE_BUFFER(buf, wrote);
}
g_string_free(prefix, true);
}
void log_print(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_vput(tstamp(), fmt, ap);
va_end(ap);
}
void log_die(char *fmt, ...)
{
GString *msg = tstamp();
g_string_append_printf(msg, "[DIED] ");
va_list ap;
va_start(ap, fmt);
log_vput(msg, fmt, ap);
va_end(ap);
exit(1);
}