commit 4647847eb30e23e082c456e5d8c471a431d3e605 Author: Markus Koch Date: Sun May 3 20:02:49 2020 +0200 C: Add report diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..8d61aae --- /dev/null +++ b/README.MD @@ -0,0 +1,6 @@ +# Code Snippets +Small code snippets that might prove useful again in the future. + +## C +* report: Easy to use report statement with log levels + diff --git a/c/report/report.c b/c/report/report.c new file mode 100644 index 0000000..aa9f562 --- /dev/null +++ b/c/report/report.c @@ -0,0 +1,60 @@ +/* ---------------------------------------------------------------------------- + * C-Report + * ---------------------------------------------------------------------------- + * Author : Markus Koch + * Contributors : None + * License : Mozilla Public License (MPL) Version 2 + * ---------------------------------------------------------------------------- +*/ + +#include "logging.h" +#include +#include +#include + +static enum log_level current_log_level = LL_INFO; + +static const char *ll_string[] = { + "\x1B[31m\x1B[1m[X] ", + "\x1B[31m[E] ", + "\x1B[33m[W] ", + "\x1B[32m[I] ", + "\x1B[34m[D] ", + "\x1B[34m[d] ", + "[?] " +}; + +int should_report(enum log_level log_level) +{ + return (log_level <= current_log_level); +} + +enum log_level report(enum log_level log_level, const char *format, ...) +{ + va_list vargs; + + if (log_level > LL_COUNT) + log_level = LL_COUNT; + + if (should_report(log_level)) { + va_start(vargs, format); + fprintf(stderr, "%s", ll_string[log_level]); + vfprintf(stderr, format, vargs); + fprintf(stderr, "\x1B[0m\n"); + va_end(vargs); + } + + return log_level; +} + +void set_log_level(enum log_level log_level) +{ + if (log_level >= LL_COUNT) + log_level = LL_COUNT - 1; + current_log_level = log_level; +} + +enum log_level get_log_level() +{ + return current_log_level; +} diff --git a/c/report/report.h b/c/report/report.h new file mode 100644 index 0000000..52668c7 --- /dev/null +++ b/c/report/report.h @@ -0,0 +1,28 @@ +/* ---------------------------------------------------------------------------- + * C-Report + * ---------------------------------------------------------------------------- + * Author : Markus Koch + * Contributors : None + * License : Mozilla Public License (MPL) Version 2 + * ---------------------------------------------------------------------------- +*/ + + +#ifndef REPORT_H +#define REPORT_H + +#include + +enum log_level {LL_CRITICAL = 0, + LL_ERROR, + LL_WARNING, + LL_INFO, + LL_DEBUG, + LL_NOISY, + LL_COUNT}; +int should_report(enum log_level log_level); +enum log_level report(enum log_level log_level, const char *format, ...); +void set_log_level(enum log_level log_level); +enum log_level get_log_level(); + +#endif // REPORT_H