Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
stats_snapshot.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
15#pragma once
16
17#include <chrono>
18#include <sstream>
19#include <string>
20#include <unordered_map>
21#include <variant>
22#include <iomanip>
23
25
26// Forward declare to avoid circular dependency
27using stats_value = std::variant<std::int64_t, double, std::string, bool>;
28
53 std::string component_name;
54 std::chrono::system_clock::time_point timestamp;
55 std::unordered_map<std::string, stats_value> values;
56
72 [[nodiscard]] auto to_json() const -> std::string
73 {
74 std::ostringstream json;
75 json << "{\n";
76 json << " \"component\": \"" << component_name << "\",\n";
77
78 // Format timestamp as ISO 8601
79 const auto time_t = std::chrono::system_clock::to_time_t(timestamp);
80 std::tm tm{};
81#ifdef _WIN32
82 localtime_s(&tm, &time_t);
83#else
84 localtime_r(&time_t, &tm);
85#endif
86 json << " \"timestamp\": \""
87 << std::put_time(&tm, "%Y-%m-%dT%H:%M:%S")
88 << "Z\",\n";
89
90 // Serialize metrics
91 json << " \"metrics\": {\n";
92
93 bool first = true;
94 for (const auto& [key, value] : values) {
95 if (!first) {
96 json << ",\n";
97 }
98 first = false;
99
100 json << " \"" << key << "\": ";
101
102 // Visit variant and format value
103 std::visit([&json](const auto& v) {
104 using T = std::decay_t<decltype(v)>;
105 if constexpr (std::is_same_v<T, std::int64_t>) {
106 json << v;
107 } else if constexpr (std::is_same_v<T, double>) {
108 json << std::fixed << std::setprecision(6) << v;
109 } else if constexpr (std::is_same_v<T, std::string>) {
110 json << "\"" << v << "\"";
111 } else if constexpr (std::is_same_v<T, bool>) {
112 json << (v ? "true" : "false");
113 }
114 }, value);
115 }
116
117 json << "\n }\n";
118 json << "}";
119
120 return json.str();
121 }
122};
123
124} // namespace kcenon::common::interfaces
std::variant< std::int64_t, double, std::string, bool > stats_value
Type-safe value type for statistics.
Point-in-time snapshot of component statistics.
std::string component_name
Component identifier.
auto to_json() const -> std::string
Serialize snapshot to JSON string.
std::unordered_map< std::string, stats_value > values
Metric key-value pairs.
std::chrono::system_clock::time_point timestamp
Snapshot capture time.