From e13d5cf8ec312ced6d3c22471786acd9aad2fb3c Mon Sep 17 00:00:00 2001 From: cinnaboot Date: Thu, 20 Jan 2022 18:38:50 -0500 Subject: [PATCH] add a printf style logging macro --- src/dumbLog.cpp | 33 ++++++++++++++++++++++++++++++++- src/dumbLog.h | 9 ++++++++- src/types.h | 3 ++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/dumbLog.cpp b/src/dumbLog.cpp index 66b5495..a31b9be 100644 --- a/src/dumbLog.cpp +++ b/src/dumbLog.cpp @@ -3,6 +3,8 @@ #include #include "dumbLog.h" +#include "types.h" + void dumbLog::setOutputStream(std::ostream* out) { @@ -33,7 +35,36 @@ int dumbLog::getCurrentMS() { auto now = std::chrono::system_clock::now(); - long long total_ms = std::chrono::duration_cast(now.time_since_epoch()).count(); + u64 total_ms = std::chrono::duration_cast( + now.time_since_epoch() + ).count(); return int(total_ms % 1000); } + +#include +#include + + +void +dumbLogF(log_level l, const char* func, const char* fmt, ...) +{ + const char* level = logger.logLevelToString(l); + char time_str[100]; + timespec ts; + timespec_get(&ts, TIME_UTC); + i64 ms = ts.tv_nsec / 1000000; + + if (strftime(time_str, sizeof(time_str), "%T", localtime(&ts.tv_sec))) { + // NOTE: print prefix, "H:M:S.ms, log_level, function(), " + printf("%s.%03ld [%s] %s(), ", time_str, ms, level, func); + + // NOTE: append user args + va_list args; + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); + } else { + printf("%s(), error getting time\n", __FUNCTION__); + } +} diff --git a/src/dumbLog.h b/src/dumbLog.h index 769cfa4..be27e25 100644 --- a/src/dumbLog.h +++ b/src/dumbLog.h @@ -24,7 +24,14 @@ struct dumbLog static dumbLog logger; #define LOG(level) *logger.OUT \ - << std::put_time(logger.getCurrentTime(), "%F %T.") << logger.getCurrentMS() << " " \ + << std::put_time(logger.getCurrentTime(), "%F %T.") \ + << logger.getCurrentMS() << " " \ << "[" << logger.logLevelToString(level) << "] " \ << "(" << __FUNCTION__ << ") " + +#include + +#define LOGF(level, format_str, ...) \ + dumbLogF(level, __FUNCTION__, format_str, ##__VA_ARGS__); +void dumbLogF(log_level l, const char* func, const char* fmt, ...); diff --git a/src/types.h b/src/types.h index 7068408..e2bbdbd 100644 --- a/src/types.h +++ b/src/types.h @@ -5,8 +5,9 @@ typedef uint8_t u8; -typedef int32_t i32; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; +typedef int32_t i32; +typedef int64_t i64;