Jelajahi Sumber

Adding Untested Logging Util

Vinicius Teshima 2 tahun lalu
induk
melakukan
7c403a44c5
2 mengubah file dengan 124 tambahan dan 0 penghapusan
  1. 32 0
      include/toolbox/logger.h
  2. 92 0
      src/toolbox/logger.c

+ 32 - 0
include/toolbox/logger.h

@@ -0,0 +1,32 @@
+#ifndef LOGGER_H
+#define LOGGER_H
+
+/* #include <stddef.h> */
+
+#ifdef TOOLBOX_TYPEDEF
+typedef struct str str_st;
+#endif
+
+enum logger_level {
+	LL_TRACE,
+	LL_DEBUG,
+	LL_INFO,
+	LL_WARN,
+	LL_ERROR,
+	LL_FATAL
+};
+
+typedef void (*_print_like)(const char *, ...);
+
+struct logger {
+	_print_like trace;
+	_print_like debug;
+	_print_like info;
+	_print_like warn;
+	_print_like error;
+	_print_like fatal;
+};
+
+struct logger* logger_create(enum logger_level lvl);
+
+#endif

+ 92 - 0
src/toolbox/logger.c

@@ -0,0 +1,92 @@
+#include "toolbox/logger.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+/* static void nop(const char *format, ...); */
+/* static void trace(const char *format, ...); */
+/* static void debug(const char *format, ...); */
+/* static void info(const char *format, ...); */
+/* static void warn(const char *format, ...); */
+/* static void error(const char *format, ...); */
+/* static void fatal(const char *format, ...); */
+
+static void nop(const char *format, ...) {(void) format;}
+
+static void trace(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[TRACE] ");
+	vfprintf(stdout, format, vargs);
+}
+
+static void debug(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[DEBUG] ");
+	vfprintf(stdout, format, vargs);
+}
+
+static void info(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[INFO] ");
+	vfprintf(stdout, format, vargs);
+}
+
+static void warn(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[WARN] ");
+	vfprintf(stdout, format, vargs);
+}
+
+
+static void error(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[ERROR] ");
+	vfprintf(stderr, format, vargs);
+}
+
+static void fatal(const char *format, ...) {
+	va_list vargs;
+	va_start(vargs, format);
+	fprintf(stdout, "[FATAL] ");
+	vfprintf(stderr, format, vargs);
+}
+
+struct logger* logger_create(enum logger_level lvl) {
+	struct logger *ret = calloc(1, sizeof(struct logger));
+
+	ret->trace = *nop;
+	ret->debug = *nop;
+	ret->info  = *nop;
+	ret->warn  = *nop;
+	ret->error = *nop;
+	ret->fatal = *nop;
+
+	switch (lvl) {
+	case LL_TRACE:
+		ret->trace = *trace;
+		/* fall through */
+	case LL_DEBUG:
+		ret->debug = *debug;
+		/* fall through */
+	case LL_INFO:
+		ret->info = *info;
+		/* fall through */
+	case LL_WARN:
+		ret->warn = *warn;
+		/* fall through */
+	case LL_ERROR:
+		ret->error = *error;
+		/* fall through */
+	case LL_FATAL:
+		ret->fatal = *fatal;
+	}
+
+	return ret;
+}
+