diff --git a/include/utils/logger.h b/include/utils/logger.h index e731e59..66c8b42 100644 --- a/include/utils/logger.h +++ b/include/utils/logger.h @@ -1,6 +1,8 @@ #ifndef _LOGGER_H_ #define _LOGGER_H_ +#define LOG_PREFIX "ClearDNS" + enum { LOG_DEBUG, LOG_INFO, diff --git a/src/cleardns.c b/src/cleardns.c index e66f8dc..42231de 100644 --- a/src/cleardns.c +++ b/src/cleardns.c @@ -1,3 +1,4 @@ +#include #include "logger.h" #include "common.h" #include "dnsproxy.h" @@ -28,11 +29,17 @@ // fprintf(stderr, "\"\n"); //} + int main(int argc, char *argv[]) { // ClearDNS server LOG_LEVEL = LOG_DEBUG; log_info("ClearDNS server start (%s)", VERSION); + FILE *fp = fopen("/dev/null/123", "r"); + log_perror("Test prefix"); + + return 0; + // dnsproxy *domestic = dnsproxy_init(DOMESTIC_PORT); // // dnsproxy_add_bootstrap(domestic, "1.1.1.1"); diff --git a/src/utils/logger.c b/src/utils/logger.c index e9850ba..121132f 100644 --- a/src/utils/logger.c +++ b/src/utils/logger.c @@ -2,6 +2,7 @@ #include #include #include +#include #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); }