logging: facade (hand-rolled async worker) + hot-path migration; drop TRUNK_DEBUG
Adds src/misc/Log.h / Log.cpp exposing geulog::{trace,debug,info,warn,error}
(subsystem, args...) with gate-before-format. Seven named loggers
(trunk, satellite, twin, client, mqtt, redis, core) share a mutex-guarded
deque drained by a single background worker thread writing to fd=1.
Levels come from [GLOBAL] LOG=*=warn,trunk=debug,... and are runtime-
settable via /dev/shm/reflector_ctrl (LOG SHOW / LOG sub=lvl / LOG RESET).
Writes continue to fd=1 so LogWriter file/syslog paths are unchanged.
Migrated hot paths only: audio relay, talker start/stop, handshake,
heartbeat, per-client RX, per-frame trunk/satellite/twin relay, plus the
ENOTCONN sendMsg race at ReflectorClient:302 (demoted to debug since it
is per-disconnect noise, not a fault).
Cold paths (startup banners, config validation, TLS/CA diagnostics,
MQTT/Redis publisher lifecycle) remain on raw cout/cerr and move in the
next commit.
TRUNK_DEBUG is removed; a startup warning points at LOG=trunk=debug.
This commit is contained in:
1 parent
59ae728713
commit
ccec8f1e95
14 files changed
+1131
-646
No files matched your search
@@ -1,6 +1,6 @@
|
||||
set(LIBNAME svxmisc)
|
||||
set(EXPINC common.h CppStdCompat.h LogWriter.h)
|
||||
set(LIBSRC common.cpp LogWriter.cpp)
|
||||
set(EXPINC common.h CppStdCompat.h LogWriter.h Log.h)
|
||||
set(LIBSRC common.cpp LogWriter.cpp Log.cpp)
|
||||
|
||||
# Copy exported include files to the global include directory
|
||||
foreach(incfile ${EXPINC})
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
#include "Log.h"
|
||||
|
||||
#include <AsyncConfig.h>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace {
|
||||
|
||||
using geulog::Level;
|
||||
using geulog::SUBSYSTEMS;
|
||||
using geulog::NUM_SUBSYSTEMS;
|
||||
|
||||
// Per-subsystem level, indexed by SUBSYSTEMS[] position. Stored as int
|
||||
// because std::atomic<int> is unconditionally lock-free and portable.
|
||||
std::array<std::atomic<int>, NUM_SUBSYSTEMS> g_levels;
|
||||
// Startup snapshot used by reset().
|
||||
std::array<int, NUM_SUBSYSTEMS> g_snapshot;
|
||||
|
||||
// Async queue + worker.
|
||||
std::mutex g_queue_mu;
|
||||
std::condition_variable g_queue_cv;
|
||||
std::deque<std::string> g_queue;
|
||||
bool g_stop = false; // guarded by g_queue_mu
|
||||
std::thread g_worker;
|
||||
|
||||
int subIndex(const char* sub) {
|
||||
for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) {
|
||||
if (std::strcmp(SUBSYSTEMS[i], sub) == 0) return static_cast<int>(i);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char* levelName(Level l) {
|
||||
switch (l) {
|
||||
case Level::Trace: return "trace";
|
||||
case Level::Debug: return "debug";
|
||||
case Level::Info: return "info";
|
||||
case Level::Warn: return "warn";
|
||||
case Level::Error: return "error";
|
||||
case Level::Off: return "off";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
bool parseLevel(const std::string& s, Level& out) {
|
||||
if (s == "trace") { out = Level::Trace; return true; }
|
||||
if (s == "debug") { out = Level::Debug; return true; }
|
||||
if (s == "info") { out = Level::Info; return true; }
|
||||
if (s == "warn") { out = Level::Warn; return true; }
|
||||
if (s == "error") { out = Level::Error; return true; }
|
||||
if (s == "off") { out = Level::Off; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
void trim(std::string& s) {
|
||||
s.erase(0, s.find_first_not_of(" \t"));
|
||||
std::size_t e = s.find_last_not_of(" \t\r\n");
|
||||
if (e != std::string::npos) s.erase(e + 1);
|
||||
}
|
||||
|
||||
void workerLoop() {
|
||||
std::deque<std::string> local;
|
||||
for (;;) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(g_queue_mu);
|
||||
g_queue_cv.wait(lock, []{ return !g_queue.empty() || g_stop; });
|
||||
local.swap(g_queue);
|
||||
if (g_stop && local.empty()) return;
|
||||
}
|
||||
for (auto& line : local) {
|
||||
// Short writes are possible on a pipe; we tolerate the rare
|
||||
// truncated line rather than introduce a retry loop that could
|
||||
// block the worker on a stuck consumer.
|
||||
::write(STDOUT_FILENO, line.data(), line.size());
|
||||
}
|
||||
local.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void startWorker() {
|
||||
if (g_worker.joinable()) return;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_queue_mu);
|
||||
g_stop = false;
|
||||
}
|
||||
g_worker = std::thread(workerLoop);
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
namespace geulog {
|
||||
|
||||
bool shouldLog(const char* sub, Level lvl) {
|
||||
int idx = subIndex(sub);
|
||||
if (idx < 0) return false;
|
||||
return static_cast<int>(lvl) >=
|
||||
g_levels[idx].load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
void enqueue(Level lvl, const char* sub, std::string&& msg) {
|
||||
std::string line = "[";
|
||||
line += levelName(lvl);
|
||||
line += "] [";
|
||||
line += sub;
|
||||
line += "] ";
|
||||
line += msg;
|
||||
line += "\n";
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_queue_mu);
|
||||
g_queue.push_back(std::move(line));
|
||||
}
|
||||
g_queue_cv.notify_one();
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
bool configure(Async::Config& cfg) {
|
||||
Level default_level = Level::Info;
|
||||
std::map<std::string, Level> per_sub;
|
||||
|
||||
std::string spec;
|
||||
cfg.getValue("GLOBAL", "LOG", spec);
|
||||
if (!spec.empty()) {
|
||||
std::stringstream ss(spec);
|
||||
std::string token;
|
||||
while (std::getline(ss, token, ',')) {
|
||||
auto eq = token.find('=');
|
||||
if (eq == std::string::npos) {
|
||||
std::cerr << "*** ERROR: LOG config: missing '=' in '"
|
||||
<< token << "'" << std::endl;
|
||||
return false;
|
||||
}
|
||||
std::string key = token.substr(0, eq);
|
||||
std::string val = token.substr(eq + 1);
|
||||
trim(key);
|
||||
trim(val);
|
||||
Level lvl;
|
||||
if (!parseLevel(val, lvl)) {
|
||||
std::cerr << "*** ERROR: LOG config: unknown level '"
|
||||
<< val << "'" << std::endl;
|
||||
return false;
|
||||
}
|
||||
if (key == "*") {
|
||||
default_level = lvl;
|
||||
} else if (subIndex(key.c_str()) < 0) {
|
||||
std::cerr << "*** WARNING: LOG config: unknown subsystem '"
|
||||
<< key << "' ignored" << std::endl;
|
||||
} else {
|
||||
per_sub[key] = lvl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) {
|
||||
Level lvl = default_level;
|
||||
auto it = per_sub.find(SUBSYSTEMS[i]);
|
||||
if (it != per_sub.end()) lvl = it->second;
|
||||
g_levels[i].store(static_cast<int>(lvl), std::memory_order_relaxed);
|
||||
g_snapshot[i] = static_cast<int>(lvl);
|
||||
}
|
||||
|
||||
// TRUNK_DEBUG deprecation warning.
|
||||
std::string td;
|
||||
if (cfg.getValue("GLOBAL", "TRUNK_DEBUG", td) &&
|
||||
!td.empty() && td != "0") {
|
||||
std::cerr << "*** WARNING: TRUNK_DEBUG is obsolete; use "
|
||||
"LOG=trunk=debug in [GLOBAL] instead" << std::endl;
|
||||
}
|
||||
|
||||
startWorker();
|
||||
return true;
|
||||
}
|
||||
|
||||
void shutdown() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_queue_mu);
|
||||
g_stop = true;
|
||||
}
|
||||
g_queue_cv.notify_all();
|
||||
if (g_worker.joinable()) g_worker.join();
|
||||
}
|
||||
|
||||
bool setLevel(const std::string& sub, const std::string& lvl_s) {
|
||||
Level lvl;
|
||||
if (!parseLevel(lvl_s, lvl)) return false;
|
||||
if (sub == "*") { setDefaultLevel(lvl_s); return true; }
|
||||
int idx = subIndex(sub.c_str());
|
||||
if (idx < 0) return false;
|
||||
g_levels[idx].store(static_cast<int>(lvl), std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
|
||||
void setDefaultLevel(const std::string& lvl_s) {
|
||||
Level lvl;
|
||||
if (!parseLevel(lvl_s, lvl)) return;
|
||||
for (auto& a : g_levels) {
|
||||
a.store(static_cast<int>(lvl), std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
std::string snapshot() {
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) {
|
||||
Level lvl = static_cast<Level>(
|
||||
g_levels[i].load(std::memory_order_relaxed));
|
||||
out += SUBSYSTEMS[i];
|
||||
out += "=";
|
||||
out += levelName(lvl);
|
||||
out += "\n";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) {
|
||||
g_levels[i].store(g_snapshot[i], std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace geulog
|
||||
@@ -0,0 +1,92 @@
|
||||
#ifndef LOG_INCLUDED
|
||||
#define LOG_INCLUDED
|
||||
|
||||
#include <cstddef>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Async { class Config; }
|
||||
|
||||
namespace geulog {
|
||||
|
||||
enum class Level : int {
|
||||
Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Off = 5
|
||||
};
|
||||
|
||||
// Seven subsystems, matching the design spec. Strings are what sysops
|
||||
// type in config and PTY commands; the index is how levels are looked
|
||||
// up on the hot path.
|
||||
constexpr const char* SUBSYSTEMS[] = {
|
||||
"trunk", "satellite", "twin", "client", "mqtt", "redis", "core"
|
||||
};
|
||||
constexpr std::size_t NUM_SUBSYSTEMS =
|
||||
sizeof(SUBSYSTEMS) / sizeof(SUBSYSTEMS[0]);
|
||||
|
||||
// Init: parse [GLOBAL] LOG=, set per-subsystem levels, spawn the worker
|
||||
// thread. Call once, before LogWriter::start(). Returns false on config
|
||||
// parse error (error already written to stderr).
|
||||
bool configure(Async::Config& cfg);
|
||||
|
||||
// Stop the worker thread, drain the queue, join. Call on normal exit
|
||||
// before LogWriter::stop(). Safe to call multiple times.
|
||||
void shutdown();
|
||||
|
||||
// Set one subsystem's level at runtime. Unknown subsystem or level
|
||||
// string => false. Passing "*" as the subsystem applies setDefaultLevel.
|
||||
bool setLevel(const std::string& subsystem, const std::string& level);
|
||||
|
||||
// Apply `level` to every subsystem.
|
||||
void setDefaultLevel(const std::string& level);
|
||||
|
||||
// Return "<sub>=<lvl>\n..." for each subsystem.
|
||||
std::string snapshot();
|
||||
|
||||
// Restore the per-subsystem levels that configure() set from .conf.
|
||||
// Does NOT reread .conf from disk.
|
||||
void reset();
|
||||
|
||||
// Hot-path gate — one atomic load and one integer compare.
|
||||
bool shouldLog(const char* subsystem, Level level);
|
||||
|
||||
namespace detail {
|
||||
// Async enqueue. Called only after shouldLog() passed.
|
||||
void enqueue(Level level, const char* subsystem, std::string&& message);
|
||||
|
||||
// Recursive stream append — C++11-compatible (avoids fold expressions so
|
||||
// Log.h can be #included from call sites built at --std=c++11).
|
||||
inline void append_all(std::ostringstream&) {}
|
||||
|
||||
template <typename T, typename... Rest>
|
||||
inline void append_all(std::ostringstream& os, T&& first, Rest&&... rest) {
|
||||
os << std::forward<T>(first);
|
||||
append_all(os, std::forward<Rest>(rest)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline std::string concat(Args&&... args) {
|
||||
std::ostringstream os;
|
||||
append_all(os, std::forward<Args>(args)...);
|
||||
return os.str();
|
||||
}
|
||||
}
|
||||
|
||||
#define _LOG_DEFINE(fnname, lvlenum) \
|
||||
template <typename... Args> \
|
||||
inline void fnname(const char* sub, Args&&... args) { \
|
||||
if (!shouldLog(sub, Level::lvlenum)) return; \
|
||||
detail::enqueue(Level::lvlenum, sub, \
|
||||
detail::concat(std::forward<Args>(args)...)); \
|
||||
}
|
||||
|
||||
_LOG_DEFINE(trace, Trace)
|
||||
_LOG_DEFINE(debug, Debug)
|
||||
_LOG_DEFINE(info, Info)
|
||||
_LOG_DEFINE(warn, Warn)
|
||||
_LOG_DEFINE(error, Error)
|
||||
|
||||
#undef _LOG_DEFINE
|
||||
|
||||
} // namespace geulog
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user