diff options
author | mrb0nk500 <b0nk@b0nk.xyz> | 2022-08-03 15:51:34 -0300 |
---|---|---|
committer | mrb0nk500 <b0nk@b0nk.xyz> | 2022-08-03 15:51:34 -0300 |
commit | fd3c65ddfba142af718dda3ca985358a1420b9fa (patch) | |
tree | 63105b08ec09056eb12356446ddb84dcd2565f83 | |
parent | 9e4d29fbc2a285ee805836267b955fecc96c0377 (diff) |
log, macros: Make `stdout`, and `stderr` logging more colourful
This is designed to make it more readable when printing the logs to
a terminal, or terminal emulator.
-rw-r--r-- | log.c | 55 | ||||
-rw-r--r-- | macros.h | 5 |
2 files changed, 58 insertions, 2 deletions
@@ -4,8 +4,61 @@ #include <string.h> #include <syslog.h> #include "log.h" +#include "macros.h" #include "misc.h" +typedef enum colour colour; + +enum colour { + BLACK, + RED, + GREEN, + YELLOW, + BLUE, + MAGENTA, + CYAN, + WHITE, + NUM_COLOURS, + RESET = NUM_COLOURS, +}; + +static const char *print_ansi_colour(colour colour, int is_bg, int is_bright) { + if (colour < NUM_COLOURS) { + static char str[const_strlen("\x1B[100m")+1] = {0}; + int colour_code = colour + 30; + + if (is_bg) { + colour_code += 10; + } + + if (is_bright) { + colour_code += 60; + } + + snprintf(str, sizeof(str)-1, "\x1B[%dm", colour_code); + return str; + } else { + return "\x1B[0m"; + } +} + +static const char *print_priority_colour(int priority) { + colour colour = RESET; + int is_bg = 0; + int is_bright = 0; + + switch (priority) { + case LOG_ERR : colour = RED; break; + case LOG_WARNING: colour = YELLOW; is_bright = 1; break; + case LOG_NOTICE : colour = CYAN; break; + case LOG_INFO : colour = MAGENTA; break; + case LOG_DEBUG : colour = GREEN; break; + default : break; + } + + return print_ansi_colour(colour, is_bg, is_bright); +} + void vprintlog(log_output output_type, int priority, const char *fmt, va_list args) { char *buf = calloc(vformat_len_copy(fmt, args)+1, sizeof(char)); vsprintf(buf, fmt, args); @@ -18,7 +71,7 @@ void vprintlog(log_output output_type, int priority, const char *fmt, va_list ar case LOG_OUT_STDERR: case LOG_OUT_STDOUT: { FILE *output = (output_type == LOG_OUT_STDOUT) ? stdout : stderr; - fprintf(output, "%s\n", buf); + fprintf(output, "%s%s\x1B[0m\n", print_priority_colour(priority), buf); break; } default: @@ -1,10 +1,13 @@ #ifndef MACROS_H #define MACROS_H +#define const_strlen(str) sizeof((char []){str}) + +#ifndef LOG_H #include "log.h" #define log(priority, ...) printlog(LOG_OUT_SYSLOG, priority, __VA_ARGS__) #define log_reason(priority, msg, ...) log(priority, msg " Reason %s", __VA_ARGS__) -#define const_strlen(str) sizeof((char []){str}) +#endif #endif |