Implement common logging function
When used as a library, it's desirable to be able to suppress logging,
or pipe logging through a different path. This commit changes behavior
such that logging is disabled by default, and introduces 2 new methods,
cper_set_log_stdio and cper_set_log_custom.
These allow library integrators to specify their logging mode. In
practice, this also allows fuzzing to run faster by not printing errors
to the log.
Change-Id: I941476627bc9b8261ba5f6c0b2b2338fdf931dd2
Signed-off-by: Ed Tanous <etanous@nvidia.com>
diff --git a/log.c b/log.c
new file mode 100644
index 0000000..2938a60
--- /dev/null
+++ b/log.c
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: Apache-2.0 */
+
+#ifndef CPER_LOG_H
+#define CPER_LOG_H
+
+#include <stdarg.h>
+
+#ifndef CPER_NO_STDIO
+#include <stdio.h>
+#endif
+
+enum {
+ CPER_LOG_NONE,
+ CPER_LOG_STDIO,
+ CPER_LOG_CUSTOM,
+} log_type = CPER_LOG_NONE;
+
+static void (*log_custom_fn)(const char *, va_list);
+
+void cper_print_log(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+
+ switch (log_type) {
+ case CPER_LOG_NONE:
+ break;
+ case CPER_LOG_STDIO:
+#ifndef CPER_NO_STDIO
+ vfprintf(stderr, fmt, ap);
+ fputs("\n", stderr);
+#endif
+ break;
+ case CPER_LOG_CUSTOM:
+ log_custom_fn(fmt, ap);
+ break;
+ }
+
+ va_end(ap);
+}
+
+void cper_set_log_stdio()
+{
+ log_type = CPER_LOG_STDIO;
+}
+
+void cper_set_log_custom(void (*fn)(const char *, va_list))
+{
+ log_type = CPER_LOG_CUSTOM;
+ log_custom_fn = fn;
+}
+
+#endif /* CPER_LOG_H */