ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
log/json.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define LOG_JSON_JSON_BUFFER_SIZE 2048
9#define LOG_JSON_ESCAPED_MESSAGE_BUFFER_SIZE 512
10#define LOG_JSON_ESCAPED_FILE_BUFFER_SIZE 256
11#define LOG_JSON_ESCAPED_FUNC_BUFFER_SIZE 128
12
13#include <ascii-chat/common.h>
14#include <ascii-chat/log/json.h>
15#include <ascii-chat/log/log.h>
16#include <ascii-chat/source_root.h>
20#include <libplatform/compiler.h>
21#include <libplatform/system.h>
22#include <libplatform/terminal.h>
23#include <stdint.h>
24#include <string.h>
25#include <time.h>
26#include <yyjson.h>
27
28/* ============================================================================
29 * Note: log_set_json_output() is implemented in logging.c where the g_log
30 * struct is defined.
31 * ============================================================================
32 */
33
34#include <stdarg.h>
35#include <unistd.h>
36
45static size_t format_timestamp_microseconds(uint64_t time_nanoseconds,
46 char *buf, size_t buf_size) {
47 if (buf_size < 32) {
48 return 0;
49 }
50
51 /* Extract seconds and nanoseconds */
52 time_t seconds = (time_t)(time_nanoseconds / NS_PER_SEC_INT);
53 long nanoseconds = (long)(time_nanoseconds % NS_PER_SEC_INT);
54
55 /* Convert seconds to struct tm */
56 struct tm tm_info;
57 platform_localtime(&seconds, &tm_info);
58
59 /* Format the time part (HH:MM:SS) */
60 size_t len = strftime(buf, buf_size, "%H:%M:%S", &tm_info);
61 if (len == 0 || len >= buf_size) {
62 return 0;
63 }
64
65 /* Convert nanoseconds to microseconds for display */
66 long microseconds = nanoseconds / 1000;
67 if (microseconds < 0) {
68 microseconds = 0;
69 }
70 if (microseconds > 999999) {
71 microseconds = 999999;
72 }
73
74 /* Append microseconds */
75 int result = safe_snprintf(buf + len, buf_size - len, ".%06ld", microseconds);
76 if (result < 0 || result >= (int)(buf_size - len)) {
77 return 0;
78 }
79
80 return len + (size_t)result;
81}
82
89static const char *log_level_to_string(log_level_t level) {
90 switch (level) {
91 case LOG_DEBUG:
92 return "DEBUG";
93 case LOG_INFO:
94 return "INFO";
95 case LOG_WARN:
96 return "WARN";
97 case LOG_ERROR:
98 return "ERROR";
99 case LOG_FATAL:
100 return "FATAL";
101 default:
102 return "UNKNOWN";
103 }
104}
105
106void log_json_write(int fd, log_level_t level, uint64_t time_nanoseconds,
107 const char *file, int line, const char *func,
108 const char *message) {
109 if (fd < 0 || !message) {
110 return;
111 }
112
113 /* Create root object */
114 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
115 if (!doc) {
116 return;
117 }
118
119 yyjson_mut_val *root = yyjson_mut_obj(doc);
120 if (!root) {
121 yyjson_mut_doc_free(doc);
122 return;
123 }
124 yyjson_mut_doc_set_root(doc, root);
125
126 /* Create "header" object */
127 yyjson_mut_val *header = yyjson_mut_obj(doc);
128 if (header) {
129 yyjson_mut_obj_add_val(doc, root, "header", header);
130
131 /* Add timestamp (HH:MM:SS.microseconds) */
132 char timestamp_buf[LOG_TIMESTAMP_BUFFER_SIZE];
133 size_t ts_len = format_timestamp_microseconds(
134 time_nanoseconds, timestamp_buf, sizeof(timestamp_buf));
135 if (ts_len > 0) {
136 yyjson_mut_obj_add_strncpy(doc, header, "timestamp", timestamp_buf,
137 ts_len);
138 }
139
140 /* Add level */
141 yyjson_mut_obj_add_str(doc, header, "level", log_level_to_string(level));
142
143 /* Add thread ID */
144 uint64_t tid = (uint64_t)thread_current_id();
145 yyjson_mut_obj_add_uint(doc, header, "tid", tid);
146
147 /* Add file (if not NULL) - normalize to project-relative path */
148 if (file) {
149 const char *rel_file =
150 extract_project_relative_path(file, ASCIICHAT_OWNED_SOURCE_DIRS);
151 yyjson_mut_obj_add_str(doc, header, "file", rel_file);
152 }
153
154 /* Add line (if > 0) */
155 if (line > 0) {
156 yyjson_mut_obj_add_int(doc, header, "line", line);
157 }
158
159 /* Add func (if not NULL) */
160 if (func) {
161 yyjson_mut_obj_add_str(doc, header, "func", func);
162 }
163 }
164
165 /* Create "body" object with message */
166 yyjson_mut_val *body = yyjson_mut_obj(doc);
167 if (body) {
168 yyjson_mut_obj_add_val(doc, root, "body", body);
169 yyjson_mut_obj_add_str(doc, body, "message", message);
170 }
171
172 /* Serialize to compact JSON (single line, no pretty-printing) */
173 size_t json_len = 0;
174 char *json_str = yyjson_mut_write(doc, 0, &json_len);
175
176 if (json_str && json_len > 0) {
177 // Include the delimiter in the same write so concurrent records stay on
178 // separate lines.
179 json_str[json_len] = '\n';
180 platform_write_all(fd, (const uint8_t *)json_str, json_len + 1);
181
182 /* Free serialized JSON string */
183 free(json_str);
184 }
185
186 /* Free document */
187 yyjson_mut_doc_free(doc);
188}
189
201static size_t json_escape_async_safe(const char *src, char *dest,
202 size_t dest_size) {
203 if (!src || !dest || dest_size < 2) {
204 return 0;
205 }
206
207 size_t pos = 0;
208 const char *p = src;
209 while (*p && pos < dest_size - 1) {
210 char c = *p++;
211 if (c == '"' || c == '\\') {
212 if (pos + 1 < dest_size - 1) {
213 dest[pos++] = '\\';
214 dest[pos++] = c;
215 } else {
216 break;
217 }
218 } else if (c == '\n') {
219 if (pos + 1 < dest_size - 1) {
220 dest[pos++] = '\\';
221 dest[pos++] = 'n';
222 } else {
223 break;
224 }
225 } else if (c == '\r') {
226 if (pos + 1 < dest_size - 1) {
227 dest[pos++] = '\\';
228 dest[pos++] = 'r';
229 } else {
230 break;
231 }
232 } else if (c == '\t') {
233 if (pos + 1 < dest_size - 1) {
234 dest[pos++] = '\\';
235 dest[pos++] = 't';
236 } else {
237 break;
238 }
239 } else if ((unsigned char)c < 32) {
240 /* Skip other control characters */
241 continue;
242 } else if ((unsigned char)c >= 0x80) {
243 // Preserve complete UTF-8 characters when the fixed output buffer fills.
244 const char *character = p - 1;
245 size_t available = 0;
246 while (available < 4 && character[available])
247 available++;
248 int bytes = utf8_next_char_bytes(character, available);
249 if (bytes < 0)
250 continue;
251 if (pos + (size_t)bytes >= dest_size)
252 break;
253 for (int i = 0; i < bytes; ++i)
254 dest[pos++] = character[i];
255 p += bytes - 1;
256 } else {
257 dest[pos++] = c;
258 }
259 }
260 dest[pos] = '\0';
261 return pos;
262}
263
282void log_json_async_safe(int fd, log_level_t level, const char *file, int line,
283 const char *func, const char *message) {
284 if (fd < 0 || !message) {
285 return;
286 }
287
288 /* Format JSON manually on stack using only async-safe operations */
289 char json_buffer[LOG_JSON_JSON_BUFFER_SIZE];
290 char escaped_message[LOG_JSON_ESCAPED_MESSAGE_BUFFER_SIZE];
291 char escaped_file[LOG_JSON_ESCAPED_FILE_BUFFER_SIZE];
292 char escaped_func[LOG_JSON_ESCAPED_FUNC_BUFFER_SIZE];
293 char timestamp_buf[LOG_TIMESTAMP_BUFFER_SIZE];
294
295 /* Escape the strings (normalize file path to project-relative) */
296 json_escape_async_safe(message, escaped_message, sizeof(escaped_message));
297 if (file) {
298 const char *rel_file =
299 extract_project_relative_path(file, ASCIICHAT_OWNED_SOURCE_DIRS);
300 json_escape_async_safe(rel_file, escaped_file, sizeof(escaped_file));
301 } else {
302 escaped_file[0] = '\0';
303 }
304 json_escape_async_safe(func ? func : "", escaped_func, sizeof(escaped_func));
305
306 /* Format timestamp using only async-safe operations */
307 uint64_t time_ns = time_get_realtime_ns();
308 format_timestamp_microseconds(time_ns, timestamp_buf, sizeof(timestamp_buf));
309
310 /* Get thread ID (note: thread_current_id is assumed to be async-safe) */
311 uint64_t tid = (uint64_t)thread_current_id();
312
313 /* Format complete JSON object with timestamp */
314 int written =
315 snprintf(json_buffer, sizeof(json_buffer),
316 "{\"header\":{\"timestamp\":\"%s\",\"level\":\"%s\",\"tid\":%lu,"
317 "\"file\":\"%s\",\"line\":%d,\"func\":\"%s\"},"
318 "\"body\":{\"message\":\"%s\"}}\n",
319 timestamp_buf, log_level_to_string(level), (unsigned long)tid,
320 file ? escaped_file : "", line, func ? escaped_func : "",
321 escaped_message);
322
323 /* Write to fd if successful */
324 if (written > 0 && written < (int)sizeof(json_buffer)) {
325 platform_write_all(fd, (const uint8_t *)json_buffer, (size_t)written);
326 }
327}
unsigned long long uint64_t
unsigned char uint8_t
log_level_t
Logging levels enumeration.
Definition log/types.h:33
#define LOG_TIMESTAMP_BUFFER_SIZE
Maximum size of a timestamp string.
Definition log/log.h:95
#define NS_PER_SEC_INT
Definition time.h:173
const char * extract_project_relative_path(const char *file, const char *const *owned_dirs)
Extract a path relative to the source root embedded by CMake.
Definition path.c:137
int utf8_next_char_bytes(const char *str, size_t max_bytes)
Get byte length of next UTF-8 character.
Definition utf8.c:183
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 JSON structured logging output
void log_json_write(int fd, log_level_t level, uint64_t time_nanoseconds, const char *file, int line, const char *func, const char *message)
Write a log entry as a JSON object to the json output fd.
Definition log/json.c:106
#define LOG_JSON_JSON_BUFFER_SIZE
Definition log/json.c:8
#define LOG_JSON_ESCAPED_MESSAGE_BUFFER_SIZE
Definition log/json.c:9
void log_json_async_safe(int fd, log_level_t level, const char *file, int line, const char *func, const char *message)
Async-safe JSON logging for signal handlers.
Definition log/json.c:282
#define LOG_JSON_ESCAPED_FILE_BUFFER_SIZE
Definition log/json.c:10
#define LOG_JSON_ESCAPED_FUNC_BUFFER_SIZE
Definition log/json.c:11
📝 Logging API with multiple log levels and terminal output control
#define LOG_DEBUG
Definition log/types.h:43
#define LOG_FATAL
Definition log/types.h:47
#define LOG_ERROR
Definition log/types.h:46
#define LOG_WARN
Definition log/types.h:45
#define LOG_INFO
Definition log/types.h:44
📂 Path Manipulation Utilities
🔤 String Manipulation and Shell Escaping Utilities
⏱️ High-precision timing utilities using sokol_time.h and uthash
🔤 UTF-8 Encoding and Decoding Utilities
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57