1
0
mirror of https://github.com/TomHarte/CLK.git synced 2024-06-26 10:29:31 +00:00

Sketch out saner logging interface.

This commit is contained in:
Thomas Harte 2024-01-18 16:37:07 -05:00
parent e8917cd294
commit 07fe219148

View File

@ -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 <Category category> LogLine line() {
return LogLine();
}
};
#else
#include <iostream>
#include <ios>
#include <iomanip>
#include <cstdio>
#include <cstdarg>
#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 <Category category> 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