Sparkplug B C++ Library 1.0.0
Modern C++-23 implementation of Eclipse Sparkplug B 2.2 specification
Loading...
Searching...
No Matches
logging.hpp
1#pragma once
2
3#include <format>
4#include <functional>
5#include <string>
6#include <string_view>
7
8namespace sparkplug {
9
10enum class LogLevel { DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3 };
11
12using LogCallback = std::function<void(LogLevel, std::string_view)>;
13
14// Escapes control characters so attacker-controlled topic/metric strings
15// cannot forge log entries or inject terminal escape sequences (CWE-117).
16inline std::string sanitize_log_message(std::string_view message) {
17 std::string sanitized;
18 sanitized.reserve(message.size());
19 for (char c : message) {
20 const auto ch = static_cast<unsigned char>(c);
21 if (ch < 0x20 || ch == 0x7f) {
22 sanitized += std::format("\\x{:02x}", ch);
23 } else {
24 sanitized += c;
25 }
26 }
27 return sanitized;
28}
29
30} // namespace sparkplug