|
|
@ -2,6 +2,7 @@ |
|
|
|
#include <stdio.h> |
|
|
|
#include <stdlib.h> |
|
|
|
#include <stdarg.h> |
|
|
|
#include <sys/time.h> |
|
|
|
#include "logger.h" |
|
|
|
|
|
|
|
int LOG_LEVEL = LOG_INFO; // default log level
|
|
|
@ -22,38 +23,37 @@ static const char *log_color[] = { |
|
|
|
"\x1b[95m", // fatal
|
|
|
|
}; |
|
|
|
|
|
|
|
// TODO: add ms field
|
|
|
|
void fprint_prefix() { // print log prefix and time info
|
|
|
|
time_t _time; |
|
|
|
time(&_time); |
|
|
|
struct timeval tv; |
|
|
|
gettimeofday(&tv, NULL); |
|
|
|
struct tm *t = localtime(&_time); |
|
|
|
fprintf(stderr, "\x1b[36m[%s]\x1b[0m", LOG_PREFIX); |
|
|
|
fprintf(stderr, " \x1b[90m%04d-%02d-%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); |
|
|
|
fprintf(stderr, " %02d:%02d:%02d.%03ld\x1b[0m", t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000); |
|
|
|
} |
|
|
|
|
|
|
|
void log_printf(int level, const char *fmt, ...) { |
|
|
|
if (level < LOG_LEVEL) { // skip low log level
|
|
|
|
return; |
|
|
|
} |
|
|
|
time_t t = time(NULL); |
|
|
|
char time_str[20]; // YYYY-mm-dd HH:MM:SS (20 bytes)
|
|
|
|
time_str[strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", localtime(&t))] = '\0'; // generate time str
|
|
|
|
|
|
|
|
va_list ap; |
|
|
|
va_start(ap, fmt); |
|
|
|
fprintf(stderr, "\x1b[36m[ClearDNS]\x1b[0m \x1b[90m%s\x1b[0m", time_str); // show log prefix
|
|
|
|
fprint_prefix(); |
|
|
|
fprintf(stderr, " %s%s\x1b[0m ", log_color[level], log_string[level]); // show log level
|
|
|
|
vfprintf(stderr, fmt, ap); // output log content
|
|
|
|
fprintf(stderr, "\n"); // add LF after line
|
|
|
|
fflush(stderr); |
|
|
|
va_end(ap); |
|
|
|
|
|
|
|
if (level == LOG_FATAL) { |
|
|
|
exit(1); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// TODO: add ms field
|
|
|
|
void log_perror(char *prefix) { |
|
|
|
time_t t; |
|
|
|
time(&t); |
|
|
|
struct tm *lt = localtime(&t); |
|
|
|
fprintf(stderr, "\x1b[36m[ClearDNS]\x1b[0m "); |
|
|
|
fprintf(stderr, "\x1b[90m%04d-%02d-%02d %02d:%02d:%02d\x1b[0m", |
|
|
|
lt->tm_year + 1900, lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); |
|
|
|
fprintf(stderr, " %s%s\x1b[0m ", log_color[3], log_string[3]); // error level
|
|
|
|
fprint_prefix(); |
|
|
|
fprintf(stderr, " %s%s\x1b[0m ", log_color[LOG_ERROR], log_string[LOG_ERROR]); |
|
|
|
fflush(stderr); |
|
|
|
perror(prefix); |
|
|
|
} |
|
|
|