-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.c
64 lines (50 loc) · 1.26 KB
/
log.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
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <stdarg.h>
#include <time.h>
#include "log.h"
int g_verbosity = VERBOSITY_VERBOSE;
int g_use_syslog = 0;
#define MAIN_SRVNAME ""
#ifdef DEBUG
// Program start time
static struct timespec log_start = { 0, 0 };
const char *log_time() {
struct timespec now = { 0, 0 };
clock_gettime( CLOCK_MONOTONIC, &now );
// Initialize clock
if( log_start.tv_sec == 0 && log_start.tv_nsec == 0 ) {
clock_gettime( CLOCK_MONOTONIC, &log_start );
}
static char buf[10];
sprintf( buf, "[%8.2f] ",
((double) now.tv_sec + 1.0e-9 * now.tv_nsec) -
((double) log_start.tv_sec + 1.0e-9 * log_start.tv_nsec)
);
return buf;
}
#endif
void log_print( int priority, const char format[], ... ) {
char buf[1024];
//const char *prefix;
const char *time;
va_list vlist;
va_start( vlist, format );
vsnprintf( buf, sizeof(buf), format, vlist );
va_end( vlist );
#ifdef DEBUG
time = log_time();
#else
time = "";
#endif
if( g_use_syslog ) {
// Write messages to e.g. /var/log/syslog
openlog( MAIN_SRVNAME, LOG_PID | LOG_CONS, LOG_USER | LOG_PERROR );
syslog( priority, "%s%s", time, buf );
closelog();
} else {
FILE *out = (priority == LOG_ERR) ? stderr : stdout;
fprintf( out, "%s %s\n", time, buf );
}
}