log.c (1647B)
1 2 #include <stdio.h> 3 #include <stdarg.h> 4 #include <time.h> 5 #include <errno.h> 6 #include <string.h> 7 #include <stdlib.h> 8 9 #include "log.h" 10 11 #define LOG_MAX_MSGLEN 1024 12 13 #define ANSI_RED "\x1b[31m" 14 #define ANSI_BOLDRED "\x1b[1;31m" 15 #define ANSI_GREY "\x1b[38;5;239m" 16 #define ANSI_YELLOW "\x1b[33m" 17 #define ANSI_GREEN "\x1b[32m" 18 #define ANSI_CYAN "\x1b[36m" 19 #define ANSI_MAGENTA "\x1b[36m" 20 #define ANSI_RESET "\x1b[0m" 21 22 const char* lvl_colors[] = { 23 ANSI_MAGENTA, ANSI_GREEN, ANSI_CYAN, ANSI_YELLOW, ANSI_RED, ANSI_BOLDRED 24 }; 25 26 size_t log_min_level = 0; 27 28 FILE* log_file = NULL; 29 30 void log_msg(enum log_level lvl, char* lvl_name, char* fmt, ...) { 31 if (lvl < log_min_level) return; 32 33 char msg[LOG_MAX_MSGLEN]; 34 35 va_list args; 36 va_start(args, fmt); 37 vsprintf(msg, fmt, args); 38 39 time_t now = time(0); 40 struct tm* local = localtime(&now); 41 42 const char* lvl_color = lvl_colors[lvl]; 43 44 if (log_file == NULL) { 45 printf(ANSI_GREY "%02d/%02d/%04d %02d:%02d:%02d %s%s" ANSI_RESET ": %s\n", 46 local->tm_mon+1, local->tm_mday, 1900+local->tm_year, local->tm_hour, 47 local->tm_min, local->tm_sec, lvl_color, lvl_name, msg); 48 } else { 49 fprintf(log_file, "%02d/%02d/%04d %02d:%02d:%02d %s: %s\n", 50 local->tm_mon+1, local->tm_mday, 1900+local->tm_year, 51 local->tm_hour, local->tm_min, local->tm_sec, lvl_name, msg); 52 } 53 54 va_end(args); 55 } 56 57 void log_set_min_lvl(enum log_level lvl) { 58 log_min_level = lvl; 59 } 60 61 void log_set_log_file(char* path) { 62 log_file = fopen(path, "w"); 63 } 64 65 void die(char* p) { 66 log_fatal("(%s) %s", p, strerror(errno)); 67 exit(1); 68 }