From 07fe2191488861bd89f98e07281fa744c93bf912 Mon Sep 17 00:00:00 2001 From: Thomas Harte Date: Thu, 18 Jan 2024 16:37:07 -0500 Subject: [PATCH] Sketch out saner logging interface. --- Outputs/Log.hpp | 69 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 48 insertions(+), 21 deletions(-) diff --git a/Outputs/Log.hpp b/Outputs/Log.hpp index 012d94f94..55f0d80a7 100644 --- a/Outputs/Log.hpp +++ b/Outputs/Log.hpp @@ -8,39 +8,66 @@ #pragma once +// TODO: if adopting C++20, std::format would be a better model to apply below. +// But I prefer C files to C++ streams, so here it is for now. + +enum Category { + Info, + Error, +}; + #ifdef NDEBUG -#define LOG(x) while(false) {} -#define LOGNBR(x) while(false) {} +class Logger { + public: + Logger(const char *) {} -#define ERROR(x) while(false) {} -#define ERRORNBR(x) while(false) {} + struct LogLine { + void append(const char *, ...) {} + }; + template LogLine line() { + return LogLine(); + } +}; #else -#include -#include -#include +#include +#include -#define PADHEX(n) std::hex << std::setfill('0') << std::setw(n) -#define PADDEC(n) std::dec << std::setfill('0') << std::setw(n) +class Logger { + public: + Logger(const char *prefix) : prefix_(prefix) {} -#ifdef LOG_PREFIX + struct LogLine { + public: + LogLine(const char *prefix, FILE *stream) : stream_(stream) { + if(prefix) { + fprintf(stream_, "%s ", prefix); + } + } -#define LOG(x) std::cout << LOG_PREFIX << x << std::endl -#define LOGNBR(x) std::cout << LOG_PREFIX << x + ~LogLine() { + fprintf(stream_, "\n"); + } -#define ERROR(x) std::cerr << LOG_PREFIX << x << std::endl -#define ERRORNBR(x) std::cerr << LOG_PREFIX << x + void append(const char *format, ...) { + va_list args; + va_start(args, format); + vfprintf(stream_, format, args); + va_end(args); + } -#else + private: + FILE *stream_; + }; -#define LOG(x) std::cout << x << std::endl -#define LOGNBR(x) std::cout << x + template LogLine line() { + return LogLine(prefix_, category == Info ? stdout : stderr); + } -#define ERROR(x) std::cerr << x << std::endl -#define ERRORNBR(x) std::cerr << x - -#endif + private: + const char *prefix_; +}; #endif