Skip to content

Commit 59b836e

Browse files
committed
feat(logging): add operational server logs
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent 0d3e24c commit 59b836e

10 files changed

Lines changed: 502 additions & 57 deletions

File tree

‎src/foundation/log.c‎

Lines changed: 260 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -12,47 +12,74 @@
1212
#include <string.h>
1313

1414
static CBMLogLevel g_log_level = CBM_LOG_INFO;
15+
static CBMLogFormat g_log_format = CBM_LOG_FORMAT_TEXT;
1516
static cbm_log_sink_fn g_log_sink = NULL;
17+
static CBMLogSinkMode g_log_sink_mode = CBM_LOG_SINK_REPLACE;
1618

1719
/* CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */
1820
void cbm_log_init_from_env(void) {
1921
/* getenv() is safe here: this runs at startup before any thread is created,
2022
* so there is no concurrent setenv() to race against. */
2123
const char *raw = getenv("CBM_LOG_LEVEL");
22-
if (!raw || raw[0] == '\0') {
23-
return; /* unset/empty: keep the current (default) level — fail-open */
24-
}
25-
26-
/* Textual form, case-insensitive. Index of each name == its enum value. */
27-
static const char *const names[] = {"debug", "info", "warn", "error", "none"};
28-
char lower[8];
29-
size_t i = 0;
30-
for (; i < sizeof(lower) - 1 && raw[i] != '\0'; i++) {
31-
lower[i] = (char)tolower((unsigned char)raw[i]);
32-
}
33-
lower[i] = '\0';
34-
if (raw[i] == '\0') { /* fully consumed — candidate textual match */
35-
for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
36-
if (strcmp(lower, names[lvl]) == 0) {
37-
cbm_log_set_level((CBMLogLevel)lvl);
38-
return;
24+
if (raw && raw[0] != '\0') {
25+
/* Textual form, case-insensitive. Index of each name == its enum value. */
26+
static const char *const names[] = {"debug", "info", "warn", "error", "none"};
27+
char lower[8];
28+
size_t i = 0;
29+
for (; i < sizeof(lower) - 1 && raw[i] != '\0'; i++) {
30+
lower[i] = (char)tolower((unsigned char)raw[i]);
31+
}
32+
lower[i] = '\0';
33+
if (raw[i] == '\0') { /* fully consumed — candidate textual match */
34+
for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
35+
if (strcmp(lower, names[lvl]) == 0) {
36+
cbm_log_set_level((CBMLogLevel)lvl);
37+
goto parse_format;
38+
}
3939
}
4040
}
41+
42+
/* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
43+
char *end = NULL;
44+
long n = strtol(raw, &end, CBM_DECIMAL_BASE);
45+
if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
46+
cbm_log_set_level((CBMLogLevel)n);
47+
}
4148
}
4249

43-
/* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
44-
char *end = NULL;
45-
long n = strtol(raw, &end, CBM_DECIMAL_BASE);
46-
if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
47-
cbm_log_set_level((CBMLogLevel)n);
50+
/* Unrecognised value: leave the level unchanged (fail-open). */
51+
52+
parse_format:;
53+
const char *fmt = getenv("CBM_LOG_FORMAT");
54+
if (fmt && fmt[0] != '\0') {
55+
char lower_fmt[8];
56+
size_t i = 0;
57+
for (; i < sizeof(lower_fmt) - 1 && fmt[i] != '\0'; i++) {
58+
lower_fmt[i] = (char)tolower((unsigned char)fmt[i]);
59+
}
60+
lower_fmt[i] = '\0';
61+
if (fmt[i] == '\0' && strcmp(lower_fmt, "json") == 0) {
62+
cbm_log_set_format(CBM_LOG_FORMAT_JSON);
63+
} else if (fmt[i] == '\0' && strcmp(lower_fmt, "text") == 0) {
64+
cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
65+
}
4866
return;
4967
}
5068

51-
/* Unrecognised value: leave the level unchanged (fail-open). */
69+
const char *env = getenv("ENVIRONMENT");
70+
const char *cloud_run = getenv("K_SERVICE");
71+
if ((env && strcmp(env, "production") == 0) || (cloud_run && cloud_run[0] != '\0')) {
72+
cbm_log_set_format(CBM_LOG_FORMAT_JSON);
73+
}
5274
}
5375

5476
void cbm_log_set_sink(cbm_log_sink_fn fn) {
77+
cbm_log_set_sink_ex(fn, CBM_LOG_SINK_REPLACE);
78+
}
79+
80+
void cbm_log_set_sink_ex(cbm_log_sink_fn fn, CBMLogSinkMode mode) {
5581
g_log_sink = fn;
82+
g_log_sink_mode = mode;
5683
}
5784

5885
void cbm_log_set_level(CBMLogLevel level) {
@@ -63,6 +90,14 @@ CBMLogLevel cbm_log_get_level(void) {
6390
return g_log_level;
6491
}
6592

93+
void cbm_log_set_format(CBMLogFormat format) {
94+
g_log_format = format;
95+
}
96+
97+
CBMLogFormat cbm_log_get_format(void) {
98+
return g_log_format;
99+
}
100+
66101
static const char *level_str(CBMLogLevel level) {
67102
switch (level) {
68103
case CBM_LOG_DEBUG:
@@ -78,54 +113,226 @@ static const char *level_str(CBMLogLevel level) {
78113
}
79114
}
80115

116+
static const char *severity_str(CBMLogLevel level) {
117+
switch (level) {
118+
case CBM_LOG_DEBUG:
119+
return "DEBUG";
120+
case CBM_LOG_INFO:
121+
return "INFO";
122+
case CBM_LOG_WARN:
123+
return "WARNING";
124+
case CBM_LOG_ERROR:
125+
return "ERROR";
126+
default:
127+
return "DEFAULT";
128+
}
129+
}
130+
131+
static void append_char(char *buf, size_t bufsz, size_t *pos, char ch) {
132+
if (*pos < bufsz - 1) {
133+
buf[*pos] = ch;
134+
}
135+
(*pos)++;
136+
}
137+
138+
static void append_raw(char *buf, size_t bufsz, size_t *pos, const char *s) {
139+
if (!s) {
140+
return;
141+
}
142+
while (*s) {
143+
append_char(buf, bufsz, pos, *s++);
144+
}
145+
}
146+
147+
static void append_text_atom(char *buf, size_t bufsz, size_t *pos, const char *s) {
148+
if (!s) {
149+
return;
150+
}
151+
while (*s) {
152+
unsigned char ch = (unsigned char)*s++;
153+
if (ch <= ' ' || ch == 0x7f) {
154+
append_char(buf, bufsz, pos, '_');
155+
} else {
156+
append_char(buf, bufsz, pos, (char)ch);
157+
}
158+
}
159+
}
160+
161+
static void append_json_string(char *buf, size_t bufsz, size_t *pos, const char *s) {
162+
append_char(buf, bufsz, pos, '"');
163+
if (s) {
164+
while (*s) {
165+
unsigned char ch = (unsigned char)*s++;
166+
switch (ch) {
167+
case '"':
168+
append_raw(buf, bufsz, pos, "\\\"");
169+
break;
170+
case '\\':
171+
append_raw(buf, bufsz, pos, "\\\\");
172+
break;
173+
case '\b':
174+
append_raw(buf, bufsz, pos, "\\b");
175+
break;
176+
case '\f':
177+
append_raw(buf, bufsz, pos, "\\f");
178+
break;
179+
case '\n':
180+
append_raw(buf, bufsz, pos, "\\n");
181+
break;
182+
case '\r':
183+
append_raw(buf, bufsz, pos, "\\r");
184+
break;
185+
case '\t':
186+
append_raw(buf, bufsz, pos, "\\t");
187+
break;
188+
default:
189+
if (ch < 0x20) {
190+
static const char hex[] = "0123456789abcdef";
191+
append_raw(buf, bufsz, pos, "\\u00");
192+
append_char(buf, bufsz, pos, hex[ch >> 4]);
193+
append_char(buf, bufsz, pos, hex[ch & 0xf]);
194+
} else {
195+
append_char(buf, bufsz, pos, (char)ch);
196+
}
197+
break;
198+
}
199+
}
200+
}
201+
append_char(buf, bufsz, pos, '"');
202+
}
203+
204+
static void finish_line(char *buf, size_t bufsz, size_t pos) {
205+
if (bufsz == 0) {
206+
return;
207+
}
208+
if (pos >= bufsz) {
209+
buf[bufsz - 1] = '\0';
210+
} else {
211+
buf[pos] = '\0';
212+
}
213+
}
214+
215+
static void emit_line(const char *line) {
216+
if (g_log_sink) {
217+
g_log_sink(line);
218+
if (g_log_sink_mode == CBM_LOG_SINK_REPLACE) {
219+
return;
220+
}
221+
}
222+
(void)fprintf(stderr, "%s\n", line);
223+
}
224+
81225
void cbm_log(CBMLogLevel level, const char *msg, ...) {
82226
if (level < g_log_level) {
83227
return;
84228
}
85229

86-
/* Build the log line into a buffer ONCE — no double va_list iteration */
87-
char line_buf[CBM_SZ_512];
88-
int pos =
89-
snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s", level_str(level), msg ? msg : "");
90-
230+
char line_buf[CBM_SZ_4K];
231+
size_t pos = 0;
91232
va_list args;
92233
va_start(args, msg);
93-
for (;;) {
94-
const char *key = va_arg(args, const char *);
95-
if (!key) {
96-
break;
97-
}
98-
const char *val = va_arg(args, const char *);
99-
if (!val) {
100-
val = "";
234+
235+
if (g_log_format == CBM_LOG_FORMAT_JSON) {
236+
append_raw(line_buf, sizeof(line_buf), &pos, "{\"severity\":");
237+
append_json_string(line_buf, sizeof(line_buf), &pos, severity_str(level));
238+
append_raw(line_buf, sizeof(line_buf), &pos, ",\"message\":");
239+
append_json_string(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
240+
append_raw(line_buf, sizeof(line_buf), &pos, ",\"event\":");
241+
append_json_string(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
242+
for (;;) {
243+
const char *key = va_arg(args, const char *);
244+
if (!key) {
245+
break;
246+
}
247+
const char *val = va_arg(args, const char *);
248+
append_char(line_buf, sizeof(line_buf), &pos, ',');
249+
append_json_string(line_buf, sizeof(line_buf), &pos, key);
250+
append_char(line_buf, sizeof(line_buf), &pos, ':');
251+
append_json_string(line_buf, sizeof(line_buf), &pos, val ? val : "");
101252
}
102-
if ((size_t)pos < sizeof(line_buf) - SKIP_ONE) {
103-
pos += snprintf(line_buf + pos, sizeof(line_buf) - (size_t)pos, " %s=%s", key, val);
253+
append_char(line_buf, sizeof(line_buf), &pos, '}');
254+
} else {
255+
append_raw(line_buf, sizeof(line_buf), &pos, "level=");
256+
append_text_atom(line_buf, sizeof(line_buf), &pos, level_str(level));
257+
append_raw(line_buf, sizeof(line_buf), &pos, " msg=");
258+
append_text_atom(line_buf, sizeof(line_buf), &pos, msg ? msg : "");
259+
for (;;) {
260+
const char *key = va_arg(args, const char *);
261+
if (!key) {
262+
break;
263+
}
264+
const char *val = va_arg(args, const char *);
265+
append_char(line_buf, sizeof(line_buf), &pos, ' ');
266+
append_text_atom(line_buf, sizeof(line_buf), &pos, key);
267+
append_char(line_buf, sizeof(line_buf), &pos, '=');
268+
append_text_atom(line_buf, sizeof(line_buf), &pos, val ? val : "");
104269
}
105270
}
106271
va_end(args);
107272

108-
/* When a sink is registered it takes over all output (exclusive).
109-
* Otherwise write structured log to stderr. */
110-
if (g_log_sink) {
111-
g_log_sink(line_buf);
112-
} else {
113-
(void)fprintf(stderr, "%s\n", line_buf);
114-
}
273+
finish_line(line_buf, sizeof(line_buf), pos);
274+
emit_line(line_buf);
115275
}
116276

117277
void cbm_log_int(CBMLogLevel level, const char *msg, const char *key, int64_t value) {
118-
if (level < g_log_level) {
278+
char value_buf[CBM_SZ_32];
279+
snprintf(value_buf, sizeof(value_buf), "%" PRId64, value);
280+
cbm_log(level, msg, key ? key : "?", value_buf, NULL);
281+
}
282+
283+
static void copy_path_without_query(const char *path, char *out, size_t outsz) {
284+
if (!out || outsz == 0) {
119285
return;
120286
}
287+
out[0] = '\0';
288+
if (!path) {
289+
return;
290+
}
291+
size_t n = 0;
292+
while (path[n] && path[n] != '?' && path[n] != '#' && n < outsz - 1) {
293+
out[n] = path[n];
294+
n++;
295+
}
296+
out[n] = '\0';
297+
}
121298

122-
char line_buf[CBM_SZ_256];
123-
snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s %s=%" PRId64, level_str(level),
124-
msg ? msg : "", key ? key : "?", value);
125-
126-
if (g_log_sink) {
127-
g_log_sink(line_buf);
299+
void cbm_log_mcp_request(const char *method, const char *tool_name, bool is_error,
300+
int64_t duration_us) {
301+
char duration_ms[CBM_SZ_32];
302+
snprintf(duration_ms, sizeof(duration_ms), "%" PRId64, duration_us / 1000);
303+
if (tool_name && tool_name[0] != '\0') {
304+
cbm_log(is_error ? CBM_LOG_WARN : CBM_LOG_INFO, "mcp.request", "rpc.system", "jsonrpc",
305+
"rpc.method", method ? method : "", "mcp.tool.name", tool_name, "status",
306+
is_error ? "error" : "ok", "duration_ms", duration_ms, NULL);
128307
} else {
129-
(void)fprintf(stderr, "%s\n", line_buf);
308+
cbm_log(is_error ? CBM_LOG_WARN : CBM_LOG_INFO, "mcp.request", "rpc.system", "jsonrpc",
309+
"rpc.method", method ? method : "", "status", is_error ? "error" : "ok",
310+
"duration_ms", duration_ms, NULL);
130311
}
131312
}
313+
314+
void cbm_log_http_request(const char *component, const char *method, const char *path, int status,
315+
int64_t duration_ms, size_t request_bytes, size_t response_bytes) {
316+
char safe_path[CBM_SZ_1K];
317+
char status_buf[CBM_SZ_16];
318+
char duration_buf[CBM_SZ_32];
319+
char request_buf[CBM_SZ_32];
320+
char response_buf[CBM_SZ_32];
321+
copy_path_without_query(path, safe_path, sizeof(safe_path));
322+
snprintf(status_buf, sizeof(status_buf), "%d", status);
323+
snprintf(duration_buf, sizeof(duration_buf), "%" PRId64, duration_ms);
324+
snprintf(request_buf, sizeof(request_buf), "%zu", request_bytes);
325+
snprintf(response_buf, sizeof(response_buf), "%zu", response_bytes);
326+
327+
CBMLogLevel level = CBM_LOG_INFO;
328+
if (status >= 500) {
329+
level = CBM_LOG_ERROR;
330+
} else if (status >= 400) {
331+
level = CBM_LOG_WARN;
332+
}
333+
334+
cbm_log(level, "http.request", "component", component ? component : "", "http.request.method",
335+
method ? method : "", "url.path", safe_path, "http.response.status_code", status_buf,
336+
"duration_ms", duration_buf, "http.request.body.size", request_buf,
337+
"http.response.body.size", response_buf, NULL);
338+
}

0 commit comments

Comments
 (0)