Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

feat(logging): add operational server logs

Martin Vogel59b836e441b7
diff --git a/src/foundation/log.c b/src/foundation/log.c
index 011ee5d4f..3e5f90c43 100644
--- a/src/foundation/log.c
+++ b/src/foundation/log.c
@@ -12,47 +12,74 @@
#include <string.h>
static CBMLogLevel g_log_level = CBM_LOG_INFO;
+static CBMLogFormat g_log_format = CBM_LOG_FORMAT_TEXT;
static cbm_log_sink_fn g_log_sink = NULL;
+static CBMLogSinkMode g_log_sink_mode = CBM_LOG_SINK_REPLACE;
/* CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */
void cbm_log_init_from_env(void) {
/* getenv() is safe here: this runs at startup before any thread is created,
* so there is no concurrent setenv() to race against. */
const char *raw = getenv("CBM_LOG_LEVEL");
- if (!raw || raw[0] == '\0') {
- return; /* unset/empty: keep the current (default) level — fail-open */
- }
-
- /* Textual form, case-insensitive. Index of each name == its enum value. */
- static const char *const names[] = {"debug", "info", "warn", "error", "none"};
- char lower[8];
- size_t i = 0;
- for (; i < sizeof(lower) - 1 && raw[i] != '\0'; i++) {
- lower[i] = (char)tolower((unsigned char)raw[i]);
- }
- lower[i] = '\0';
- if (raw[i] == '\0') { /* fully consumed — candidate textual match */
- for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
- if (strcmp(lower, names[lvl]) == 0) {
- cbm_log_set_level((CBMLogLevel)lvl);
- return;
+ if (raw && raw[0] != '\0') {
+ /* Textual form, case-insensitive. Index of each name == its enum value. */
+ static const char *const names[] = {"debug", "info", "warn", "error", "none"};
+ char lower[8];
+ size_t i = 0;
+ for (; i < sizeof(lower) - 1 && raw[i] != '\0'; i++) {
+ lower[i] = (char)tolower((unsigned char)raw[i]);
+ }
+ lower[i] = '\0';
+ if (raw[i] == '\0') { /* fully consumed — candidate textual match */
+ for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
+ if (strcmp(lower, names[lvl]) == 0) {
+ cbm_log_set_level((CBMLogLevel)lvl);
+ goto parse_format;
+ }
}
}
+
+ /* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
+ char *end = NULL;
+ long n = strtol(raw, &end, CBM_DECIMAL_BASE);
+ if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
+ cbm_log_set_level((CBMLogLevel)n);
+ }
}
- /* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
- char *end = NULL;
- long n = strtol(raw, &end, CBM_DECIMAL_BASE);
- if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
- cbm_log_set_level((CBMLogLevel)n);
+ /* Unrecognised value: leave the level unchanged (fail-open). */
+
+parse_format:;
+ const char *fmt = getenv("CBM_LOG_FORMAT");
+ if (fmt && fmt[0] != '\0') {
+ char lower_fmt[8];
+ size_t i = 0;
+ for (; i < sizeof(lower_fmt) - 1 && fmt[i] != '\0'; i++) {
+ lower_fmt[i] = (char)tolower((unsigned char)fmt[i]);
+ }
+ lower_fmt[i] = '\0';
+ if (fmt[i] == '\0' && strcmp(lower_fmt, "json") == 0) {
+ cbm_log_set_format(CBM_LOG_FORMAT_JSON);
+ } else if (fmt[i] == '\0' && strcmp(lower_fmt, "text") == 0) {
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ }
return;
}
- /* Unrecognised value: leave the level unchanged (fail-open). */
+ const char *env = getenv("ENVIRONMENT");
+ const char *cloud_run = getenv("K_SERVICE");
+ if ((env && strcmp(env, "production") == 0) || (cloud_run && cloud_run[0] != '\0')) {
+ cbm_log_set_format(CBM_LOG_FORMAT_JSON);
+ }
}
void cbm_log_set_sink(cbm_log_sink_fn fn) {
+ cbm_log_set_sink_ex(fn, CBM_LOG_SINK_REPLACE);
+}
+
+void cbm_log_set_sink_ex(cbm_log_sink_fn fn, CBMLogSinkMode mode) {
g_log_sink = fn;
+ g_log_sink_mode = mode;
}
void cbm_log_set_level(CBMLogLevel level) {
@@ -63,6 +90,14 @@ CBMLogLevel cbm_log_get_level(void) {
return g_log_level;
}
+void cbm_log_set_format(CBMLogFormat format) {
+ g_log_format = format;
+}
+
+CBMLogFormat cbm_log_get_format(void) {
+ return g_log_format;
+}
+
static const char *level_str(CBMLogLevel level) {
switch (level) {
case CBM_LOG_DEBUG:
@@ -78,54 +113,226 @@ static const char *level_str(CBMLogLevel level) {
}
}
+static const char *severity_str(CBMLogLevel level) {
+ switch (level) {
+ case CBM_LOG_DEBUG:
+ return "DEBUG";
+ case CBM_LOG_INFO:
+ return "INFO";
+ case CBM_LOG_WARN:
+ return "WARNING";
+ case CBM_LOG_ERROR:
+ return "ERROR";
+ default:
+ return "DEFAULT";
+ }
+}
+
+static void append_char(char *buf, size_t bufsz, size_t *pos, char ch) {
+ if (*pos < bufsz - 1) {
+ buf[*pos] = ch;
+ }
+ (*pos)++;
+}
+
+static void append_raw(char *buf, size_t bufsz, size_t *pos, const char *s) {
+ if (!s) {
+ return;
+ }
+ while (*s) {
+ append_char(buf, bufsz, pos, *s++);
+ }
+}
+
+static void append_text_atom(char *buf, size_t bufsz, size_t *pos, const char *s) {
+ if (!s) {
+ return;
+ }
+ while (*s) {
+ unsigned char ch = (unsigned char)*s++;
+ if (ch <= ' ' || ch == 0x7f) {
+ append_char(buf, bufsz, pos, '_');
+ } else {
+ append_char(buf, bufsz, pos, (char)ch);
+ }
+ }
+}
+
+static void append_json_string(char *buf, size_t bufsz, size_t *pos, const char *s) {
+ append_char(buf, bufsz, pos, '"');
+ if (s) {
+ while (*s) {
+ unsigned char ch = (unsigned char)*s++;
+ switch (ch) {
+ case '"':
+ append_raw(buf, bufsz, pos, "\\\"");
+ break;
+ case '\\':
+ append_raw(buf, bufsz, pos, "\\\\");
+ break;
+ case '\b':
+ append_raw(buf, bufsz, pos, "\\b");
+ break;
+ case '\f':
+ append_raw(buf, bufsz, pos, "\\f");
+ break;
+ case '\n':
+ append_raw(buf, bufsz, pos, "\\n");
+ break;
+ case '\r':
+ append_raw(buf, bufsz, pos, "\\r");
+ break;
+ case '\t':
+ append_raw(buf, bufsz, pos, "\\t");
+ break;
+ default:
+ if (ch < 0x20) {
+ static const char hex[] = "0123456789abcdef";
+ append_raw(buf, bufsz, pos, "\\u00");
+ append_char(buf, bufsz, pos, hex[ch >> 4]);
+ append_char(buf, bufsz, pos, hex[ch & 0xf]);
+ } else {
+ append_char(buf, bufsz, pos, (char)ch);
+ }
+ break;
+ }
+ }
+ }
+ append_char(buf, bufsz, pos, '"');
+}
+
+static void finish_line(char *buf, size_t bufsz, size_t pos) {
+ if (bufsz == 0) {
+ return;
+ }
+ if (pos >= bufsz) {
+ buf[bufsz - 1] = '\0';
+ } else {
+ buf[pos] = '\0';
+ }
+}
+
+static void emit_line(const char *line) {
+ if (g_log_sink) {
+ g_log_sink(line);
+ if (g_log_sink_mode == CBM_LOG_SINK_REPLACE) {
+ return;
+ }
+ }
+ (void)fprintf(stderr, "%s\n", line);
+}
+
void cbm_log(CBMLogLevel level, const char *msg, ...) {
if (level < g_log_level) {
return;
}
- /* Build the log line into a buffer ONCE — no double va_list iteration */
- char line_buf[CBM_SZ_512];
- int pos =
- snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s", level_str(level), msg ? msg : "");
-
+ char line_buf[CBM_SZ_4K];
+ size_t pos = 0;
va_list args;
va_start(args, msg);
- for (;;) {
- const char *key = va_arg(args, const char *);
- if (!key) {
- break;
- }
- const char *val = va_arg(args, const char *);
- if (!val) {
- val = "";
+
+ if (g_log_format == CBM_LOG_FORMAT_JSON) {
+ append_raw(line_buf, sizeof(line_buf), &pos, "{\"severity\":");
+ append_json_string(line_buf, sizeof(line_buf), &pos, severity_str(level));
+ append_raw(line_buf, sizeof(line_buf), &pos, ",\"message\":");
+ append_json_string(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
+ append_raw(line_buf, sizeof(line_buf), &pos, ",\"event\":");
+ append_json_string(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
+ for (;;) {
+ const char *key = va_arg(args, const char *);
+ if (!key) {
+ break;
+ }
+ const char *val = va_arg(args, const char *);
+ append_char(line_buf, sizeof(line_buf), &pos, ',');
+ append_json_string(line_buf, sizeof(line_buf), &pos, key);
+ append_char(line_buf, sizeof(line_buf), &pos, ':');
+ append_json_string(line_buf, sizeof(line_buf), &pos, val ? val : "");
}
- if ((size_t)pos < sizeof(line_buf) - SKIP_ONE) {
- pos += snprintf(line_buf + pos, sizeof(line_buf) - (size_t)pos, " %s=%s", key, val);
+ append_char(line_buf, sizeof(line_buf), &pos, '}');
+ } else {
+ append_raw(line_buf, sizeof(line_buf), &pos, "level=");
+ append_text_atom(line_buf, sizeof(line_buf), &pos, level_str(level));
+ append_raw(line_buf, sizeof(line_buf), &pos, " msg=");
+ append_text_atom(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
+ for (;;) {
+ const char *key = va_arg(args, const char *);
+ if (!key) {
+ break;
+ }
+ const char *val = va_arg(args, const char *);
+ append_char(line_buf, sizeof(line_buf), &pos, ' ');
+ append_text_atom(line_buf, sizeof(line_buf), &pos, key);
+ append_char(line_buf, sizeof(line_buf), &pos, '=');
+ append_text_atom(line_buf, sizeof(line_buf), &pos, val ? val : "");
}
}
va_end(args);
- /* When a sink is registered it takes over all output (exclusive).
- * Otherwise write structured log to stderr. */
- if (g_log_sink) {
- g_log_sink(line_buf);
- } else {
- (void)fprintf(stderr, "%s\n", line_buf);
- }
+ finish_line(line_buf, sizeof(line_buf), pos);
+ emit_line(line_buf);
}
void cbm_log_int(CBMLogLevel level, const char *msg, const char *key, int64_t value) {
- if (level < g_log_level) {
+ char value_buf[CBM_SZ_32];
+ snprintf(value_buf, sizeof(value_buf), "%" PRId64, value);
+ cbm_log(level, msg, key ? key : "?", value_buf, NULL);
+}
+
+static void copy_path_without_query(const char *path, char *out, size_t outsz) {
+ if (!out || outsz == 0) {
return;
}
+ out[0] = '\0';
+ if (!path) {
+ return;
+ }
+ size_t n = 0;
+ while (path[n] && path[n] != '?' && path[n] != '#' && n < outsz - 1) {
+ out[n] = path[n];
+ n++;
+ }
+ out[n] = '\0';
+}
- char line_buf[CBM_SZ_256];
- snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s %s=%" PRId64, level_str(level),
- msg ? msg : "", key ? key : "?", value);
-
- if (g_log_sink) {
- g_log_sink(line_buf);
+void cbm_log_mcp_request(const char *method, const char *tool_name, bool is_error,
+ int64_t duration_us) {
+ char duration_ms[CBM_SZ_32];
+ snprintf(duration_ms, sizeof(duration_ms), "%" PRId64, duration_us / 1000);
+ if (tool_name && tool_name[0] != '\0') {
+ cbm_log(is_error ? CBM_LOG_WARN : CBM_LOG_INFO, "mcp.request", "rpc.system", "jsonrpc",
+ "rpc.method", method ? method : "", "mcp.tool.name", tool_name, "status",
+ is_error ? "error" : "ok", "duration_ms", duration_ms, NULL);
} else {
- (void)fprintf(stderr, "%s\n", line_buf);
+ cbm_log(is_error ? CBM_LOG_WARN : CBM_LOG_INFO, "mcp.request", "rpc.system", "jsonrpc",
+ "rpc.method", method ? method : "", "status", is_error ? "error" : "ok",
+ "duration_ms", duration_ms, NULL);
}
}
+
+void cbm_log_http_request(const char *component, const char *method, const char *path, int status,
+ int64_t duration_ms, size_t request_bytes, size_t response_bytes) {
+ char safe_path[CBM_SZ_1K];
+ char status_buf[CBM_SZ_16];
+ char duration_buf[CBM_SZ_32];
+ char request_buf[CBM_SZ_32];
+ char response_buf[CBM_SZ_32];
+ copy_path_without_query(path, safe_path, sizeof(safe_path));
+ snprintf(status_buf, sizeof(status_buf), "%d", status);
+ snprintf(duration_buf, sizeof(duration_buf), "%" PRId64, duration_ms);
+ snprintf(request_buf, sizeof(request_buf), "%zu", request_bytes);
+ snprintf(response_buf, sizeof(response_buf), "%zu", response_bytes);
+
+ CBMLogLevel level = CBM_LOG_INFO;
+ if (status >= 500) {
+ level = CBM_LOG_ERROR;
+ } else if (status >= 400) {
+ level = CBM_LOG_WARN;
+ }
+
+ cbm_log(level, "http.request", "component", component ? component : "", "http.request.method",
+ method ? method : "", "url.path", safe_path, "http.response.status_code", status_buf,
+ "duration_ms", duration_buf, "http.request.body.size", request_buf,
+ "http.response.body.size", response_buf, NULL);
+}
diff --git a/src/foundation/log.h b/src/foundation/log.h
index beb60d5be..74c68d45a 100644
--- a/src/foundation/log.h
+++ b/src/foundation/log.h
@@ -3,7 +3,8 @@
*
* Design:
* - All output goes to stderr (stdout is reserved for MCP JSON-RPC)
- * - Structured format: "level=info msg=pass.timing pass=defs elapsed_ms=42"
+ * - Structured text format: "level=info msg=pass.timing pass=defs elapsed_ms=42"
+ * - Optional JSON format for production collectors / Cloud Logging
* - Levels: DEBUG, INFO, WARN, ERROR
* - Level filtering at runtime via cbm_log_set_level() or the
* CBM_LOG_LEVEL env var (see cbm_log_init_from_env)
@@ -12,7 +13,9 @@
#ifndef CBM_LOG_H
#define CBM_LOG_H
+#include <stdbool.h>
#include <stdint.h>
+#include <stddef.h>
typedef enum {
CBM_LOG_DEBUG = 0,
@@ -22,11 +25,24 @@ typedef enum {
CBM_LOG_NONE = 4 /* disable all logging */
} CBMLogLevel;
+typedef enum {
+ CBM_LOG_FORMAT_TEXT = 0,
+ CBM_LOG_FORMAT_JSON = 1,
+} CBMLogFormat;
+
+typedef enum {
+ CBM_LOG_SINK_REPLACE = 0,
+ CBM_LOG_SINK_TEE = 1,
+} CBMLogSinkMode;
+
/* Apply the CBM_LOG_LEVEL environment variable to the runtime log level.
* Accepts (case-insensitive) "debug", "info", "warn", "error", "none", or
* the numeric equivalents 0..4 matching CBMLogLevel. Unknown, empty, or
- * unset values leave the level unchanged (fail-open). Call once at startup,
- * before any threads or log statements. Distilled from #414 (closes #413). */
+ * unset values leave the level unchanged (fail-open).
+ *
+ * Also applies CBM_LOG_FORMAT=text|json. If unset, JSON is auto-enabled for
+ * production / Cloud Run style environments (ENVIRONMENT=production or
+ * K_SERVICE present). Call once at startup before any threads or log lines. */
void cbm_log_init_from_env(void);
/* Set minimum log level (default: INFO). */
@@ -35,6 +51,10 @@ void cbm_log_set_level(CBMLogLevel level);
/* Get current log level. */
CBMLogLevel cbm_log_get_level(void);
+/* Set/get output format. Default is text. */
+void cbm_log_set_format(CBMLogFormat format);
+CBMLogFormat cbm_log_get_format(void);
+
/* Core logging function. msg is a short semantic tag.
* Variadic args are key-value pairs: (const char *key, const char *value)...
* Terminated by NULL key.
@@ -57,8 +77,16 @@ void cbm_log(CBMLogLevel level, const char *msg, ...);
/* Log with integer value (avoids sprintf for common case). */
void cbm_log_int(CBMLogLevel level, const char *msg, const char *key, int64_t value);
+/* Operational event helpers. They deliberately avoid request bodies, headers,
+ * arguments, and query strings. */
+void cbm_log_mcp_request(const char *method, const char *tool_name, bool is_error,
+ int64_t duration_us);
+void cbm_log_http_request(const char *component, const char *method, const char *path, int status,
+ int64_t duration_ms, size_t request_bytes, size_t response_bytes);
+
/* Optional log sink callback — called with the formatted log line. */
typedef void (*cbm_log_sink_fn)(const char *line);
void cbm_log_set_sink(cbm_log_sink_fn fn);
+void cbm_log_set_sink_ex(cbm_log_sink_fn fn, CBMLogSinkMode mode);
#endif /* CBM_LOG_H */
diff --git a/src/main.c b/src/main.c
index f2b72cba8..3fec11630 100644
--- a/src/main.c
+++ b/src/main.c
@@ -429,7 +429,7 @@ int main(int argc, char **argv) {
* No more untracked heap blind spots. */
/* Store binary path for subprocess spawning + hook log sink */
cbm_http_server_set_binary_path(argv[0]);
- cbm_log_set_sink(cbm_ui_log_append);
+ cbm_log_set_sink_ex(cbm_ui_log_append, CBM_LOG_SINK_TEE);
cbm_log_info("server.start", "version", CBM_VERSION);
cbm_diag_start(); /* starts if CBM_DIAGNOSTICS=1 */
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 65c8233da..19a326c1a 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -4943,7 +4943,10 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
return NULL;
}
+ struct timespec req_t0;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &req_t0);
char *result_json = NULL;
+ bool request_logged = false;
if (strcmp(req.method, "initialize") == 0) {
result_json = cbm_mcp_initialize_response(req.params_raw);
@@ -4974,6 +4977,10 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
((long long)(t1.tv_nsec - t0.tv_nsec) / MCP_MS_TO_US);
bool is_err = (result_json != NULL) && (strstr(result_json, "\"isError\":true") != NULL);
cbm_diag_record_query(dur_us, is_err);
+ long long request_dur_us = ((long long)(t1.tv_sec - req_t0.tv_sec) * MCP_S_TO_US) +
+ ((long long)(t1.tv_nsec - req_t0.tv_nsec) / MCP_MS_TO_US);
+ cbm_log_mcp_request(req.method, tool_name, is_err, request_dur_us);
+ request_logged = true;
result_json = inject_update_notice(srv, result_json);
free(tool_name);
@@ -4989,10 +4996,23 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
.error_json = err_obj,
};
char *err = cbm_jsonrpc_format_response(&err_resp);
+ struct timespec t1;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t1);
+ long long dur_us = ((long long)(t1.tv_sec - req_t0.tv_sec) * MCP_S_TO_US) +
+ ((long long)(t1.tv_nsec - req_t0.tv_nsec) / MCP_MS_TO_US);
+ cbm_log_mcp_request(req.method, NULL, true, dur_us);
cbm_jsonrpc_request_free(&req);
return err;
}
+ if (!request_logged) {
+ struct timespec t1;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t1);
+ long long dur_us = ((long long)(t1.tv_sec - req_t0.tv_sec) * MCP_S_TO_US) +
+ ((long long)(t1.tv_nsec - req_t0.tv_nsec) / MCP_MS_TO_US);
+ cbm_log_mcp_request(req.method, NULL, false, dur_us);
+ }
+
cbm_jsonrpc_response_t resp = {
.id = req.id,
.id_str = req.id_str,
diff --git a/src/ui/http_server.c b/src/ui/http_server.c
index 568b47cc0..1f61ef771 100644
--- a/src/ui/http_server.c
+++ b/src/ui/http_server.c
@@ -1386,15 +1386,22 @@ void cbm_http_server_run(cbm_http_server_t *srv) {
if (!conn)
continue; /* timeout — re-check stop flag */
+ uint64_t request_start_ms = cbm_now_ms();
cbm_http_req_t req;
int rc = cbm_httpd_read_request(conn, &req);
if (rc == 0) {
dispatch_request(srv, conn, &req);
+ cbm_log_http_request("graph_ui", req.method, req.path, cbm_http_conn_status(conn),
+ (int64_t)(cbm_now_ms() - request_start_ms), req.body_len,
+ cbm_http_conn_response_bytes(conn));
cbm_http_req_free(&req);
} else if (rc > 0) {
/* Parse/transport error with a known HTTP status (400/408/411/413/431).
* No CORS reflection here — the request was never parsed. */
cbm_http_replyf(conn, rc, "", "bad request");
+ cbm_log_http_request("graph_ui", "", "", cbm_http_conn_status(conn),
+ (int64_t)(cbm_now_ms() - request_start_ms), 0,
+ cbm_http_conn_response_bytes(conn));
}
cbm_httpd_conn_close(conn);
}
diff --git a/src/ui/httpd.c b/src/ui/httpd.c
index 5d1b01e09..fc0bf6431 100644
--- a/src/ui/httpd.c
+++ b/src/ui/httpd.c
@@ -52,6 +52,8 @@ struct cbm_httpd {
struct cbm_http_conn {
cbm_sock_t fd;
int recv_deadline_ms;
+ int response_status;
+ size_t response_bytes;
};
/* ── Small platform helpers ───────────────────────────────────── */
@@ -215,6 +217,14 @@ void cbm_httpd_conn_close(cbm_http_conn_t *c) {
free(c);
}
+int cbm_http_conn_status(const cbm_http_conn_t *c) {
+ return c ? c->response_status : 0;
+}
+
+size_t cbm_http_conn_response_bytes(const cbm_http_conn_t *c) {
+ return c ? c->response_bytes : 0;
+}
+
/* ── Head parsing ─────────────────────────────────────────────── */
static bool header_name_is(const char *line, size_t name_len, const char *name) {
@@ -506,6 +516,8 @@ void cbm_http_reply_buf(cbm_http_conn_t *c, int status, const char *extra_header
size_t len) {
if (!c)
return;
+ c->response_status = status;
+ c->response_bytes = len;
char head[1024];
int hn = snprintf(head, sizeof(head),
"HTTP/1.1 %d %s\r\n"
diff --git a/src/ui/httpd.h b/src/ui/httpd.h
index 75835fee5..d29dce64c 100644
--- a/src/ui/httpd.h
+++ b/src/ui/httpd.h
@@ -95,6 +95,8 @@ void cbm_http_replyf(cbm_http_conn_t *c, int status, const char *extra_headers,
void cbm_http_reply_buf(cbm_http_conn_t *c, int status, const char *extra_headers, const void *data,
size_t len);
+int cbm_http_conn_status(const cbm_http_conn_t *c);
+size_t cbm_http_conn_response_bytes(const cbm_http_conn_t *c);
void cbm_httpd_conn_close(cbm_http_conn_t *c);
/* ── Pure helpers (unit-tested without sockets) ───────────────── */
diff --git a/tests/test_httpd.c b/tests/test_httpd.c
index ca4e66a75..8aea6ccdf 100644
--- a/tests/test_httpd.c
+++ b/tests/test_httpd.c
@@ -12,6 +12,7 @@
*/
#include "../src/foundation/compat.h"
#include "../src/foundation/compat_thread.h"
+#include "../src/foundation/log.h"
#include "test_framework.h"
#include "test_helpers.h"
#include "ui/httpd.h"
@@ -37,6 +38,18 @@ typedef int th_sock_t;
#define TH_SOCK_BAD (-1)
#endif
+static char httpd_log_buf[8192];
+
+static void httpd_capture_log(const char *line) {
+ size_t used = strlen(httpd_log_buf);
+ size_t avail = sizeof(httpd_log_buf) - used;
+ if (avail <= 1)
+ return;
+ int n = snprintf(httpd_log_buf + used, avail, "%s\n", line ? line : "");
+ if (n < 0 || (size_t)n >= avail)
+ httpd_log_buf[sizeof(httpd_log_buf) - 1] = '\0';
+}
+
/* ── Raw-socket test client ───────────────────────────────────── */
static th_sock_t th_connect(int port) {
@@ -535,6 +548,35 @@ TEST(ui_server_slow_request_hits_deadline) {
PASS();
}
+TEST(ui_server_access_log_redacts_query) {
+ httpd_log_buf[0] = '\0';
+ CBMLogLevel prev_level = cbm_log_get_level();
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ cbm_log_set_sink_ex(httpd_capture_log, CBM_LOG_SINK_REPLACE);
+
+ th_server_t ts;
+ ASSERT_EQ(th_server_start(&ts), 0);
+ char resp[4096];
+ int n = th_http(cbm_http_server_port(ts.srv),
+ "GET /definitely/not/here?token=secret HTTP/1.1\r\n\r\n", resp, sizeof(resp));
+ ASSERT_GT(n, 0);
+ ASSERT_EQ(th_status(resp), 404);
+ th_server_stop(&ts);
+
+ cbm_log_set_sink(NULL);
+ cbm_log_set_level(prev_level);
+
+ ASSERT_NOT_NULL(strstr(httpd_log_buf, "msg=http.request"));
+ ASSERT_NOT_NULL(strstr(httpd_log_buf, "component=graph_ui"));
+ ASSERT_NOT_NULL(strstr(httpd_log_buf, "http.request.method=GET"));
+ ASSERT_NOT_NULL(strstr(httpd_log_buf, "url.path=/definitely/not/here"));
+ ASSERT_NOT_NULL(strstr(httpd_log_buf, "http.response.status_code=404"));
+ ASSERT_NULL(strstr(httpd_log_buf, "token"));
+ ASSERT_NULL(strstr(httpd_log_buf, "secret"));
+ PASS();
+}
+
TEST(ui_server_stop_joins_cleanly) {
th_server_t ts;
ASSERT_EQ(th_server_start(&ts), 0);
@@ -578,5 +620,6 @@ SUITE(httpd) {
RUN_TEST(ui_server_nul_in_target_rejected);
RUN_TEST(ui_server_browse_traversal_probe);
RUN_TEST(ui_server_slow_request_hits_deadline);
+ RUN_TEST(ui_server_access_log_redacts_query);
RUN_TEST(ui_server_stop_joins_cleanly);
}
diff --git a/tests/test_log.c b/tests/test_log.c
index 9b87efcc8..8165d8967 100644
--- a/tests/test_log.c
+++ b/tests/test_log.c
@@ -22,9 +22,14 @@ static inline bool cbm_str_contains_raw(const char *s, const char *sub) {
}
static char log_buf[4096];
+static char sink_buf[4096];
static int saved_stderr;
static int pipe_fds[2];
+static void test_log_sink(const char *line) {
+ snprintf(sink_buf, sizeof(sink_buf), "%s", line ? line : "");
+}
+
static void capture_start(void) {
fflush(stderr);
saved_stderr = dup(STDERR_FILENO);
@@ -112,6 +117,86 @@ TEST(log_int_helper) {
PASS();
}
+TEST(log_json_output) {
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_JSON);
+ capture_start();
+ cbm_log_info("test.msg", "key1", "val1", "key2", "line\nbreak");
+ const char *output = capture_end();
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ cbm_log_set_level(CBM_LOG_INFO);
+
+ ASSERT(cbm_str_contains_raw(output, "\"severity\":\"INFO\""));
+ ASSERT(cbm_str_contains_raw(output, "\"message\":\"test.msg\""));
+ ASSERT(cbm_str_contains_raw(output, "\"key1\":\"val1\""));
+ ASSERT(cbm_str_contains_raw(output, "\"key2\":\"line\\nbreak\""));
+ PASS();
+}
+
+TEST(log_text_sanitizes_control_chars) {
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ capture_start();
+ cbm_log_info("test\nmsg", "key", "line\r\nbreak\tvalue");
+ const char *output = capture_end();
+ cbm_log_set_level(CBM_LOG_INFO);
+
+ ASSERT(cbm_str_contains_raw(output, "msg=test_msg"));
+ ASSERT(cbm_str_contains_raw(output, "key=line__break_value"));
+ ASSERT_EQ(output[strlen(output) - 1], '\n');
+ ASSERT_NULL(strchr(output, '\r'));
+ PASS();
+}
+
+TEST(log_sink_tee_keeps_stderr) {
+ sink_buf[0] = '\0';
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ cbm_log_set_sink_ex(test_log_sink, CBM_LOG_SINK_TEE);
+ capture_start();
+ cbm_log_info("tee.msg", "key", "val");
+ const char *output = capture_end();
+ cbm_log_set_sink(NULL);
+ cbm_log_set_level(CBM_LOG_INFO);
+
+ ASSERT(cbm_str_contains_raw(output, "msg=tee.msg"));
+ ASSERT(cbm_str_contains_raw(sink_buf, "msg=tee.msg"));
+ PASS();
+}
+
+TEST(log_operational_helpers) {
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ capture_start();
+ cbm_log_mcp_request("tools/call", "search_graph", false, 1250);
+ cbm_log_http_request("graph_ui", "GET", "/api/layout", 200, 7, 0, 42);
+ const char *output = capture_end();
+ cbm_log_set_level(CBM_LOG_INFO);
+
+ ASSERT(cbm_str_contains_raw(output, "msg=mcp.request"));
+ ASSERT(cbm_str_contains_raw(output, "rpc.method=tools/call"));
+ ASSERT(cbm_str_contains_raw(output, "mcp.tool.name=search_graph"));
+ ASSERT(cbm_str_contains_raw(output, "msg=http.request"));
+ ASSERT(cbm_str_contains_raw(output, "http.request.method=GET"));
+ ASSERT(cbm_str_contains_raw(output, "url.path=/api/layout"));
+ ASSERT(cbm_str_contains_raw(output, "http.response.status_code=200"));
+ PASS();
+}
+
+TEST(log_format_from_env) {
+ cbm_setenv("CBM_LOG_FORMAT", "json", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_format(), CBM_LOG_FORMAT_JSON);
+
+ cbm_setenv("CBM_LOG_FORMAT", "text", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_format(), CBM_LOG_FORMAT_TEXT);
+
+ cbm_unsetenv("CBM_LOG_FORMAT");
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ PASS();
+}
+
/* CBM_LOG_LEVEL parsing — distilled from #414 (closes #413). */
TEST(log_level_from_env_textual) {
cbm_setenv("CBM_LOG_LEVEL", "error", 1);
@@ -191,6 +276,11 @@ SUITE(log) {
RUN_TEST(log_filtered_by_level);
RUN_TEST(log_error_output);
RUN_TEST(log_int_helper);
+ RUN_TEST(log_json_output);
+ RUN_TEST(log_text_sanitizes_control_chars);
+ RUN_TEST(log_sink_tee_keeps_stderr);
+ RUN_TEST(log_operational_helpers);
+ RUN_TEST(log_format_from_env);
RUN_TEST(log_level_from_env_textual);
RUN_TEST(log_level_from_env_numeric);
RUN_TEST(log_level_from_env_invalid_ignored);
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index cf9992731..554c444d7 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -5,6 +5,7 @@
*/
#include "../src/foundation/compat.h"
#include "../src/foundation/compat_fs.h" /* cbm_unlink / cbm_rmdir */
+#include "../src/foundation/log.h"
#include "test_framework.h"
#include <mcp/mcp.h>
#include <store/store.h>
@@ -14,6 +15,12 @@
#include <stdbool.h>
#include <stdio.h>
+static char mcp_log_buf[4096];
+
+static void mcp_capture_log(const char *line) {
+ snprintf(mcp_log_buf, sizeof(mcp_log_buf), "%s", line ? line : "");
+}
+
/* ══════════════════════════════════════════════════════════════════
* JSON-RPC PARSING
* ══════════════════════════════════════════════════════════════════ */
@@ -406,6 +413,34 @@ TEST(server_handle_tools_list_paginates) {
PASS();
}
+TEST(server_handle_logs_request_without_params) {
+ mcp_log_buf[0] = '\0';
+ CBMLogLevel prev_level = cbm_log_get_level();
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ cbm_log_set_sink_ex(mcp_capture_log, CBM_LOG_SINK_REPLACE);
+
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ char *resp =
+ cbm_mcp_server_handle(srv,
+ "{\"jsonrpc\":\"2.0\",\"id\":210,\"method\":\"tools/list\","
+ "\"params\":{\"token\":\"secret\"}}");
+ ASSERT_NOT_NULL(resp);
+ free(resp);
+ cbm_mcp_server_free(srv);
+
+ cbm_log_set_sink(NULL);
+ cbm_log_set_level(prev_level);
+
+ ASSERT_NOT_NULL(strstr(mcp_log_buf, "msg=mcp.request"));
+ ASSERT_NOT_NULL(strstr(mcp_log_buf, "rpc.system=jsonrpc"));
+ ASSERT_NOT_NULL(strstr(mcp_log_buf, "rpc.method=tools/list"));
+ ASSERT_NOT_NULL(strstr(mcp_log_buf, "status=ok"));
+ ASSERT_NULL(strstr(mcp_log_buf, "token"));
+ ASSERT_NULL(strstr(mcp_log_buf, "secret"));
+ PASS();
+}
+
TEST(server_handle_unknown_method) {
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
@@ -2416,6 +2451,7 @@ SUITE(mcp) {
RUN_TEST(server_handle_initialized_notification);
RUN_TEST(server_handle_tools_list);
RUN_TEST(server_handle_tools_list_paginates);
+ RUN_TEST(server_handle_logs_request_without_params);
RUN_TEST(server_handle_unknown_method);
/* Server handle — edge cases */