2#ifndef LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_LOGGERS_PROMETHEUSHTTPSERVERLOGGER_HPP_INCLUDED
3#define LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_LOGGERS_PROMETHEUSHTTPSERVERLOGGER_HPP_INCLUDED
8#ifndef LOGIT_WITH_PROMETHEUS_SERVER
9# error "PrometheusHttpServerLogger requires LOGIT_WITH_PROMETHEUS_SERVER=1. Enable LOGIT_WITH_PROMETHEUS_SERVER in CMake."
16#include <server_http.hpp>
43 unsigned short port = 9090;
44 std::string
path =
"/metrics";
47 std::function<void(std::vector<PrometheusMetricFamily>&)>
on_collect;
66 [
this](std::shared_ptr<HttpServer::Response> response,
67 std::shared_ptr<HttpServer::Request>) {
73 SimpleWeb::StatusCode::success_ok,
75 {{
"Content-Type",
"text/plain; version=0.0.4; charset=utf-8"},
76 {
"Cache-Control",
"no-store"}});
79 response->write(SimpleWeb::StatusCode::server_error_internal_server_error);
84 m_server.resource[m_config.health_path][
"GET"] =
85 [](std::shared_ptr<HttpServer::Response> response,
86 std::shared_ptr<HttpServer::Request>) {
87 response->write(SimpleWeb::StatusCode::success_ok,
"ok");
92 [](std::shared_ptr<HttpServer::Response> response,
93 std::shared_ptr<HttpServer::Request>) {
95 SimpleWeb::StatusCode::client_error_not_found,
113 if (m_running.load()) {
116 m_running.store(
true);
117 m_server_thread = std::thread([
this]() {
125 void log(
const LogRecord& record,
const std::string& message)
override {
141 auto start = std::chrono::steady_clock::now();
142 std::vector<PrometheusMetricFamily> families;
144 std::lock_guard<std::mutex> lock(m_collect_mutex);
145 m_metrics.build_builtin_metrics(
146 families, m_config.format,
"prometheus_http_server",
148 build_scrape_metrics(families);
149 if (m_config.on_collect) {
151 m_config.on_collect(families);
153 m_metrics.add_failed_export();
157 auto end = std::chrono::steady_clock::now();
158 m_last_collect_duration_sec.store(
159 std::chrono::duration<double>(end - start).count());
175 return std::string();
199 return static_cast<double>(m_metrics.last_log_ts()) / 1000.0;
203 return static_cast<double>(m_metrics.dropped_count());
205 return static_cast<double>(m_metrics.failed_export_count());
215 m_log_level =
static_cast<int>(level);
221 return static_cast<LogLevel>(m_log_level.load());
226 return m_metrics.dropped_count();
231 return m_metrics.failed_export_count();
239 std::atomic<bool> m_running = ATOMIC_VAR_INIT(
false);
244 std::atomic<uint64_t> m_scrapes_total{0};
245 std::atomic<uint64_t> m_scrape_errors_total{0};
246 std::atomic<int64_t> m_last_scrape_timestamp_ms{0};
247 std::atomic<double> m_last_collect_duration_sec{0.0};
255 mf.
name = prefix +
"prometheus_scrapes_total";
256 mf.
help =
"Total number of Prometheus scrape requests";
260 s.
value =
static_cast<double>(m_scrapes_total.load());
261 add_scrape_labels(s);
263 families.push_back(mf);
269 mf.
name = prefix +
"prometheus_scrape_errors_total";
270 mf.
help =
"Total number of failed Prometheus scrape requests";
274 s.
value =
static_cast<double>(m_scrape_errors_total.load());
275 add_scrape_labels(s);
277 families.push_back(mf);
283 mf.
name = prefix +
"prometheus_last_scrape_timestamp_ms";
284 mf.
help =
"Timestamp of the last Prometheus scrape request";
288 s.
value =
static_cast<double>(m_last_scrape_timestamp_ms.load());
289 add_scrape_labels(s);
291 families.push_back(mf);
297 mf.
name = prefix +
"prometheus_collect_duration_seconds";
298 mf.
help =
"Duration of the last metrics collection in seconds";
302 s.
value = m_last_collect_duration_sec.load();
303 add_scrape_labels(s);
305 families.push_back(mf);
313 "prometheus_http_server"});
323 if (!m_running.exchange(
false)) {
327 if (m_server_thread.joinable()) {
328 m_server_thread.join();
Defines the interface for loggers used in the logging system.
Shared built-in metrics state and serialization for Prometheus loggers.
Prometheus text exposition format serialization helpers.
Optional buffered snapshot access returns empty results by default.
Serves Prometheus metrics via an embedded HTTP server.
int64_t get_int_param(const LoggerParam ¶m) const override
Retrieves an integer parameter from the logger.
void wait() override
No-op; server is independently serving metrics.
std::string get_string_param(const LoggerParam ¶m) const override
Retrieves a string parameter from the logger.
void log(const LogRecord &record, const std::string &message) override
Updates internal metric counters for a log message.
PrometheusHttpServerLogger(const PrometheusHttpServerLogger &)=delete
void shutdown() override
Stops the HTTP server and joins the server thread.
std::atomic< uint64_t > m_scrapes_total
SimpleWeb::Server< SimpleWeb::HTTP > HttpServer
uint64_t failed_export_count() const
Returns number of failed export attempts.
std::mutex m_collect_mutex
LogLevel get_log_level() const override
Gets minimal log level for this logger.
uint64_t dropped_count() const
Returns number of dropped records.
void set_log_level(LogLevel level) override
Sets minimal log level for this logger.
PrometheusHttpServerLogger()
Constructs Prometheus HTTP server logger with default configuration.
double get_float_param(const LoggerParam ¶m) const override
Retrieves a floating-point parameter from the logger.
std::atomic< uint64_t > m_scrape_errors_total
PrometheusHttpServerLogger & operator=(const PrometheusHttpServerLogger &)=delete
PrometheusLoggerMetrics m_metrics
void build_scrape_metrics(std::vector< PrometheusMetricFamily > &families) const
~PrometheusHttpServerLogger() override
void add_scrape_labels(PrometheusSample &sample) const
std::string collect_payload()
Collects current metrics and returns serialized Prometheus text payload.
PrometheusHttpServerLogger(const Config &config)
Constructs Prometheus HTTP server logger with custom configuration.
void start()
Starts the HTTP server thread.
std::atomic< int64_t > m_last_scrape_timestamp_ms
std::thread m_server_thread
Tracks log-record counters and builds built-in Prometheus metric families.
static int64_t counter_to_int64(uint64_t value)
Safely convert uint64_t counter to int64_t (clamping on overflow).
#define LOGIT_CURRENT_TIMESTAMP_MS()
Macro to get the current timestamp in milliseconds.
The primary namespace for the LogIt++ library.
@ LOG_LVL_TRACE
Trace level logging.
std::string build_prometheus_text_payload(const std::vector< PrometheusMetricFamily > &families, const PrometheusTextFormatConfig &config)
Builds a complete Prometheus text exposition format payload.
LoggerParam
Enumeration for different logger parameters that can be retrieved.
@ TimeSinceLastLog
The time elapsed since the last log in seconds.
@ LastLogTimestamp
The timestamp of the last log.
@ DroppedLogCount
Number of log records dropped by the backend.
@ FailedExportCount
Number of failed export attempts reported by the backend.
Stores log metadata and content.
const int64_t timestamp_ms
Timestamp in milliseconds.
PrometheusTextFormatConfig format
bool enable_health_endpoint
std::function< void(std::vector< PrometheusMetricFamily > &)> on_collect
A group of related samples sharing a name, help, and type.
std::vector< PrometheusSample > samples
Samples in this family.
std::string help
HELP text.
std::string name
Metric family name.
PrometheusMetricType type
Metric type.
A single metric sample with optional labels and timestamp.
std::string name
Full metric name (including suffixes).
std::vector< PrometheusLabel > labels
Labels for this sample.
double value
Sample value.
Configuration for Prometheus text exposition format output.
std::string logger_label_name
Name of logger label.
std::string instance_label_value
Value of instance label.
bool include_instance_label
Add instance label to built-in metrics.
std::string instance_label_name
Name of instance label.
bool include_logger_label
Add logger label to built-in metrics.
std::string metric_prefix
Prefix applied to built-in metric names.