ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/log/log.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define LOG_BUFFER_BUFFER_SIZE 8192
4#define LOG_LOG_MSG_BUFFER_SIZE 256
5#define LOG_PARSE_TIMESTAMP_BUFFER_SIZE 64
6#define LOG_LEVEL_BUFFER_SIZE 16
7#define LOG_FILE_PATH_BUFFER_SIZE 256
8#define LOG_FUNC_NAME_BUFFER_SIZE 256
9
10#include <ascii-chat/otel.h>
17
19
21#include <ascii-chat/common.h>
22#include <ascii-chat/source_root.h>
23#include <options/options.h>
24#include <options/rcu.h> // For RCU-based options access
25#include <libplatform/compiler.h>
26#include <libplatform/system.h>
27#include <libplatform/terminal.h>
28#include <libplatform/debug/memory.h>
29#include <libplatform/system.h>
34#include <libplatform/lifecycle.h>
35#include <stdarg.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <time.h>
40#include <fcntl.h>
41#include <sys/stat.h>
42#include <ctype.h>
43
44#include <ascii-chat/log/log.h>
45
46int terminal_choose_log_fd(int level);
47
50#include <ascii-chat/log/mmap.h>
51#include <ascii-chat/log/grep.h>
52#include <ascii-chat/log/json.h>
53#include <libplatform/terminal.h>
54#include <libplatform/systemd.h>
57#include <options/colorscheme.h>
58#include <libplatform/thread.h>
59#include <libplatform/mutex.h>
63
64// Readers pin the session buffer until unregister has drained their appends.
65static atomic_t g_session_log_readers = {0};
66
67/* Platform-specific log hook (weak, can be overridden by platform implementations) */
68__attribute__((weak)) void platform_log_hook(log_level_t level, const char *message) {
69 (void)level;
70 (void)message;
71 // Default: no-op
72}
73
74/* ============================================================================
75 * Logging System Internal State
76 * ============================================================================ */
77
78/* Log context struct - Lock-free logging with mutex-protected rotation
79 *
80 * Design: Logging itself is lock-free using atomic operations and atomic write() syscalls.
81 * Only log rotation uses a mutex, since it involves multiple file operations that must
82 * be atomic as a group (close, read tail, write temp, rename, reopen).
83 *
84 * This structure consolidates all logging system state into a single, named struct
85 * for better auditability and easier initialization/cleanup.
86 */
87#pragma GCC diagnostic push
88#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
89// Console logs never draw over a live screen, even from its rendering callback.
90static void log_terminal_printf(int fd, const char *format, ...) {
92 return;
93 char buffer[LOG_TERMINAL_BUFFER_SIZE];
94 va_list args;
95 va_start(args, format);
96 int length = vsnprintf(buffer, sizeof(buffer), format, args);
97 va_end(args);
98 if (length > 0) {
99 size_t bytes = (size_t)length < sizeof(buffer) ? (size_t)length : sizeof(buffer) - 1;
100 ui_controller_write(fd, buffer, bytes);
101 }
102}
103
104static struct log_system_t {
105 /* Core logging I/O and state */
106 atomic_t file; /* File descriptor (atomic for safe access) */
107 atomic_t json_file; /* JSON output file descriptor (-1 = disabled) */
108 atomic_t level; /* Log level as int for atomic ops */
109 lifecycle_t lifecycle; /* Initialization state machine */
110 char filename[LOG_MSG_BUFFER_SIZE]; /* Store filename (set once at init) */
111 atomic_t current_size; /* Track current file size */
112
113 /* Terminal output control */
114 atomic_t terminal_output_enabled; /* Control stderr output to terminal */
115 atomic_t force_stderr; /* Force all terminal logs to stderr (client mode) */
116 atomic_t terminal_locked; /* True when a thread has exclusive terminal access */
117 atomic_t terminal_owner_thread; /* Thread that owns terminal output (stored as uint64) */
118
119 /* Log level and formatting */
120 atomic_t level_manually_set; /* Track if level was set manually */
121 atomic_t flush_delay_ms; /* Delay between each buffered log flush (0 = disabled) */
122 log_template_t *format; /* Compiled log format (NULL = use default) */
123 log_template_t *format_console_only; /* Console-only format variant */
124 atomic_t has_custom_format; /* True if format was customized */
125
126 /* Terminal capability detection and color scheme */
127 terminal_capabilities_t terminal_caps; /* Detected terminal capabilities */
128 bool terminal_caps_initialized; /* Whether terminal caps were detected */
129 bool terminal_caps_detecting; /* Guard against recursion during detection */
130
131 /* Shutdown state management */
132 bool shutdown_saved_terminal_output; /* Saved state for log_shutdown_begin/end */
133 bool shutdown_in_progress; /* Track if shutdown phase is active */
134
135 /* Log rotation */
136 mutex_t rotation_mutex; /* Mutex for log rotation only (not for logging!) */
137 lifecycle_t rotation_mutex_lifecycle; /* Rotation mutex initialization state machine */
138
139 /* Session-specific logging (splash/status screens) */
140 atomic_ptr_t session_log_buffer; /* Pointer to registered session log buffer (can be NULL) */
141} g_log = {
142 .file = {0}, /* STDERR_FILENO (fd 2) - fd 0 is STDIN (read-only!) */
143 .json_file = {.impl = (uint64_t)-1}, /* -1 = disabled (atomic_t initialized as uint64_t -1) */
144 .level = {0}, /* DEFAULT_LOG_LEVEL */
145 .lifecycle = LIFECYCLE_INIT,
146 .filename = {0},
147 .current_size = {0},
148 .terminal_output_enabled = {1}, /* true */
149 .force_stderr = {0}, /* false */
150 .terminal_locked = {0}, /* false */
151 .terminal_owner_thread = {0},
152 .level_manually_set = {0}, /* false */
153 .flush_delay_ms = {0},
154 .format = NULL,
155 .format_console_only = NULL,
156 .has_custom_format = {0}, /* false */
157 .terminal_caps = {0},
158 .terminal_caps_initialized = false,
159 .terminal_caps_detecting = false,
160 .shutdown_saved_terminal_output = true,
161 .shutdown_in_progress = false,
162 .rotation_mutex_lifecycle = LIFECYCLE_INIT,
163 .session_log_buffer = {0}, /* NULL */
164};
165#pragma GCC diagnostic pop
166
167/* Level strings are defined in format.c (get_level_string_padded / get_level_string) */
168
169/* ============================================================================
170 * Level Strings
171 * ============================================================================
172 * The actual default log format is defined in lib/log/format.c
173 * and accessed via OPT_LOG_TEMPLATE_DEFAULT macro to support different modes.
174 */
175
187 const char *result;
188 switch (level) {
189 case LOG_INFO:
190 result = "INFO "; // 5 chars: INFO + 1 space
191 break;
192 case LOG_WARN:
193 result = "WARN "; // 5 chars: WARN + 1 space
194 break;
195 case LOG_DEV:
196 result = "DEV "; // 5 chars: DEV + 2 spaces
197 break;
198 case LOG_DEBUG:
199 result = "DEBUG"; // 5 chars: DEBUG (no padding needed)
200 break;
201 case LOG_ERROR:
202 result = "ERROR"; // 5 chars: ERROR (no padding needed)
203 break;
204 case LOG_FATAL:
205 result = "FATAL"; // 5 chars: FATAL (no padding needed)
206 break;
207 default:
208 result = "?????"; // Invalid level - return 5 question marks
209 }
210 // Verify length
211 if (strlen(result) != 5) {
212 log_terminal_printf(STDERR_FILENO, "ERROR: get_level_string_padded() returned non-5-char string: '%s' (len=%zu)\n", result, strlen(result));
213 }
214 return result;
215}
216
217#define LOG_COLOR_COUNT 8 /* DEV, DEBUG, WARN, INFO, ERROR, FATAL, GREY, RESET */
218
219/* Semantic colors are resolved through the shared live palette API. */
220
221/* Internal error macro - uses g_log directly, only used in this file */
222#ifdef NDEBUG
223#define LOGGING_INTERNAL_ERROR(error, message, ...) \
224 do { \
225 errno_set_with_message(error, NULL, 0, NULL, message, ##__VA_ARGS__); \
226 static const char *msg_header = "CRITICAL LOGGING SYSTEM ERROR: "; \
227 log_terminal_printf(STDERR_FILENO, "%s %s\n", colored_string(LOG_COLOR_ERROR, msg_header), message); \
228 int _log_fd = atomic_load_int(&g_log.file); \
229 platform_write(_log_fd, msg_header, strlen(msg_header)); \
230 platform_write(_log_fd, message, strlen(message)); \
231 platform_write(_log_fd, "\n", 1); \
232 backtrace_print_simple(0); \
233 } while (0)
234#else
235#define LOGGING_INTERNAL_ERROR(error, message, ...) \
236 do { \
237 errno_set_with_message(error, __FILE__, __LINE__, __func__, message, ##__VA_ARGS__); \
238 static const char *msg_header = "CRITICAL LOGGING SYSTEM ERROR: "; \
239 log_terminal_printf(STDERR_FILENO, "%s %s\n", colored_string(LOG_COLOR_ERROR, msg_header), message); \
240 int _log_fd = atomic_load_int(&g_log.file); \
241 platform_write(_log_fd, msg_header, strlen(msg_header)); \
242 platform_write(_log_fd, message, strlen(message)); \
243 platform_write(_log_fd, "\n", 1); \
244 backtrace_print_simple(0); \
245 } while (0)
246#endif
247
248size_t get_current_time_formatted(char *time_buf) {
249 /* Get wall-clock time in nanoseconds */
250 uint64_t ts_ns = time_get_realtime_ns();
251 // Extract seconds and nanoseconds from total nanoseconds
252 time_t seconds = (time_t)(ts_ns / NS_PER_SEC_INT);
253 long nanoseconds = (long)(ts_ns % NS_PER_SEC_INT);
254 struct tm tm_info;
255 platform_localtime(&seconds, &tm_info);
256 // Format the time part first
257 // strftime returns 0 on error, not negative (and len is size_t/unsigned)
258 size_t len = strftime(time_buf, 32, "%H:%M:%S", &tm_info);
259 if (len == 0 || len >= 32) {
260 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format time");
261 return 0;
262 }
263
264 // Add microseconds manually (convert nanoseconds to microseconds for display)
265 long microseconds = nanoseconds / 1000;
266 if (microseconds < 0)
267 microseconds = 0;
268 if (microseconds > 999999)
269 microseconds = 999999;
270
271 int result = safe_snprintf(time_buf + len, 32 - len, ".%06ld", microseconds);
272 if (result < 0 || result >= (int)(32 - len)) {
273 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format microseconds");
274 return 0;
275 }
276
277 return len + (size_t)result;
278}
279
280char *format_message(const char *format, va_list args) {
281 if (!format) {
282 return NULL;
283 }
284
285 // First, determine the size needed
286 va_list args_copy;
287 va_copy(args_copy, args);
288 int size = safe_vsnprintf(NULL, 0, format, args_copy);
289 va_end(args_copy);
290
291 if (size < 0) {
292 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format context message");
293 return NULL;
294 }
295
296 // Allocate and format the message
297 char *message = SAFE_MALLOC(size + 1, char *);
298 int result = safe_vsnprintf(message, (size_t)size + 1, format, args);
299 if (result < 0) {
300 SAFE_FREE(message);
301 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format context message");
302 return NULL;
303 }
304
305 return message;
306}
307
318static int truncate_at_whole_line(char *buffer, int current_len, size_t max_len) {
319 if (current_len < 0 || (size_t)current_len <= max_len) {
320 return current_len; // No truncation needed
321 }
322
323 // Search backwards from max_len position for last newline
324 int truncate_pos = (int)max_len - 1;
325 while (truncate_pos > 0 && buffer[truncate_pos] != '\n') {
326 truncate_pos--;
327 }
328
329 // If we found a newline, truncate after it
330 if (truncate_pos > 0 && buffer[truncate_pos] == '\n') {
331 truncate_pos++; // Include the newline
332 // NOLINTNEXTLINE(clang-analyzer-security.ArrayBound) - truncate_pos validated by max_len
333 buffer[truncate_pos] = '\0';
334 return truncate_pos;
335 }
336
337 // No newline found, truncate at max_len to be safe
338 truncate_pos = (int)max_len - 1;
339 buffer[truncate_pos] = '\0';
340 return truncate_pos;
341}
342
350static void validate_log_message_utf8(const char *message, const char *source) {
351 if (!message || !source) {
352 return;
353 }
354
355 if (!utf8_is_valid(message)) {
356 // Use fprintf instead of log_warn to avoid infinite recursion
357 // (this function is called from log_msg, which would create a loop)
358 log_terminal_printf(STDERR_FILENO, "[WARN] Invalid UTF-8 detected in %s\n", source);
359 log_terminal_printf(STDERR_FILENO, "[DEBUG] Invalid UTF-8 data: %s\n", message);
360 }
361}
362
363/* ============================================================================
364 * Logging Implementation
365 * ============================================================================
366 */
367
368/* Parse LOG_LEVEL environment variable */
369static log_level_t parse_log_level_from_env(void) {
370 const char *env_level = SAFE_GETENV("LOG_LEVEL");
371 if (!env_level) {
372 return DEFAULT_LOG_LEVEL; // Default level based on build type
373 }
374
375 // Case-insensitive comparison
376 if (platform_strcasecmp(env_level, "DEV") == 0 || strcmp(env_level, "0") == 0) {
377 return LOG_DEV;
378 }
379 if (platform_strcasecmp(env_level, "DEBUG") == 0 || strcmp(env_level, "1") == 0) {
380 return LOG_DEBUG;
381 }
382 if (platform_strcasecmp(env_level, "INFO") == 0 || strcmp(env_level, "2") == 0) {
383 return LOG_INFO;
384 }
385 if (platform_strcasecmp(env_level, "WARN") == 0 || strcmp(env_level, "3") == 0) {
386 return LOG_WARN;
387 }
388 if (platform_strcasecmp(env_level, "ERROR") == 0 || strcmp(env_level, "4") == 0) {
389 return LOG_ERROR;
390 }
391 if (platform_strcasecmp(env_level, "FATAL") == 0 || strcmp(env_level, "5") == 0) {
392 return LOG_FATAL;
393 }
394
395 // Invalid value - return default
396 log_warn("Invalid LOG_LEVEL: %s", env_level);
397 return DEFAULT_LOG_LEVEL;
398}
399
400/* Log rotation function - keeps the tail (recent entries)
401 * REQUIRES: rotation_mutex must be held by caller
402 * This is the only operation that uses a mutex - regular logging is lock-free.
403 */
404static void rotate_log_locked(void) {
405 int file = atomic_load_int(&g_log.file);
406 size_t current_size = atomic_load_u64(&g_log.current_size);
407
408 if (file < 0 || file == STDERR_FILENO || strlen(g_log.filename) == 0) {
409 return;
410 }
411
412 if (current_size < MAX_LOG_SIZE) {
413 return;
414 }
415
416 platform_close(file);
417 atomic_store_int(&g_log.file, -1);
418
419 /* Open file for reading to get the tail */
420 int read_file = platform_open("log_file_read", g_log.filename, O_RDONLY, 0);
421 if (read_file < 0) {
422 log_error("Failed to open file descriptor for log rotation: fd=%d, path=%s", read_file, g_log.filename);
423 /* Fall back to regular truncation */
424 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
425 atomic_store_int(&g_log.file, fd);
426 atomic_store_u64(&g_log.current_size, 0);
427 return;
428 }
429
430 /* Seek to position where we want to start keeping data (keep last 2MB) */
431 size_t keep_size = MAX_LOG_SIZE * 2 / 3; /* Keep last 2MB of 3MB file */
432 if (current_size < keep_size) {
433 platform_close(read_file);
434 /* Fall back to truncation since we don't have enough data to rotate */
435 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
436 atomic_store_int(&g_log.file, fd);
437 atomic_store_u64(&g_log.current_size, 0);
438 return;
439 }
440 if (lseek(read_file, (off_t)(current_size - keep_size), SEEK_SET) == (off_t)-1) {
441 platform_close(read_file);
442 /* Fall back to truncation */
443 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
444 atomic_store_int(&g_log.file, fd);
445 atomic_store_u64(&g_log.current_size, 0);
446 return;
447 }
448
449 /* Skip to next line boundary to avoid partial lines */
450 char c;
451 while (platform_read(read_file, &c, 1) > 0 && c != '\n') {
452 /* Skip characters until newline */
453 }
454
455 /* Read the tail into a temporary file */
456 char temp_filename[PLATFORM_MAX_PATH_LENGTH];
457 int result = safe_snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", g_log.filename);
458 if (result <= 0 || result >= (int)sizeof(temp_filename)) {
459 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format temp filename");
460 platform_close(read_file);
461 int fd = platform_open("log_file_append", g_log.filename, O_CREAT | O_RDWR | O_APPEND, FILE_PERM_PRIVATE);
462 atomic_store_int(&g_log.file, fd);
463 return;
464 }
465
466 int temp_file = platform_open("log_file_temp", temp_filename, O_CREAT | O_WRONLY | O_TRUNC, FILE_PERM_PRIVATE);
467 if (temp_file < 0) {
468 log_warn("Failed to open temporary file descriptor for log rotation: fd=%d, path=%s", temp_file, temp_filename);
469 platform_close(read_file);
470 /* Fall back to truncation */
471 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
472 atomic_store_int(&g_log.file, fd);
473 atomic_store_u64(&g_log.current_size, 0);
474 return;
475 }
476
477 /* Copy tail to temp file */
478 char buffer[LOG_BUFFER_BUFFER_SIZE];
479 ssize_t bytes_read;
480 size_t new_size = 0;
481 while ((bytes_read = platform_read(read_file, buffer, sizeof(buffer))) > 0) {
482 ssize_t written = platform_write(temp_file, buffer, (size_t)bytes_read);
483 if (written != bytes_read) {
484 platform_close(read_file);
485 platform_close(temp_file);
486 unlink(temp_filename);
487 /* Fall back to truncation */
488 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
489 atomic_store_int(&g_log.file, fd);
490 atomic_store_u64(&g_log.current_size, 0);
491 return;
492 }
493 new_size += (size_t)bytes_read;
494 }
495
496 platform_close(read_file);
497 platform_close(temp_file);
498
499 /* Replace original with temp file */
500 if (rename(temp_filename, g_log.filename) != 0) {
501 unlink(temp_filename); /* Clean up temp file */
502 /* Fall back to truncation */
503 int fd = platform_open("log_file_write", g_log.filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
504 atomic_store_int(&g_log.file, fd);
505 atomic_store_u64(&g_log.current_size, 0);
506 return;
507 }
508
509 /* Reopen for appending */
510 int new_fd = platform_open("log_file_append", g_log.filename, O_CREAT | O_RDWR | O_APPEND, FILE_PERM_PRIVATE);
511 if (new_fd < 0) {
512 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to reopen rotated log file: %s", g_log.filename);
513 atomic_store_int(&g_log.file, STDERR_FILENO);
514 g_log.filename[0] = '\0';
515 atomic_store_u64(&g_log.current_size, 0);
516 return;
517 }
518 atomic_store_int(&g_log.file, new_fd);
519 atomic_store_u64(&g_log.current_size, new_size);
520
521 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
523
525 int log_msg_len = safe_snprintf(log_msg, sizeof(log_msg), "[%s] [INFO] Log tail-rotated (kept %zu bytes)\n", time_buf, new_size);
526 if (log_msg_len > 0 && log_msg_len < (int)sizeof(log_msg)) {
527 (void)platform_write(new_fd, log_msg, (size_t)log_msg_len);
528 }
529}
530
531/* Check if rotation is needed and perform it (acquires mutex only if needed) */
532static void maybe_rotate_log(void) {
533 /* Rotation mutex not initialized - skip rotation */
534 if (!lifecycle_is_initialized(&g_log.rotation_mutex_lifecycle)) {
535 return;
536 }
537
538 /* Check mmap path first */
539 if (log_mmap_is_active()) {
540 size_t used = 0, capacity = 0;
541 if (log_mmap_get_usage(&used, &capacity) && capacity > 0) {
542 /* Rotate when 90% full to leave room for writes */
543 if (used > capacity * 9 / 10) {
544 mutex_lock(&g_log.rotation_mutex);
546 mutex_unlock(&g_log.rotation_mutex);
547 }
548 }
549 return;
550 }
551
552 /* File path: quick atomic check - avoid mutex if not needed */
553 size_t current_size = atomic_load_u64(&g_log.current_size);
554 if (current_size < MAX_LOG_SIZE) {
555 return;
556 }
557
558 /* Size exceeded - acquire mutex and rotate */
559 mutex_lock(&g_log.rotation_mutex);
560 rotate_log_locked();
561 mutex_unlock(&g_log.rotation_mutex);
562}
563
564static session_log_buffer_t *g_history;
565
567 return g_history;
568}
569
570void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap) {
571
572 if (!g_history)
573 g_history = session_log_buffer_create();
574
575 // Initialize rotation mutex (only operation that uses a mutex)
576 g_log.rotation_mutex_lifecycle.sync_type = LIFECYCLE_SYNC_MUTEX;
577 g_log.rotation_mutex_lifecycle.sync.mutex = &g_log.rotation_mutex;
578 lifecycle_init(&g_log.rotation_mutex_lifecycle, "log_rotation");
579
580 // Set basic config using atomic stores
581 atomic_store_u64(&g_log.force_stderr, force_stderr);
582 bool preserve_terminal_output = atomic_load_u64(&g_log.terminal_output_enabled);
583
584 // Force logs to stderr if stdout is piped/redirected
585 // This prevents logs from contaminating piped/redirected output in snapshot/batch modes
586 // Per terminal.h: "force stderr when piped to prevent data corruption"
588 atomic_store_bool(&g_log.force_stderr, true);
589 }
590
591 // Close any existing file (atomic load/store)
592 int old_file = atomic_load_int(&g_log.file);
593 if (lifecycle_is_initialized(&g_log.lifecycle) && old_file >= 0 && old_file != STDERR_FILENO) {
594 platform_close(old_file);
595 atomic_store_int(&g_log.file, -1);
596 }
597
598 // Check LOG_LEVEL environment variable
599 const char *env_level_str = SAFE_GETENV("LOG_LEVEL");
600 if (env_level_str) {
601 atomic_store_u64(&g_log.level, (int)parse_log_level_from_env());
602 } else {
603 atomic_store_u64(&g_log.level, (int)level);
604 }
605
606 atomic_store_bool(&g_log.level_manually_set, false);
607 atomic_store_u64(&g_log.current_size, 0);
608
609 if (filename && strcmp(filename, "/dev/null") == 0) {
610 g_log.filename[0] = '\0';
611 atomic_store_int(&g_log.file, -1);
612 atomic_store_bool(&g_log.terminal_output_enabled, false);
613 } else if (filename) {
614 SAFE_STRNCPY(g_log.filename, filename, sizeof(g_log.filename) - 1);
615
616 if (use_mmap) {
617 // Lock-free mmap path - writes go to mmap'd file
618 asciichat_error_t mmap_result = log_mmap_init_simple(filename, 0);
619 if (mmap_result == ASCIICHAT_OK) {
620 atomic_store_int(&g_log.file, -1); // No regular fd - using mmap for file output
621 } else {
622 // Mmap failed - use stderr only (atomic writes, lock-free)
623 if (preserve_terminal_output) {
624 log_terminal_printf(STDERR_FILENO, "Mmap logging failed for %s, using stderr only (lock-free)\n", filename);
625 }
626 atomic_store_int(&g_log.file, STDERR_FILENO);
627 g_log.filename[0] = '\0';
628 }
629 } else {
630 // Lock-free file I/O path - uses atomic write() syscalls
631 int fd = platform_open("log_file", filename, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
632 atomic_store_int(&g_log.file, (fd >= 0) ? fd : STDERR_FILENO);
633 if (fd < 0) {
634 if (preserve_terminal_output) {
635 log_terminal_printf(STDERR_FILENO, "Failed to open log file: %s\n", filename);
636 }
637 g_log.filename[0] = '\0';
638 }
639 }
640 } else {
641 atomic_store_int(&g_log.file, STDERR_FILENO);
642 g_log.filename[0] = '\0';
643 }
644
645 /* Initialize default log format (NULL means use mode-specific default) */
646 log_set_format(NULL, false);
647
648 /* Mark logging system as initialized (state machine transition) */
649 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
650 lifecycle_init(&g_log.lifecycle, "logging");
651 }
652
653 atomic_store_u64(&g_log.terminal_output_enabled, preserve_terminal_output);
654
655 // Reset terminal detection if needed
656 if (g_log.terminal_caps_initialized && !g_log.terminal_caps.detection_reliable) {
657 g_log.terminal_caps_initialized = false;
658 }
659
660 // Detect terminal capabilities
662
663 // NOTE: Color initialization happens separately via log_set_color_scheme()
664 // after options are parsed. Logging works without colors until then.
665 // NOTE: Grep filter initialization happens in main.c after options_init() completes.
666}
667
668void log_destroy(void) {
669 // Destroy mmap logging first (if active)
670 if (log_mmap_is_active()) {
672 }
673
674 // Cleanup grep filter
675 grep_destroy();
676
677 /* Mark logging system as shutdown FIRST (state machine transition)
678 * This signals worker threads to stop logging immediately before we free memory.
679 * This prevents TOCTOU race where a worker thread could see non-NULL format pointer
680 * after we've freed it but before lifecycle_shutdown() is called. */
681 lifecycle_shutdown(&g_log.lifecycle);
682
683 // Cleanup custom format structures: All worker threads have been signaled to stop by this point.
684 // Safe to free templates now without use-after-free concerns.
685 if (g_log.format) {
686 log_template_free(g_log.format);
687 g_log.format = NULL;
688 }
689 if (g_log.format_console_only) {
690 log_template_free(g_log.format_console_only);
691 g_log.format_console_only = NULL;
692 }
693 atomic_store_bool(&g_log.has_custom_format, false);
694
695 // Lock-free cleanup using atomic operations
696 int old_file = atomic_load_int(&g_log.file);
697 if (old_file >= 0 && old_file != STDERR_FILENO) {
698 platform_close(old_file);
699 }
700 atomic_store_int(&g_log.file, -1);
701
702 // Destroy rotation mutex
703 lifecycle_shutdown(&g_log.rotation_mutex_lifecycle);
704}
705
713void log_system_init(void) {
714
715 // Detect terminal capabilities if not already done
717
718 // Initialize color scheme based on terminal capabilities
720}
721
731 // Unregister session log buffer if registered
735 g_history = NULL;
736}
737
739 atomic_store_u64(&g_log.level, (int)level);
740 atomic_store_bool(&g_log.level_manually_set, true);
741}
742
744 return (log_level_t)atomic_load_u64(&g_log.level);
745}
746
748 // Respect --quiet flag: if quiet is set, never enable terminal output
749 // But allow disabling even if options are unavailable (for shutdown cleanup)
750
751 // Only check quiet flag when ENABLING output to avoid deadlock with
752 // concurrent logging from other threads (options_get() can deadlock when
753 // called while other threads are actively logging due to RCU synchronization)
754 if (enabled) {
755 const options_t *opts = options_get();
756 if (opts && opts->quiet) {
757 return; // Silently ignore attempts to enable terminal output when --quiet is set
758 }
759 }
760
761 atomic_store_u64(&g_log.terminal_output_enabled, enabled);
762}
763
765 return atomic_load_u64(&g_log.terminal_output_enabled);
766}
767
769 atomic_store_u64(&g_log.force_stderr, enabled);
770}
771
773 return atomic_load_u64(&g_log.force_stderr);
774}
775
777 atomic_store_int(&g_log.json_file, fd);
778}
779
781 /* Close the current file if it's not stderr */
782 int old_file = atomic_load_int(&g_log.file);
783 if (old_file >= 0 && old_file != STDERR_FILENO) {
784 platform_close(old_file);
785 }
786 /* Redirect file output to stderr */
787 atomic_store_int(&g_log.file, STDERR_FILENO);
788 g_log.filename[0] = '\0';
789}
790
791asciichat_error_t log_set_format(const char *format_str, bool console_only) {
792 /* Free old format if it exists */
793 if (g_log.format) {
794 log_template_free(g_log.format);
795 g_log.format = NULL;
796 }
797 if (g_log.format_console_only) {
798 log_template_free(g_log.format_console_only);
799 g_log.format_console_only = NULL;
800 }
801
802 /* Use default format if NULL or empty string */
803 const char *format_to_use = (format_str && format_str[0] != '\0') ? format_str : OPT_LOG_TEMPLATE_DEFAULT;
804 bool is_custom = (format_str && format_str[0] != '\0');
805
806 /* Parse the format string (always parse, never skip) */
807 log_template_t *parsed_format = log_template_parse(format_to_use, false);
808
809 if (!parsed_format) {
810 log_error("Failed to parse log format: %s", format_to_use);
811 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid log format string");
812 }
813
814 /* If console_only is true, we also need the default format for file output */
815 if (console_only && is_custom) {
817
818 if (!default_format) {
819 log_template_free(parsed_format);
820 log_error("Failed to parse default log format");
821 return SET_ERRNO(ERROR_INVALID_STATE, "Failed to parse default format");
822 }
823 g_log.format = default_format;
824 g_log.format_console_only = parsed_format;
825 } else {
826 g_log.format = parsed_format;
827 g_log.format_console_only = NULL;
828 }
829
830 atomic_store_u64(&g_log.has_custom_format, is_custom);
831 return ASCIICHAT_OK;
832}
833
835 bool expected = atomic_load_bool(&g_log.terminal_locked);
836 while (!atomic_cas_bool(&g_log.terminal_locked, &expected, true)) {
837 // Retry if CAS failed
838 }
839 atomic_store_u64(&g_log.terminal_owner_thread, (uint64_t)thread_self());
840 return expected;
841}
842
843void log_unlock_terminal(bool previous_state) {
844 atomic_store_u64(&g_log.terminal_locked, previous_state);
845 if (!previous_state) {
846 atomic_store_u64(&g_log.terminal_owner_thread, 0);
847 }
848}
849
850void log_set_flush_delay(unsigned int delay_ms) {
851 atomic_store_u64(&g_log.flush_delay_ms, delay_ms);
852}
853
855 // Log rotation is inherently racy without locks - best-effort only
856 // For reliable rotation, use mmap mode or external logrotate
857 int file = atomic_load_int(&g_log.file);
858 if (file >= 0 && file != STDERR_FILENO && strlen(g_log.filename) > 0) {
859 struct stat st;
860 if (fstat(file, &st) == 0 && st.st_size > MAX_LOG_SIZE) {
861 atomic_store_u64(&g_log.current_size, (size_t)st.st_size);
862 }
863 }
864}
865
866/* Helper: Write formatted log entry to file using atomic write() syscall
867 * POSIX guarantees write() is atomic for sizes <= PIPE_BUF (typically 4096 bytes)
868 * Strips ANSI escape codes from the buffer before writing to ensure clean log files.
869 */
870static void write_to_log_file_atomic(const char *buffer, int length, const char *stripped_buffer) {
871 if (length <= 0 || buffer == NULL) {
872 return;
873 }
874
875 if (length > MAX_LOG_SIZE) {
876 return;
877 }
878
879 int file = atomic_load_int(&g_log.file);
880 if (file < 0 || file == STDERR_FILENO) {
881 return;
882 }
883
884 // Use pre-stripped buffer if available (already stripped by caller), otherwise use original
885 const char *write_buf = stripped_buffer ? stripped_buffer : buffer;
886 size_t write_len = stripped_buffer ? strlen(stripped_buffer) : (size_t)length;
887
888 // Single atomic write() call - no locking needed
889 ssize_t written = platform_write(file, write_buf, write_len);
890 if (written > 0) {
891 atomic_fetch_add_u64(&g_log.current_size, (uint64_t)written);
892 maybe_rotate_log();
893 }
894}
895
896/* Helper: Format log message header using the format system
897 * Returns the number of characters written to the buffer
898 */
899static int format_log_header(char *buffer, size_t buffer_size, log_level_t level, const char *timestamp, const char *file, int line, const char *func, bool use_colors, uint64_t time_nanoseconds) {
900 const log_template_t *format = g_log.format;
901 if (!format) {
902 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Log format not initialized");
903 return -1;
904 }
905
906 /* Use log_template_apply() to generate the complete formatted output
907 * Safety: reload format immediately before use. Format is never freed to avoid TOCTOU races. */
908 const log_template_t *format_check = g_log.format;
909 if (!format_check) {
910 /* Format not available - return minimal output */
911 return -1;
912 }
913
914 int written = log_template_apply(format_check, buffer, buffer_size, level, timestamp, file, line, func, thread_current_id(), "", use_colors, time_nanoseconds);
915 if (written < 0 || written >= (int)buffer_size) {
916 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format log header");
917 return -1;
918 }
919
920 return written;
921}
922
923/* Note: Terminal buffering removed for lock-free design.
924 * When terminal is locked, other threads' output goes to file only.
925 */
926
927/* Helper: Write colored log entry to terminal (lock-free)
928 * Uses atomic loads for state checks, skips output if terminal is locked by another thread
929 */
930static _Atomic bool g_terminal_log_colors;
931
932static void write_to_terminal_atomic(log_level_t level, const char *timestamp, const char *file, int line, const char *func, const char *fmt, va_list args, uint64_t time_nanoseconds,
933 bool capture_history) {
934 // Prevent logging during shutdown - if logging lifecycle is being destroyed,
935 // bail out to avoid use-after-free of the log template
936 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
937 return; /* Logging is being shut down, skip */
938 }
939
940 // Choose output file descriptor using unified routing logic
941 bool presenting = ui_controller_is_presenting();
942 int fd = presenting ? STDERR_FILENO : terminal_choose_log_fd(level);
943 FILE *output_stream = (fd == STDERR_FILENO) ? stderr : stdout;
944 // Captured session logs still need formatting, but detecting the console
945 // again would block their producer behind the presentation worker's writes.
946 bool use_colors = presenting ? atomic_load(&g_terminal_log_colors) : terminal_should_color_output(fd, options_terminal_settings());
947 if (!presenting)
948 atomic_store(&g_terminal_log_colors, use_colors);
949
950 // Format message first (needed for status screen capture even if terminal output disabled)
951 char msg_buffer[LOG_MSG_BUFFER_SIZE];
952 va_list args_copy;
953 va_copy(args_copy, args);
954 int msg_len = safe_vsnprintf(msg_buffer, sizeof(msg_buffer), fmt, args_copy);
955 va_end(args_copy);
956
957 // Use message buffer directly as clean message
958 // Stack allocation avoids heap corruption during shutdown signal handling
959 const char *clean_msg = msg_buffer;
960
961 // Use format system to generate the complete log line
962 char colored_log_line[LOG_MSG_BUFFER_SIZE + LOG_HEADER_BUFFER_SIZE];
963 char plain_log_line[LOG_MSG_BUFFER_SIZE + LOG_HEADER_BUFFER_SIZE];
964
965 /* Apply format without colors first (plain version for grep matching)
966 * Load format pointer once to prevent TOCTOU race condition where another
967 * thread frees the format between our check and use. */
968 const log_template_t *format = g_log.format_console_only ? g_log.format_console_only : g_log.format;
969 int plain_len = 0;
970 if (format && lifecycle_is_initialized(&g_log.lifecycle)) { /* Double-check lifecycle is still active */
971 plain_len = log_template_apply(format, plain_log_line, sizeof(plain_log_line), level, timestamp, file, line, func, thread_current_id(), clean_msg, false, time_nanoseconds);
972 }
973
974 /* For colored output, apply format with colors enabled */
975 int colored_len = 0;
976 if (use_colors && plain_len > 0) {
977 const log_template_t *format_check = g_log.format_console_only ? g_log.format_console_only : g_log.format;
978 if (format_check && lifecycle_is_initialized(&g_log.lifecycle)) { /* Re-verify lifecycle before use */
979 colored_len = log_template_apply(format_check, colored_log_line, sizeof(colored_log_line), level, timestamp, file, line, func, thread_current_id(), clean_msg, true, time_nanoseconds);
980 }
981 /* If applying with colors failed, fall back to plain text */
982 if (colored_len <= 0) {
983 // Applying with colors failed - use plain text (no colors)
984 colored_len = plain_len;
985 if (plain_len > 0 && plain_len < (int)sizeof(colored_log_line)) {
986 memcpy(colored_log_line, plain_log_line, (size_t)plain_len + 1);
987 }
988 }
989 } else {
990 /* No colors - use plain text */
991 colored_len = plain_len;
992 if (plain_len > 0 && plain_len < (int)sizeof(colored_log_line)) {
993 memcpy(colored_log_line, plain_log_line, (size_t)plain_len + 1);
994 }
995 }
996
997 if (capture_history)
998 session_log_buffer_append(g_history, colored_len > 0 ? colored_log_line : clean_msg);
999
1000 // Feed log to registered session log buffer (use colored version if available, otherwise plain)
1001 atomic_fetch_add_u64_impl(&g_session_log_readers, 1);
1002 session_log_buffer_t *buf = (session_log_buffer_t *)atomic_ptr_load(&g_log.session_log_buffer);
1003 if (buf && buf != g_history) {
1004 if (colored_len > 0 && colored_len < (int)sizeof(colored_log_line)) {
1005 session_log_buffer_append(buf, colored_log_line);
1006 } else if (plain_len > 0 && plain_len < (int)sizeof(plain_log_line)) {
1007 session_log_buffer_append(buf, plain_log_line);
1008 }
1009 }
1010
1011 atomic_fetch_sub_u64_impl(&g_session_log_readers, 1);
1012
1013 // The session now owns this log entry. Do not filter or flush a suppressed
1014 // stdio write: fflush can wait on console/stdio activity on another thread.
1015 if (presenting)
1016 return;
1017
1018 // Check if terminal output is enabled (atomic load)
1019 bool is_enabled = atomic_load_u64(&g_log.terminal_output_enabled);
1020 if (!is_enabled) {
1021 // Terminal output disabled - return (status screen already captured)
1022 return;
1023 }
1024
1025 // Check if terminal is locked by another thread
1026 if (atomic_load_u64(&g_log.terminal_locked)) {
1027 uint64_t owner = atomic_load_u64(&g_log.terminal_owner_thread);
1028 if (owner != (uint64_t)thread_self()) {
1029 // Terminal locked by another thread - return
1030 return;
1031 }
1032 }
1033
1034 // Handle message formatting errors for terminal output
1035 if (msg_len <= 0 || msg_len >= (int)sizeof(msg_buffer)) {
1036 // Message formatting failed - skip filtering and try direct output
1037 /* A failed format is omitted; args may already have been consumed. */
1038 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "\n");
1039 (void)fflush(output_stream);
1040 return;
1041 }
1042
1043 // Handle log formatting errors
1044 if (colored_len <= 0 || colored_len >= (int)sizeof(colored_log_line) || plain_len <= 0 || plain_len >= (int)sizeof(plain_log_line)) {
1045 // Formatting failed - try to output something
1046 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", clean_msg);
1047 (void)fflush(output_stream);
1048 return;
1049 }
1050
1051 // Apply grep filter (terminal output only - file logs are unfiltered)
1052 // Match against PLAIN text (no ANSI codes) so offsets are correct
1053 size_t match_start = 0, match_len = 0;
1054 if (!grep_should_output(plain_log_line, &match_start, &match_len)) {
1055 return; // No match - suppress terminal output
1056 }
1057
1058 // Output with colors
1059 if (use_colors) {
1060 const char **colors = log_get_color_array();
1061
1062 // When grep matches, highlight in the colored line
1063 if (match_len > 0 && colors != NULL) {
1064 // Apply highlighting to the full line, respecting existing ANSI codes
1065 const char *highlighted_line = grep_highlight_colored(colored_log_line, plain_log_line, match_start, match_len);
1066 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", highlighted_line);
1067 } else {
1068 // No grep match - output colored line as-is
1069 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", colored_log_line);
1070 }
1071 } else {
1072 // No colors - output plain line
1073 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", plain_log_line);
1074 }
1075
1076 (void)fflush(output_stream);
1077}
1078
1079static _Thread_local const char *g_notice_text;
1080static _Thread_local ui_notice_severity_t g_notice_severity;
1081static _Thread_local bool g_notice_record_only;
1082static _Thread_local bool g_notice_unfiltered;
1083
1084static void output_notice(log_level_t level, const char *file, int line, const char *func) {
1085 if (g_notice_record_only)
1086 return;
1087 const char *text = g_notice_text;
1088 ui_notice_severity_t severity = g_notice_severity;
1089 g_notice_text = NULL;
1090 atomic_fetch_add_u64_impl(&g_session_log_readers, 1);
1092 session_log_buffer_append(g_history, text);
1093 if (buffer && buffer != g_history)
1094 session_log_buffer_append(buffer, text);
1095 atomic_fetch_sub_u64_impl(&g_session_log_readers, 1);
1096 // Match the same uncolored template as ordinary terminal logs, including metadata.
1097 // Keep the complete body for notices that span multiple file-log records.
1098 size_t capacity = strlen(text) + LOG_MSG_BUFFER_SIZE + LOG_HEADER_BUFFER_SIZE;
1099 char *plain_log_line = SAFE_MALLOC(capacity, char *);
1100 char timestamp[LOG_PARSE_TIMESTAMP_BUFFER_SIZE];
1101 uint64_t time_ns = time_get_realtime_ns();
1102 get_current_time_formatted(timestamp);
1103 const log_template_t *format = g_log.format;
1104 int plain_len = format && plain_log_line ? log_template_apply(format, plain_log_line, capacity, level, timestamp, file, line, func, thread_current_id(), text, false, time_ns) : -1;
1105 size_t start = 0, length = 0;
1106 if (!GET_OPTION(quiet) && (log_get_terminal_output() || ui_controller_is_presenting() || severity == UI_NOTICE_FATAL) && plain_len > 0 && (size_t)plain_len < capacity &&
1107 grep_should_output(plain_log_line, &start, &length))
1108#ifdef EMSCRIPTEN_BUILD
1109 log_plain("%s", text);
1110#else
1111 if (ui_notice_present(severity, text) == ERROR_BUFFER_FULL)
1112 log_warn_every(US_PER_SEC_INT, "Notice display queue is full; additional notices remain in the log");
1113#endif
1114 SAFE_FREE(plain_log_line);
1115 g_notice_text = text;
1116}
1117
1118static void notice_logv(ui_notice_severity_t severity, bool unfiltered, const char *file, int line, const char *func, const char *title, const char *format, va_list args) {
1119 if (!title || !format || !lifecycle_is_initialized(&g_log.lifecycle))
1120 return;
1121 char *body = format_message(format, args);
1122 if (!body)
1123 return;
1124 size_t size = strlen(title) + strlen(body) + 2;
1125 char *message = SAFE_MALLOC(size, char *);
1126 if (!message) {
1127 SAFE_FREE(body);
1128 return;
1129 }
1130 safe_snprintf(message, size, "%s\n%s", title, body);
1131 const char *previous = g_notice_text;
1132 ui_notice_severity_t previous_severity = g_notice_severity;
1133 bool previous_unfiltered = g_notice_unfiltered;
1134 g_notice_text = message;
1135 g_notice_severity = severity;
1136 g_notice_unfiltered = unfiltered;
1137 log_level_t level = severity == UI_NOTICE_FATAL ? LOG_FATAL : severity == UI_NOTICE_DANGER ? LOG_ERROR : severity == UI_NOTICE_WARNING ? LOG_WARN : LOG_INFO;
1138 if (strlen(message) < 3000) {
1139 log_msg(level, file, line, func, "%s", message);
1140 } else {
1141 bool previous_record_only = g_notice_record_only;
1142 g_notice_record_only = true;
1143 const char *cursor = message;
1144 while (*cursor) {
1145 size_t bytes = strlen(cursor);
1146 if (bytes > 3000) {
1147 bytes = 3000;
1148 while (bytes && ((unsigned char)cursor[bytes] & 0xc0) == 0x80)
1149 --bytes;
1150 if (!bytes)
1151 bytes = 3000; // Malformed UTF-8 must still make progress.
1152 }
1153 log_msg(level, file, line, func, "%.*s", (int)bytes, cursor);
1154 cursor += bytes;
1155 }
1156 g_notice_record_only = previous_record_only;
1157 if ((unfiltered || level >= log_get_level()) && atomic_load_int(&g_log.json_file) < 0)
1158 output_notice(level, file, line, func);
1159 }
1160 g_notice_text = previous;
1161 g_notice_severity = previous_severity;
1162 g_notice_unfiltered = previous_unfiltered;
1163 SAFE_FREE(message);
1164 SAFE_FREE(body);
1165}
1166
1167void ui_notice_log(ui_notice_severity_t severity, const char *file, int line, const char *func, const char *title, const char *format, ...) {
1168 va_list args;
1169 va_start(args, format);
1170 notice_logv(severity, false, file, line, func, title, format, args);
1171 va_end(args);
1172}
1173
1174void ui_notice_announce(const char *file, int line, const char *func, const char *title, const char *format, ...) {
1175 va_list args;
1176 va_start(args, format);
1177 notice_logv(UI_NOTICE_INFO, true, file, line, func, title, format, args);
1178 va_end(args);
1179}
1180
1181void log_msg(log_level_t level, const char *file, int line, const char *func, const char *fmt, ...) {
1182#ifndef __EMSCRIPTEN__
1183 va_list telemetry_args;
1184 va_start(telemetry_args, fmt);
1185 ascii_otel_log((int)level, file, line, func, fmt, telemetry_args);
1186 va_end(telemetry_args);
1187#endif
1188
1189 // All state access uses atomic operations - fully lock-free
1190 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1191 return;
1192 }
1193
1194 // Safety check: if main format template has been freed during shutdown, skip logging
1195 // This prevents heap-use-after-free when threads call logging after log_destroy() has freed g_log.format
1196 if (!g_log.format) {
1197 return;
1198 }
1199
1200 uint64_t loaded_level = atomic_load_u64(&g_log.level);
1201
1202 if (level < (log_level_t)loaded_level && !(g_notice_text && g_notice_unfiltered)) {
1203 return;
1204 }
1205#ifdef __EMSCRIPTEN__
1206 /* Browser logging is independent of terminal and stdout redirection. */
1207 char browser_message[LOG_MMAP_MSG_BUFFER_SIZE];
1208 va_list browser_args;
1209 va_start(browser_args, fmt);
1210 safe_vsnprintf(browser_message, sizeof(browser_message), fmt, browser_args);
1211 va_end(browser_args);
1212 platform_log_hook(level, browser_message);
1213 if (g_notice_text) {
1214 output_notice(level, file, line, func);
1215 } else {
1216 session_log_buffer_append(g_history, browser_message);
1217 }
1218 return;
1219#endif
1220 /* =========================================================================
1221 * MMAP PATH: When mmap logging is active, writes go to mmap'd file
1222 * ========================================================================= */
1223 bool mmap_active = log_mmap_is_active();
1224
1225 if (mmap_active) {
1226 maybe_rotate_log();
1227
1228 va_list args;
1229 va_start(args, fmt);
1230 char msg_buffer[LOG_MMAP_MSG_BUFFER_SIZE];
1231 int msg_len = safe_vsnprintf(msg_buffer, sizeof(msg_buffer), fmt, args);
1232 va_end(args);
1233
1234 // Truncate at whole line boundaries to avoid UTF-8 issues
1235 if (msg_len > 0) {
1236 msg_len = truncate_at_whole_line(msg_buffer, msg_len, sizeof(msg_buffer));
1237 }
1238
1239 // Validate UTF-8 in formatted message
1240 validate_log_message_utf8(msg_buffer, "mmap log message");
1241
1242 if (!g_notice_text)
1243 session_log_buffer_append(g_history, msg_buffer);
1244 log_mmap_write(level, file, line, func, "%s", msg_buffer);
1245 platform_systemd_journal_log(level, msg_buffer, "ascii-chat", file, line, func);
1246
1247 if (g_notice_text) {
1248 output_notice(level, file, line, func);
1249 return;
1250 }
1251
1252 // Terminal output (check with atomic loads)
1253 if (atomic_load_u64(&g_log.terminal_output_enabled) && !atomic_load_bool(&g_log.terminal_locked) && !ui_controller_is_presenting()) {
1254 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1255 uint64_t time_ns = time_get_realtime_ns();
1257
1258 // Choose output stream using unified routing logic
1259 int fd = terminal_choose_log_fd(level);
1260 FILE *output_stream = (fd == STDERR_FILENO) ? stderr : stdout;
1262
1263 char header_buffer[LOG_HEADER_BUFFER_SIZE];
1264 int header_len = format_log_header(header_buffer, sizeof(header_buffer), level, time_buf, file, line, func, use_colors, time_ns);
1265
1266 if (header_len >= 0 && header_len < (int)sizeof(header_buffer)) {
1267 if (use_colors) {
1268 const char *colorized_msg = colorize_log_message(msg_buffer);
1269 const char **colors = log_get_color_array();
1270 if (colors) {
1271 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s%s%s%s\n", header_buffer, colors[LOG_COLOR_RESET], colorized_msg, colors[LOG_COLOR_RESET]);
1272 } else {
1273 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s%s\n", header_buffer, colorized_msg);
1274 }
1275 } else {
1276 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s%s\n", header_buffer, msg_buffer);
1277 }
1278 (void)fflush(output_stream);
1279 }
1280 } else {
1281 }
1282 return;
1283 }
1284 /* =========================================================================
1285 * FILE I/O PATH: Lock-free using atomic write() syscalls
1286 * ========================================================================= */
1287 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1288 uint64_t time_ns = time_get_realtime_ns();
1290 // Format message for file output
1291 char log_buffer[LOG_MSG_BUFFER_SIZE];
1292 va_list args;
1293 va_start(args, fmt);
1294 int header_len = format_log_header(log_buffer, sizeof(log_buffer), level, time_buf, file, line, func, false, time_ns);
1295 if (header_len < 0 || header_len >= (int)sizeof(log_buffer)) {
1296 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format log header");
1297 va_end(args);
1298 return;
1299 }
1300 int msg_len = header_len;
1301 int formatted_len = safe_vsnprintf(log_buffer + header_len, sizeof(log_buffer) - (size_t)header_len, fmt, args);
1302 if (formatted_len < 0) {
1303 LOGGING_INTERNAL_ERROR(ERROR_INVALID_STATE, "Failed to format log message");
1304 va_end(args);
1305 return;
1306 }
1307
1308 msg_len += formatted_len;
1309 // Truncate at whole line boundaries to avoid UTF-8 issues
1310 msg_len = truncate_at_whole_line(log_buffer, msg_len, sizeof(log_buffer));
1311 // Add newline if there's room and message doesn't already end with one
1312 if (msg_len > 0 && msg_len < (int)sizeof(log_buffer) - 1) {
1313 if (log_buffer[msg_len - 1] != '\n') {
1314 log_buffer[msg_len++] = '\n';
1315 log_buffer[msg_len] = '\0';
1316 }
1317 }
1318 va_end(args);
1319 // Validate UTF-8 in formatted message
1320 validate_log_message_utf8(log_buffer, "leveled log message");
1321 platform_systemd_journal_log(level, log_buffer + header_len, "ascii-chat", file, line, func);
1322
1323 // Extract the user message part (without header) for JSON logging
1324 const char *user_message = log_buffer + header_len;
1325
1326 // For JSON output: strip automatic trailing newline (keep explicit ones)
1327 char json_message_buf[LOG_MSG_BUFFER_SIZE];
1328 const char *json_message = user_message;
1329 size_t user_msg_len = strlen(user_message);
1330
1331 // If message ends with newline and it was added automatically (not in original message)
1332 if (user_msg_len > 0 && user_message[user_msg_len - 1] == '\n') {
1333 // The newline was added automatically if the message part didn't end with one
1334 // before we added it on line 1067. We can check this by looking at msg_len - 1
1335 // If msg_len >= header_len + 2, then msg_len - 2 would be the char before the newline
1336 int msg_content_len = msg_len - header_len;
1337 // NOLINTNEXTLINE(clang-analyzer-security.ArrayBound) - msg_content_len > 1 bounds check above
1338 if (msg_content_len > 1 && log_buffer[msg_len - 2] != '\n') {
1339 // Newline was added automatically - strip it for JSON
1340 if (user_msg_len - 1 < sizeof(json_message_buf)) {
1341 memcpy(json_message_buf, user_message, user_msg_len - 1);
1342 json_message_buf[user_msg_len - 1] = '\0';
1343 json_message = json_message_buf;
1344 }
1345 }
1346 }
1347
1348 // Check if JSON format is enabled
1349 int json_fd = atomic_load_int(&g_log.json_file);
1350 bool json_format_enabled = (json_fd >= 0);
1351
1352 // If JSON format is enabled, output ONLY JSON (skip text output)
1353 if (json_format_enabled) {
1354 session_log_buffer_append(g_history, log_buffer);
1355 // Output JSON to the JSON file descriptor
1356 log_json_write(json_fd, level, time_ns, file, line, func, json_message);
1357 // Also output JSON to console using unified routing logic, respecting quiet flag
1358 if (atomic_load_u64(&g_log.terminal_output_enabled)) {
1359 int console_fd = terminal_choose_log_fd(level);
1360 log_json_write(console_fd, level, time_ns, file, line, func, json_message);
1361 }
1362 } else {
1363 // Text format: output to file and terminal
1364 // No heap allocation - use log_buffer directly
1365 // Write to file (atomic write syscall) - use original buffer (with ANSI codes)
1366 int file_fd = (int)atomic_load_u64(&g_log.file);
1367 if (file_fd >= 0 && file_fd != STDERR_FILENO) {
1368 write_to_log_file_atomic(log_buffer, msg_len, NULL);
1369 }
1370
1371 if (g_notice_text) {
1372 output_notice(level, file, line, func);
1373 return;
1374 }
1375
1376 // Write to terminal (atomic state checks)
1377 va_list args_terminal;
1378 va_start(args_terminal, fmt);
1379 write_to_terminal_atomic(level, time_buf, file, line, func, fmt, args_terminal, time_ns, true);
1380 va_end(args_terminal);
1381 }
1382}
1383
1384void log_terminal_msg(log_level_t level, const char *file, int line, const char *func, const char *fmt, ...) {
1385 // Lock-free: only uses atomic loads, no mutex
1386 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1387 return;
1388 }
1389
1390 if (level < (log_level_t)atomic_load_u64(&g_log.level)) {
1391 return;
1392 }
1393
1394 // Terminal output only - no file/mmap writing
1395 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1396 uint64_t time_ns = time_get_realtime_ns();
1398
1399 va_list args;
1400 va_start(args, fmt);
1401 write_to_terminal_atomic(level, time_buf, file, line, func, fmt, args, time_ns, true);
1402 va_end(args);
1403}
1404
1405static void log_colored_msg_internal(log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message, bool persist) {
1406 if (!colored_message || !plain_message || !lifecycle_is_initialized(&g_log.lifecycle)) {
1407 return;
1408 }
1409 if (level < (log_level_t)atomic_load_u64(&g_log.level)) {
1410 return;
1411 }
1412
1413 bool presenting = ui_controller_is_presenting();
1414 int fd = presenting ? STDERR_FILENO : terminal_choose_log_fd(level);
1415 bool use_colors = presenting ? atomic_load(&g_terminal_log_colors) : terminal_should_color_output(fd, options_terminal_settings());
1416 if (!presenting) {
1417 atomic_store(&g_terminal_log_colors, use_colors);
1418 }
1419
1420 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1421 uint64_t time_ns = time_get_realtime_ns();
1423
1424 char colored_header[LOG_HEADER_BUFFER_SIZE] = {0};
1425 char plain_header[LOG_HEADER_BUFFER_SIZE] = {0};
1426 if (format_log_header(colored_header, sizeof(colored_header), level, time_buf, file, line, func, use_colors, time_ns) < 0) {
1427 colored_header[0] = '\0';
1428 }
1429 if (format_log_header(plain_header, sizeof(plain_header), level, time_buf, file, line, func, false, time_ns) < 0) {
1430 plain_header[0] = '\0';
1431 }
1432
1433 char colored_entry[LOG_TERMINAL_ENTRY_BUFFER_SIZE];
1434 char plain_entry[LOG_TERMINAL_ENTRY_BUFFER_SIZE];
1435 safe_snprintf(colored_entry, sizeof(colored_entry), "%s%s", colored_header, colored_message);
1436 safe_snprintf(plain_entry, sizeof(plain_entry), "%s%s", plain_header, plain_message);
1437
1438 int json_fd = atomic_load_int(&g_log.json_file);
1439 if (persist && json_fd >= 0) {
1440 log_json_write(json_fd, level, time_ns, file, line, func, plain_message);
1441 } else if (persist && log_mmap_is_active()) {
1442 log_mmap_write(level, file, line, func, "%s", plain_message);
1443 } else if (persist) {
1444 int file_fd = atomic_load_int(&g_log.file);
1445 if (file_fd >= 0 && file_fd != STDERR_FILENO) {
1446 write_to_log_file_atomic(plain_entry, (int)strlen(plain_entry), NULL);
1447 }
1448 }
1449
1450 const char *terminal_message = use_colors ? colored_entry : plain_entry;
1451 session_log_buffer_append(g_history, json_fd >= 0 ? plain_message : terminal_message);
1452 atomic_fetch_add_u64_impl(&g_session_log_readers, 1);
1453 session_log_buffer_t *buffer = (session_log_buffer_t *)atomic_ptr_load(&g_log.session_log_buffer);
1454 if (buffer && buffer != g_history) {
1455 session_log_buffer_append(buffer, json_fd >= 0 ? plain_message : terminal_message);
1456 }
1457 atomic_fetch_sub_u64_impl(&g_session_log_readers, 1);
1458
1459 if (presenting || !atomic_load_u64(&g_log.terminal_output_enabled)) {
1460 return;
1461 }
1462 if (atomic_load_u64(&g_log.terminal_locked)) {
1463 uint64_t owner = atomic_load_u64(&g_log.terminal_owner_thread);
1464 if (owner != (uint64_t)thread_self()) {
1465 return;
1466 }
1467 }
1468
1469 if (json_fd >= 0) {
1470 log_json_write(fd, level, time_ns, file, line, func, plain_message);
1471 return;
1472 }
1473
1474 size_t match_start = 0;
1475 size_t match_len = 0;
1476 if (!grep_should_output(plain_entry, &match_start, &match_len)) {
1477 return;
1478 }
1479
1480 const char *output = terminal_message;
1481 if (use_colors && match_len > 0 && log_get_color_array() != NULL) {
1482 output = grep_highlight_colored(colored_entry, plain_entry, match_start, match_len);
1483 }
1484 size_t output_len = strlen(output);
1485 ui_controller_write(fd, output, output_len);
1486 if (output_len == 0 || output[output_len - 1] != '\n') {
1487 ui_controller_write(fd, "\n", 1);
1488 }
1489}
1490
1491void log_colored_msg_impl(log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message) {
1492 log_colored_msg_internal(level, file, line, func, colored_message, plain_message, true);
1493}
1494
1495void log_terminal_colored_msg_impl(log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message) {
1496 log_colored_msg_internal(level, file, line, func, colored_message, plain_message, false);
1497}
1498
1499void log_plain_msg(const char *fmt, ...) {
1500 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1501 return;
1502 }
1503
1504 char log_buffer[LOG_MSG_BUFFER_SIZE];
1505 va_list args;
1506 va_start(args, fmt);
1507 int msg_len = safe_vsnprintf(log_buffer, sizeof(log_buffer), fmt, args);
1508 va_end(args);
1509
1510 if (msg_len <= 0) {
1511 return;
1512 }
1513
1514 // Truncate at whole line boundaries to avoid UTF-8 issues
1515 msg_len = truncate_at_whole_line(log_buffer, msg_len, sizeof(log_buffer));
1516
1517 // Validate UTF-8 in formatted message
1518 validate_log_message_utf8(log_buffer, "plain text log");
1519
1520 session_log_buffer_append(g_history, log_buffer);
1521
1522 // Write to mmap if active
1523 if (log_mmap_is_active()) {
1524 log_mmap_write(LOG_INFO, NULL, 0, NULL, "%s", log_buffer);
1525 } else {
1526 // Write to file with headers (atomic write syscall)
1527 int file_fd = atomic_load_u64(&g_log.file);
1528 if (file_fd >= 0 && file_fd != STDERR_FILENO) {
1529 // Add header with timestamp and log level to file output
1530 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1531 uint64_t time_ns = time_get_realtime_ns();
1533
1534 char header_buffer[LOG_HEADER_BUFFER_SIZE];
1535 int header_len = format_log_header(header_buffer, sizeof(header_buffer), LOG_INFO, time_buf, "lib/log/logging.c", 0, "log_plain_msg", false, time_ns);
1536
1537 if (header_len > 0) {
1538 write_to_log_file_atomic(header_buffer, header_len, NULL);
1539 }
1540 write_to_log_file_atomic(log_buffer, msg_len, NULL);
1541 write_to_log_file_atomic("\n", 1, NULL);
1542 }
1543 }
1544
1545 // Preserve diagnostics in the log file during shutdown without repainting the terminal.
1547 return;
1548
1549 // Terminal output (atomic state checks)
1550 if (!atomic_load_u64(&g_log.terminal_output_enabled)) {
1551 return;
1552 }
1553 if (atomic_load_u64(&g_log.terminal_locked)) {
1554 uint64_t owner = atomic_load_u64(&g_log.terminal_owner_thread);
1555 if (owner != (uint64_t)thread_self()) {
1556 return;
1557 }
1558 }
1559
1560 // Check if JSON format is enabled
1561 int json_fd = atomic_load_int(&g_log.json_file);
1562 bool json_format_enabled = (json_fd >= 0);
1563
1564 if (json_format_enabled) {
1565 // Output JSON for plain messages too
1566 uint64_t time_ns = time_get_realtime_ns();
1567 int console_fd = terminal_choose_log_fd(LOG_INFO);
1568 log_json_write(console_fd, LOG_INFO, time_ns, __FILE__, __LINE__, "log_plain_msg", log_buffer);
1569 } else {
1570 // Choose output stream using unified routing logic (LOG_INFO level)
1572 FILE *output_stream = (fd == STDERR_FILENO) ? stderr : stdout;
1573
1574 // Apply colorization for TTY output
1576 const char *colorized_msg = colorize_log_message(log_buffer);
1577 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", colorized_msg);
1578 } else {
1579 log_terminal_printf(output_stream == stdout ? STDOUT_FILENO : STDERR_FILENO, "%s\n", log_buffer);
1580 }
1581 (void)fflush(output_stream);
1582 }
1583}
1584
1585// Helper for log_plain_stderr variants (lock-free)
1586static void log_plain_stderr_internal_atomic(const char *fmt, va_list args, bool add_newline) {
1587 char log_buffer[LOG_MSG_BUFFER_SIZE];
1588 int msg_len = safe_vsnprintf(log_buffer, sizeof(log_buffer), fmt, args);
1589
1590 if (msg_len <= 0) {
1591 return;
1592 }
1593
1594 // Truncate at whole line boundaries to avoid UTF-8 issues
1595 msg_len = truncate_at_whole_line(log_buffer, msg_len, sizeof(log_buffer));
1596
1597 // Validate UTF-8 in formatted message
1598 validate_log_message_utf8(log_buffer, "stderr log");
1599 session_log_buffer_append(g_history, log_buffer);
1600
1601 // Write to mmap if active
1602 if (log_mmap_is_active()) {
1603 log_mmap_write(LOG_INFO, NULL, 0, NULL, "%s", log_buffer);
1604 } else {
1605 // Write to file with headers (atomic write syscall)
1606 int file_fd = atomic_load_u64(&g_log.file);
1607 if (file_fd >= 0 && file_fd != STDERR_FILENO) {
1608 // Add header with timestamp and log level to file output
1609 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1610 uint64_t time_ns = time_get_realtime_ns();
1612
1613 char header_buffer[LOG_HEADER_BUFFER_SIZE];
1614 int header_len = format_log_header(header_buffer, sizeof(header_buffer), LOG_INFO, time_buf, "lib/log/logging.c", 0, "log_plain_stderr_msg", false, time_ns);
1615
1616 if (header_len > 0) {
1617 write_to_log_file_atomic(header_buffer, header_len, NULL);
1618 }
1619 write_to_log_file_atomic(log_buffer, msg_len, NULL);
1620 if (add_newline) {
1621 write_to_log_file_atomic("\n", 1, NULL);
1622 }
1623 }
1624 }
1625
1626 // Terminal output (atomic state checks)
1627 if (!atomic_load_u64(&g_log.terminal_output_enabled)) {
1628 return;
1629 }
1630 if (atomic_load_u64(&g_log.terminal_locked)) {
1631 uint64_t owner = atomic_load_u64(&g_log.terminal_owner_thread);
1632 if (owner != (uint64_t)thread_self()) {
1633 return;
1634 }
1635 }
1636
1637 // Write to stderr without colorization (plain output)
1638 if (add_newline) {
1639 log_terminal_printf(STDERR_FILENO, "%s\n", log_buffer);
1640 } else {
1641 log_terminal_printf(STDERR_FILENO, "%s", log_buffer);
1642 }
1643 (void)fflush(stderr);
1644}
1645
1646void log_plain_stderr_msg(const char *fmt, ...) {
1647 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1648 return;
1649 }
1650 if (shutdown_is_requested()) {
1651 return;
1652 }
1653
1654 va_list args;
1655 va_start(args, fmt);
1656 log_plain_stderr_internal_atomic(fmt, args, true);
1657 va_end(args);
1658}
1659
1660void log_plain_stderr_nonewline_msg(const char *fmt, ...) {
1661 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1662 return;
1663 }
1664 if (shutdown_is_requested()) {
1665 return;
1666 }
1667
1668 va_list args;
1669 va_start(args, fmt);
1670 log_plain_stderr_internal_atomic(fmt, args, false);
1671 va_end(args);
1672}
1673
1679static void log_plain_stdout_internal_atomic(const char *fmt, va_list args, bool add_newline) {
1680 char log_buffer[LOG_MSG_BUFFER_SIZE];
1681 int msg_len = safe_vsnprintf(log_buffer, sizeof(log_buffer), fmt, args);
1682
1683 if (msg_len <= 0) {
1684 return;
1685 }
1686
1687 // Truncate at whole line boundaries to avoid UTF-8 issues
1688 msg_len = truncate_at_whole_line(log_buffer, msg_len, sizeof(log_buffer));
1689
1690 // Validate UTF-8 in formatted message
1691 validate_log_message_utf8(log_buffer, "stdout log");
1692 session_log_buffer_append(g_history, log_buffer);
1693
1694 // Write to mmap if active
1695 if (log_mmap_is_active()) {
1696 log_mmap_write(LOG_INFO, NULL, 0, NULL, "%s", log_buffer);
1697 } else {
1698 // Write to file with headers (atomic write syscall)
1699 int file_fd = atomic_load_u64(&g_log.file);
1700 if (file_fd >= 0 && file_fd != STDOUT_FILENO) {
1701 // Add header with timestamp and log level to file output
1702 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
1703 uint64_t time_ns = time_get_realtime_ns();
1705
1706 char header_buffer[LOG_HEADER_BUFFER_SIZE];
1707 int header_len = format_log_header(header_buffer, sizeof(header_buffer), LOG_INFO, time_buf, "lib/log/logging.c", 0, "log_plain_stdout_msg", false, time_ns);
1708
1709 if (header_len > 0) {
1710 write_to_log_file_atomic(header_buffer, header_len, NULL);
1711 }
1712 write_to_log_file_atomic(log_buffer, msg_len, NULL);
1713 if (add_newline) {
1714 write_to_log_file_atomic("\n", 1, NULL);
1715 }
1716 }
1717 }
1718
1719 // Terminal output (atomic state checks)
1720 if (!atomic_load_u64(&g_log.terminal_output_enabled)) {
1721 return;
1722 }
1723 if (atomic_load_u64(&g_log.terminal_locked)) {
1724 uint64_t owner = atomic_load_u64(&g_log.terminal_owner_thread);
1725 if (owner != (uint64_t)thread_self()) {
1726 return;
1727 }
1728 }
1729
1730 // Write to stdout without colorization (plain output)
1731 if (add_newline) {
1732 log_terminal_printf(STDOUT_FILENO, "%s\n", log_buffer);
1733 } else {
1734 log_terminal_printf(STDOUT_FILENO, "%s", log_buffer);
1735 }
1736}
1737
1738void log_plain_stdout_msg(const char *fmt, ...) {
1739 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1740 return;
1741 }
1742 if (shutdown_is_requested()) {
1743 return;
1744 }
1745
1746 va_list args;
1747 va_start(args, fmt);
1748 log_plain_stdout_internal_atomic(fmt, args, true);
1749 va_end(args);
1750}
1751
1752void log_file_msg(const char *fmt, ...) {
1753 if (!lifecycle_is_initialized(&g_log.lifecycle)) {
1754 return;
1755 }
1756
1757 char log_buffer[LOG_MSG_BUFFER_SIZE];
1758 va_list args;
1759 va_start(args, fmt);
1760 int msg_len = safe_vsnprintf(log_buffer, sizeof(log_buffer), fmt, args);
1761 va_end(args);
1762
1763 if (msg_len <= 0) {
1764 return;
1765 }
1766
1767 // Truncate at whole line boundaries to avoid UTF-8 issues
1768 msg_len = truncate_at_whole_line(log_buffer, msg_len, sizeof(log_buffer));
1769
1770 // Validate UTF-8 in formatted message
1771 validate_log_message_utf8(log_buffer, "file-only log");
1772 session_log_buffer_append(g_history, log_buffer);
1773
1774 // Write to mmap if active, else to file
1775 if (log_mmap_is_active()) {
1776 log_mmap_write(LOG_INFO, NULL, 0, NULL, "%s", log_buffer);
1777 } else {
1778 int file_fd = atomic_load_u64(&g_log.file);
1779 if (file_fd >= 0 && file_fd != STDERR_FILENO) {
1780 write_to_log_file_atomic(log_buffer, msg_len, NULL);
1781 write_to_log_file_atomic("\n", 1, NULL);
1782 }
1783 }
1784}
1785
1786static const char *log_network_direction_label(remote_log_direction_t direction) {
1787 switch (direction) {
1789 return "server→client";
1791 return "client→server";
1792 default:
1793 return "network";
1794 }
1795}
1796
1797asciichat_error_t log_net_message(struct acip_transport *transport, log_level_t level, remote_log_direction_t direction, const char *file, int line, const char *func, const char *fmt, ...) {
1798 if (!fmt) {
1799 return SET_ERRNO(ERROR_INVALID_PARAM, "Format string is NULL");
1800 }
1801
1802 va_list args_copy;
1803 va_start(args_copy, fmt);
1805 char *formatted = format_message(fmt, args_copy);
1806 va_end(args_copy);
1807
1808 if (!formatted) {
1810 asciichat_error_t current_error = errno_peek_since(format_scope, &current) ? current.code : ASCIICHAT_OK;
1811 if (current_error == ASCIICHAT_OK) {
1812 current_error = SET_ERRNO(ERROR_MEMORY, "Failed to format network log message");
1813 }
1814 return current_error;
1815 }
1816
1817 asciichat_error_t send_result = ASCIICHAT_OK;
1818 if (!transport) {
1819 send_result = SET_ERRNO(ERROR_INVALID_PARAM, "Missing log transport");
1820 log_msg(LOG_WARN, file, line, func, "Skipping remote log message: transport unavailable");
1821 } else {
1822 send_result = acip_send_remote_log(transport, level, direction, formatted);
1823 if (send_result != ASCIICHAT_OK) {
1824 log_msg(LOG_WARN, file, line, func, "Failed to send remote log message: %s", asciichat_error_string(send_result));
1825 }
1826 }
1827
1828 const char *direction_label = log_network_direction_label(direction);
1829 log_msg(level, file, line, func, "[NET %s] %s", direction_label, formatted);
1830
1831 SAFE_FREE(formatted);
1832 return send_result;
1833}
1834
1835/* ============================================================================
1836 * Color Helper Functions
1837 * ============================================================================ */
1838
1839/* Initialize terminal capabilities if not already done */
1840static void init_terminal_capabilities(void) {
1841 // Guard against recursion - this can be called indirectly via log_get_color_array()
1842 // from detect_terminal_capabilities() which uses logging
1843 if (g_log.terminal_caps_detecting) {
1844 return;
1845 }
1846
1847 // Terminal capabilities should already be initialized via log_system_init()
1848 // This function is now just a safety guard for any edge cases before init
1849 if (!g_log.terminal_caps_initialized) {
1850 // Set detecting flag to prevent recursion
1851 g_log.terminal_caps_detecting = true;
1852
1853 // Use safe fallback during very early initialization to avoid recursion
1854 g_log.terminal_caps.color_level = TERM_COLOR_16;
1855 g_log.terminal_caps.capabilities = TERM_CAP_COLOR_16;
1856 g_log.terminal_caps.color_count = 16;
1857 g_log.terminal_caps.detection_reliable = false;
1858 g_log.terminal_caps_initialized = true;
1859
1860 // Clear detecting flag
1861 g_log.terminal_caps_detecting = false;
1862 }
1863}
1864
1865/* Re-detect terminal capabilities after logging is initialized */
1867
1868 // Guard against recursion
1869 if (g_log.terminal_caps_detecting) {
1870 return;
1871 }
1872
1873 // Detect if not initialized, or if we're using defaults (not reliably detected)
1874 // This ensures we get proper detection after logging is ready, replacing any defaults
1875 // Once we have reliable detection, never re-detect to keep colors consistent
1876 if (!g_log.terminal_caps_initialized || !g_log.terminal_caps.detection_reliable) {
1877 g_log.terminal_caps_detecting = true;
1879 g_log.terminal_caps_detecting = false;
1880 g_log.terminal_caps_initialized = true;
1881
1882 // Now log the capabilities AFTER colors are set, so this log uses the correct colors
1883 log_debug("Terminal capabilities: color_level=%d, capabilities=0x%x, utf8=%s, fps=%d", g_log.terminal_caps.color_level, g_log.terminal_caps.capabilities,
1884 g_log.terminal_caps.utf8_support ? "yes" : "no", g_log.terminal_caps.desired_fps);
1885
1886 // Now that we've detected once with reliable results, keep these colors consistent for all future logs
1887 } else {
1888 }
1889 // Once initialized with reliable detection, never re-detect to keep colors consistent
1890}
1891
1892/* Get the appropriate color array based on terminal capabilities */
1893static _Thread_local colorscheme_palette_t live_log_palette;
1894static _Thread_local const char *live_log_codes[COLORSCHEME_LOG_COLOR_COUNT];
1895
1896const char **log_get_color_array(void) {
1897 init_terminal_capabilities();
1898 colorscheme_current_palette(&live_log_palette, g_log.terminal_caps.color_level);
1899 for (int i = 0; i < 8; ++i)
1900 live_log_codes[i] = live_log_palette.codes[i];
1901 return live_log_codes;
1902}
1903
1905 init_terminal_capabilities();
1906 return g_log.terminal_caps.color_level;
1907}
1908
1909const char *log_get_foreground_color(void) {
1911 return live_log_palette.foreground;
1912}
1913
1914const char *log_level_color(log_color_t color) {
1915 if (color == LOG_COLOR_WHITE)
1916 return "\033[37m";
1917 const char **colors = log_get_color_array();
1918 if (colors == NULL) {
1919 return ""; /* Return empty string if colors not available */
1920 }
1921 if (color >= 0 && color <= LOG_COLOR_RESET) {
1922 return colors[color];
1923 }
1924 return colors[LOG_COLOR_RESET]; /* Return reset color if invalid */
1925}
1926
1928 if (!enabled)
1929 return "";
1930 if (color == LOG_COLOR_WHITE)
1931 return "\033[37m";
1932 static _Thread_local colorscheme_palette_t palette;
1933 // The caller already resolved whether this destination accepts color. Do not
1934 // re-check stdout here: reports can target a terminal independent of stdout.
1935 terminal_color_mode_t mode = GET_OPTION(color_mode);
1936 if (mode == TERM_COLOR_AUTO)
1937 mode = (terminal_color_mode_t)log_get_color_mode();
1938 if (mode == TERM_COLOR_NONE && GET_OPTION(color_mode) == TERM_COLOR_AUTO)
1939 mode = TERM_COLOR_16;
1940 colorscheme_current_palette(&palette, mode);
1941 return palette.codes[color >= 0 && color <= LOG_COLOR_RESET ? color : LOG_COLOR_RESET];
1942}
1943
1944/* ============================================================================
1945 * Color Scheme Management
1946 * ============================================================================ */
1947
1949 if (g_log.terminal_caps_detecting || !lifecycle_is_initialized(&g_log.lifecycle))
1950 return;
1952}
1953
1955 colorscheme_apply(scheme);
1956}
1957
1958/* ============================================================================
1959 * Lock-Free MMAP Logging Integration
1960 * ============================================================================ */
1961
1962asciichat_error_t log_enable_mmap(const char *log_path) {
1963 return log_enable_mmap_sized(log_path, 0); /* Use default size */
1964}
1965
1966asciichat_error_t log_enable_mmap_sized(const char *log_path, size_t max_size) {
1967 if (!log_path) {
1968 return SET_ERRNO(ERROR_INVALID_PARAM, "log_path is required");
1969 }
1970
1971 // Initialize mmap logging - text is written directly to the mmap'd file
1972 asciichat_error_t result = log_mmap_init_simple(log_path, max_size);
1973 if (result != ASCIICHAT_OK) {
1974 return result;
1975 }
1976
1977 log_info("Lock-free mmap logging enabled: %s", log_path);
1978 return ASCIICHAT_OK;
1979}
1980
1982 if (log_mmap_is_active()) {
1984 log_info("Lock-free mmap logging disabled");
1985 }
1986}
1987
1988/* ============================================================================
1989 * Shutdown Logging Control
1990 * ============================================================================ */
1991
1993 if (g_log.shutdown_in_progress) {
1994 return; /* Already in shutdown phase */
1995 }
1996
1997 /* Save current terminal output state and disable console output */
1998 g_log.shutdown_saved_terminal_output = atomic_load_u64(&g_log.terminal_output_enabled);
1999 atomic_store_bool(&g_log.terminal_output_enabled, false);
2000 g_log.shutdown_in_progress = true;
2001}
2002
2004 if (!g_log.shutdown_in_progress) {
2005 return; /* Not in shutdown phase, skip terminal state restoration */
2006 }
2007
2008 /* Restore previous terminal output state */
2009 atomic_store_u64(&g_log.terminal_output_enabled, g_log.shutdown_saved_terminal_output);
2010 g_log.shutdown_in_progress = false;
2011}
2012
2020
2021/* ============================================================================
2022 * Session Log Buffer Registration
2023 * ============================================================================ */
2024
2034 atomic_ptr_store(&g_log.session_log_buffer, (void *)buf);
2035}
2036
2043 atomic_ptr_store(&g_log.session_log_buffer, NULL);
2044 // An atomic pointer swap alone does not protect a writer that loaded the old
2045 // buffer. Wait for those writers before the UI releases its storage.
2046 while (atomic_load_u64_impl(&g_session_log_readers))
2047 platform_sleep_us(100);
2048}
2049
2057 return (session_log_buffer_t *)atomic_ptr_load(&g_log.session_log_buffer);
2058}
2059
2060/* ============================================================================
2061 * Log Recoloring for Plain Text Entries
2062 * ============================================================================ */
2063
2070size_t log_recolor_plain_entry(const char *plain_line, char *colored_buf, size_t buf_size) {
2071 if (!plain_line || !colored_buf || buf_size < 128) {
2072 return 0;
2073 }
2074
2075 static char work_buffer[LOG_MSG_BUFFER_SIZE + 1024];
2076
2077 // Parse format FIRST, regardless of color availability
2078 // Parse format: [TIMESTAMP] [LEVEL] [tid:THREAD_ID] FILE:LINE in FUNC(): MESSAGE
2079 const char *p = plain_line;
2080
2081 // Extract timestamp [TIMESTAMP]
2082 if (*p != '[') {
2083 return 0; // Invalid format
2084 }
2085 p++;
2086 const char *timestamp_start = p;
2087
2088 // Find the closing ] for timestamp - look for pattern that ends with proper timestamp format
2089 // Valid timestamp: HH:MM:SS.UUUUUU (time with microseconds, no date)
2090 while (*p && *p != ']') {
2091 p++;
2092 }
2093 if (*p != ']') {
2094 return 0; // Malformed - no closing bracket
2095 }
2096
2097 size_t timestamp_len = p - timestamp_start;
2098 char timestamp[LOG_PARSE_TIMESTAMP_BUFFER_SIZE];
2099 if (timestamp_len >= sizeof(timestamp) || timestamp_len == 0) {
2100 return 0; // Invalid timestamp - empty or too long
2101 }
2102 SAFE_STRNCPY(timestamp, timestamp_start, timestamp_len);
2103 timestamp[timestamp_len] = '\0';
2104 p++; // Skip ]
2105
2106 // Skip whitespace after timestamp
2107 while (*p && *p == ' ') {
2108 p++;
2109 }
2110
2111 // Extract level [LEVEL]
2112 if (*p != '[') {
2113 return 0; // Missing opening bracket for level
2114 }
2115 p++;
2116 const char *level_start = p;
2117 while (*p && *p != ']') {
2118 p++;
2119 }
2120 if (*p != ']') {
2121 return 0; // Missing closing bracket for level
2122 }
2123 size_t level_len = p - level_start;
2124 char level_str[LOG_LEVEL_BUFFER_SIZE];
2125 if (level_len >= sizeof(level_str) || level_len == 0) {
2126 return 0; // Level string too long or empty
2127 }
2128 memcpy(level_str, level_start, level_len);
2129 level_str[level_len] = '\0';
2130
2131 // Determine log level for color selection
2132 log_level_t level = LOG_INFO; // Default
2133 if (strstr(level_str, "DEV") || strstr(level_str, "DEBUG")) {
2134 level = LOG_DEBUG;
2135 } else if (strstr(level_str, "INFO")) {
2136 level = LOG_INFO;
2137 } else if (strstr(level_str, "WARN")) {
2138 level = LOG_WARN;
2139 } else if (strstr(level_str, "ERROR")) {
2140 level = LOG_ERROR;
2141 } else if (strstr(level_str, "FATAL")) {
2142 level = LOG_FATAL;
2143 }
2144
2145 p++; // Skip ]
2146
2147 // Skip whitespace after level
2148 while (*p && *p == ' ') {
2149 p++;
2150 }
2151
2152 // Extract thread ID [tid:THREAD_ID] - optional field
2153 uint64_t tid = 0;
2154 if (*p == '[' && strncmp(p, "[tid:", 5) == 0) {
2155 p += 5;
2156 char *tid_end = NULL;
2157 tid = strtoull(p, &tid_end, 10);
2158 if (!tid_end || *tid_end != ']') {
2159 // tid parsing failed, but continue anyway (might still recover)
2160 // Try to find the closing bracket
2161 while (*p && *p != ']') {
2162 p++;
2163 }
2164 if (*p == ']') {
2165 p++;
2166 }
2167 } else {
2168 p = tid_end + 1; // Skip past the ]
2169 }
2170 // Skip whitespace after tid
2171 while (*p && *p == ' ') {
2172 p++;
2173 }
2174 }
2175 // tid is optional - continue parsing if not present
2176
2177 // Extract file path (everything up to :LINE)
2178 const char *file_start = p;
2179 while (*p && *p != ':') {
2180 p++;
2181 }
2182 if (*p != ':') {
2183 return 0; // Malformed
2184 }
2185 size_t file_len = p - file_start;
2187 if (file_len >= sizeof(file_path)) {
2188 return 0;
2189 }
2190 memcpy(file_path, file_start, file_len);
2191 file_path[file_len] = '\0';
2192 p++; // Skip :
2193
2194 // Extract line number (digits only)
2195 int line_num = 0;
2196 const char *line_start = p;
2197 while (*p && isdigit((unsigned char)*p)) {
2198 p++;
2199 }
2200 if (p == line_start) {
2201 return 0; // No line number
2202 }
2203 line_num = (int)strtol(line_start, NULL, 10);
2204
2205 // Skip whitespace and find "in" keyword (be very lenient)
2206 while (*p && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) {
2207 p++;
2208 }
2209
2210 // Try to find "in " - if not found, might still be valid, just harder to parse
2211 if (strncmp(p, "in ", 3) == 0) {
2212 p += 3; // Skip "in "
2213 } else if (*p == 'i' && *(p + 1) == 'n' && (*(p + 2) == ' ' || *(p + 2) == '\t')) {
2214 // Allow tab after "in"
2215 p += 2; // Skip "in"
2216 while (*p && (*p == ' ' || *p == '\t')) {
2217 p++;
2218 }
2219 } else {
2220 // Missing "in" keyword - this is a format error
2221 return 0;
2222 }
2223
2224 // Extract function name (everything up to "()")
2225 const char *func_start = p;
2226 while (*p && *p != '(') {
2227 p++;
2228 }
2229 if (*p != '(' || func_start == p) {
2230 return 0; // Missing function name or parentheses
2231 }
2232 size_t func_len = p - func_start;
2233
2234 // Trim trailing whitespace from function name
2235 while (func_len > 0 && (func_start[func_len - 1] == ' ' || func_start[func_len - 1] == '\t')) {
2236 func_len--;
2237 }
2238
2239 char func_name[LOG_FUNC_NAME_BUFFER_SIZE];
2240 if (func_len >= sizeof(func_name)) {
2241 func_len = sizeof(func_name) - 1;
2242 }
2243 if (func_len > 0) {
2244 memcpy(func_name, func_start, func_len);
2245 }
2246 func_name[func_len] = '\0';
2247
2248 // Skip "(" and ")" - be lenient about what's between them
2249 if (*p == '(') {
2250 p++;
2251 while (*p && *p != ')') {
2252 p++;
2253 }
2254 if (*p == ')') {
2255 p++;
2256 }
2257 }
2258
2259 // Skip whitespace and optional colon(s) and other separators
2260 while (*p && (*p == ' ' || *p == ':' || *p == '\t')) {
2261 p++;
2262 }
2263
2264 // Remaining is the message
2265 const char *message = p;
2266
2267 // Format is valid, get colors from logging system
2268 const char **colors = log_get_color_array();
2269 if (!colors) {
2270 // No colors available, return plain text
2271 static bool warned_once = false;
2272 if (!warned_once) {
2273 log_debug("Colors not initialized - returning plain text");
2274 warned_once = true;
2275 }
2276 size_t len = strlen(plain_line);
2277 if (len >= buf_size) {
2278 return 0;
2279 }
2280 SAFE_STRNCPY(colored_buf, plain_line, buf_size - 1);
2281 colored_buf[buf_size - 1] = '\0';
2282 return len;
2283 }
2284
2285 // Build colored output
2286 const char *level_color = colors[level];
2287 const char *reset = colors[LOG_COLOR_RESET];
2288 const char *file_color = colors[1]; // DEBUG/Cyan
2289 const char *line_color = colors[6]; // GREY (matching tid)
2290 const char *func_color = colors[0]; // DEV/Orange
2291 const char *tid_color = colors[6]; // GREY
2292
2293 int len = safe_snprintf(work_buffer, sizeof(work_buffer), "[%s%s%s] [%s%s%s] [tid:%s%llu%s] %s%s%s:%s%d%s in %s%s%s(): %s", level_color, timestamp, reset, level_color, level_str, reset, tid_color,
2294 (unsigned long long)tid, reset, file_color, file_path, reset, line_color, line_num, reset, func_color, func_name, reset, message);
2295
2296 if (len <= 0 || len >= (int)sizeof(work_buffer)) {
2297 return 0;
2298 }
2299
2300 // Colorize the message part
2301 const char *colorized_msg = colorize_log_message(message);
2302 len = safe_snprintf(work_buffer, sizeof(work_buffer), "[%s%s%s] [%s%s%s] [tid:%s%llu%s] %s%s%s:%s%d%s in %s%s%s(): %s", level_color, timestamp, reset, level_color, level_str, reset, tid_color,
2303 (unsigned long long)tid, reset, file_color, file_path, reset, line_color, line_num, reset, func_color, func_name, reset, colorized_msg);
2304
2305 if (len <= 0 || len >= (int)sizeof(work_buffer) || len >= (int)buf_size) {
2306 return 0;
2307 }
2308
2309 SAFE_STRNCPY(colored_buf, work_buffer, buf_size - 1);
2310 colored_buf[buf_size - 1] = '\0';
2311 return (size_t)len;
2312}
2313
2314// Internal implementation - don't use directly, use log_console_impl macro
2315void log_console_impl(log_level_t level, const char *file, int line, const char *func, const char *message) {
2316 if (!message) {
2317 return;
2318 }
2319
2320 int fd = terminal_choose_log_fd(level);
2321 if (fd < 0) {
2322 return;
2323 }
2324
2325 // Presentation owns terminal output, but never changes the caller's logging preference.
2327 return;
2328 }
2329
2330 // Check if JSON output is enabled (json_file >= 0 means enabled)
2331 int json_fd = atomic_load_int(&g_log.json_file);
2332 bool use_json = (json_fd >= 0);
2333
2334 if (use_json) {
2335 // Use async-safe JSON formatter (safe for signal handlers)
2336 log_json_async_safe(fd, level, file, line, func, message);
2337 } else {
2338 // Text output to console using platform_write_all to handle partial writes
2339 size_t msg_len = strlen(message);
2340 ui_controller_write(fd, message, msg_len);
2341 if (msg_len == 0 || message[msg_len - 1] != '\n') {
2342 ui_controller_write(fd, "\n", 1);
2343 }
2344 }
2345}
2346
2356void *log_get_template(void) {
2357 return (void *)g_log.format;
2358}
ANSI escape sequence utilities and fast color code generation.
void platform_log_hook(log_level_t level, const char *message)
Definition apple.c:55
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
asciichat_errno_scope_t errno_checkpoint(void)
#define SET_ERRNO(code,...)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
uint64_t atomic_load_u64_impl(const atomic_t *a)
uint64_t atomic_fetch_add_u64_impl(atomic_t *a, uint64_t delta)
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
uint64_t atomic_fetch_sub_u64_impl(atomic_t *a, uint64_t delta)
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
int atomic_load_int(atomic_t *a)
Atomically load an int value.
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.
const char * colorize_log_message(const char *message)
Colorize a log message for terminal output.
Definition colorize.c:530
Log message colorization for terminal output.
void colorscheme_apply(const color_scheme_t *scheme)
const color_scheme_t * colorscheme_get_active_scheme(void)
Get currently active color scheme.
void colorscheme_current_palette(colorscheme_palette_t *palette, terminal_color_mode_t mode)
#define COLORSCHEME_LOG_COLOR_COUNT
Definition colorscheme.h:40
int color_mode
Definition fft.c:26
unsigned char colors[(512 *256 *2) *3]
Definition fft.c:23
audio_visualization_source_t source
Definition fft.c:25
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
int platform_close(int fd)
Definition filesystem.c:91
ssize_t platform_read(int fd, void *buf, size_t count)
Definition filesystem.c:61
void grep_destroy(void)
Clean up filter resources.
Definition grep.c:995
bool grep_should_output(const char *log_line, size_t *match_start, size_t *match_len)
Check if log line should be output (matches filter).
Definition grep.c:510
bool enabled
Is filtering active?
Definition grep.c:62
int buffer_size
Size of circular buffer.
Definition grep.c:68
const char * grep_highlight_colored(const char *colored_text, const char *plain_text, size_t match_start, size_t match_len)
Highlight matches in colored text while preserving original colors.
Definition grep.c:665
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
#define PLATFORM_MAX_PATH_LENGTH
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_BUFFER_FULL
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
void log_truncate_if_large(void)
Manually truncate large log files.
void log_plain_stderr_nonewline_msg(const char *fmt,...)
Plain logging to stderr without trailing newline.
void log_plain_msg(const char *fmt,...)
Plain logging without timestamps or levels.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
bool log_get_terminal_output(void)
Get current terminal output setting.
asciichat_error_t log_enable_mmap(const char *log_path)
Enable lock-free mmap-based logging.
void log_init_colors(void)
Initialize logging color system with current terminal capabilities.
void log_system_init(void)
Initialize the logging system internal state (system-level init).
void log_msg(log_level_t level, const char *file, int line, const char *func, const char *fmt,...)
Log a message at a specific level.
void log_shutdown_end(void)
End shutdown phase - restore previous logging settings.
asciichat_error_t log_net_message(struct acip_transport *transport, log_level_t level, remote_log_direction_t direction, const char *file, int line, const char *func, const char *fmt,...)
Log a message to all destinations (network, file, and terminal).
void log_destroy(void)
Destroy the logging system and close log file.
void log_colored_msg_impl(log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message)
Write semantically colored terminal text and an ANSI-free log equivalent.
void log_set_force_stderr(bool enabled)
Force all terminal log output to stderr.
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
log_level_t log_get_level(void)
Get the current minimum log level.
const char ** log_get_color_array(void)
Get the appropriate color array based on terminal capabilities.
const char * log_level_color_for_output(log_color_t color, bool enabled)
const char * log_level_color(log_color_t color)
Get color string for a given color enum.
int log_template_apply(const log_template_t *format, char *buf, size_t buf_size, log_level_t level, const char *timestamp, const char *file, int line, const char *func, uint64_t tid, const char *message, bool use_colors, uint64_t time_nanoseconds)
Apply format to a log entry and write result to buffer.
Definition log/format.c:496
struct session_log_buffer session_log_buffer_t
Thread-safe fixed-size history ring for session-screen log lines.
void log_set_flush_delay(unsigned int delay_ms)
Set the delay between flushing buffered log entries.
const char * log_get_foreground_color(void)
session_log_buffer_t * log_get_session_log_buffer(void)
Get the currently registered session log buffer.
#define LOG_MSG_BUFFER_SIZE
Maximum size of a single log message (including formatting).
Definition log/log.h:91
char * format_message(const char *format, va_list args)
Format a message using va_list.
log_color_t
Color enum for logging - indexes into color arrays.
Definition log/log.h:146
void log_cleanup_colors(void)
Clean up compiled color scheme.
#define LOG_HEADER_BUFFER_SIZE
Maximum size of a log header (timestamp, level, file:line:func).
Definition log/log.h:97
void log_shutdown_begin(void)
Begin shutdown phase - disable console logging but keep file logging.
void log_disable_file_output(void)
Disable file output and use stderr instead.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
bool log_get_force_stderr(void)
Get current force_stderr setting.
void log_set_level(log_level_t level)
Set the minimum log level.
size_t log_recolor_plain_entry(const char *plain_line, char *colored_buf, size_t buf_size)
Recolor a plain (non-colored) log line with proper ANSI codes.
void log_clear_session_log_buffer(void)
Unregister the session log buffer.
void log_plain_stdout_msg(const char *fmt,...)
Plain logging to stdout with newline.
void log_set_session_log_buffer(session_log_buffer_t *buf)
Register a session log buffer with the logger.
void log_system_destroy(void)
Shutdown the logging system internal state (system-level cleanup).
void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
Initialize the logging system.
#define LOG_TERMINAL_BUFFER_SIZE
Definition log/log.h:103
bool log_lock_terminal(void)
Lock terminal output for exclusive access by the calling thread.
log_level_t
Logging levels enumeration.
Definition types.h:33
void log_template_free(log_template_t *format)
Free compiled format structure.
Definition log/format.c:332
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
asciichat_error_t log_set_format(const char *format_str, bool console_only)
Set a custom log format string.
#define LOG_TERMINAL_ENTRY_BUFFER_SIZE
Definition log/log.h:106
log_template_t * log_template_parse(const char *format_str, bool console_only)
Parse a format string into compiled format structure.
Definition log/format.c:328
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
size_t get_current_time_formatted(char *time_buf)
Get current time as formatted string.
asciichat_error_t log_enable_mmap_sized(const char *log_path, size_t max_size)
Enable lock-free mmap logging with custom file size.
#define MAX_LOG_SIZE
Maximum log file size in bytes (3MB) before rotation.
Definition log/log.h:75
void log_file_msg(const char *fmt,...)
Log to file only, no stderr output.
void log_disable_mmap(void)
Disable mmap logging and return to mutex-based logging.
#define LOG_TIMESTAMP_BUFFER_SIZE
Maximum size of a timestamp string.
Definition log/log.h:100
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
void * log_get_template(void)
Get the current log format template.
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:659
int log_get_color_mode(void)
#define LOG_MMAP_MSG_BUFFER_SIZE
Maximum size of a log message in mmap mode.
Definition log/log.h:94
void log_set_color_scheme(const color_scheme_t *scheme)
Set the color scheme for logging output.
void log_plain_stderr_msg(const char *fmt,...)
Plain logging to stderr with newline.
void log_redetect_terminal_capabilities(void)
Re-detect terminal capabilities after logging is initialized.
void log_unlock_terminal(bool previous_state)
Release terminal lock and flush buffered messages.
#define DEFAULT_LOG_LEVEL
Default log level for debug builds (DEBUG and above).
Definition log/log.h:68
void log_terminal_colored_msg_impl(log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message)
Write semantically colored terminal text without persistent logging.
void log_terminal_msg(log_level_t level, const char *file, int line, const char *func, const char *fmt,...)
Log a message to terminal only (no file output).
@ REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT
Definition network/log.h:20
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:20
@ LOG_COLOR_RESET
Definition log/log.h:154
@ LOG_COLOR_WHITE
Definition log/log.h:155
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
#define NS_PER_SEC_INT
Definition time.h:173
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1333
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
#define OPT_LOG_TEMPLATE_DEFAULT
Default log template string (selected based on build mode).
Definition options.h:386
#define options_terminal_settings()
Definition options.h:1287
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:86
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:128
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 JSON structured logging output
session_log_buffer_t * log_get_history_buffer(void)
#define LOG_LEVEL_BUFFER_SIZE
Definition lib/log/log.c:6
#define LOG_FILE_PATH_BUFFER_SIZE
Definition lib/log/log.c:7
int terminal_choose_log_fd(int level)
#define LOG_BUFFER_BUFFER_SIZE
Definition lib/log/log.c:3
#define LOG_PARSE_TIMESTAMP_BUFFER_SIZE
Definition lib/log/log.c:5
#define LOG_LOG_MSG_BUFFER_SIZE
Definition lib/log/log.c:4
void log_set_json_output(int fd)
Set the JSON output file descriptor.
#define LOGGING_INTERNAL_ERROR(error, message,...)
const char * get_level_string_padded(log_level_t level)
Get padded level string for consistent alignment.
void log_console_impl(log_level_t level, const char *file, int line, const char *func, const char *message)
void ui_notice_announce(const char *file, int line, const char *func, const char *title, const char *format,...)
void ui_notice_log(ui_notice_severity_t severity, const char *file, int line, const char *func, const char *title, const char *format,...)
#define LOG_FUNC_NAME_BUFFER_SIZE
Definition lib/log/log.c:8
action_args_t args
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:104
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:272
📝 Logging API with multiple log levels and terminal output control
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
void log_mmap_rotate(void)
Rotate the mmap log (tail-keeping rotation).
Definition mmap.c:422
bool log_mmap_is_active(void)
Check if mmap logging is active.
Definition mmap.c:389
void log_mmap_write(int level, const char *file, int line, const char *func, const char *fmt,...)
Write a log entry directly to the mmap'd file (lock-free).
Definition mmap.c:312
bool log_mmap_get_usage(size_t *used, size_t *capacity)
Get current mmap log usage.
Definition mmap.c:408
void log_mmap_destroy(void)
Shutdown mmap logging.
Definition mmap.c:263
asciichat_error_t log_mmap_init_simple(const char *log_path, size_t max_size)
Initialize mmap logging with simple parameters.
Definition mmap.c:255
Lock-free memory-mapped text logging with crash safety.
asciichat_error_t ui_notice_present(ui_notice_severity_t severity, const char *text)
Definition notice.c:359
ui_notice_severity_t
Definition notice.h:13
@ UI_NOTICE_WARNING
Definition notice.h:13
@ UI_NOTICE_INFO
Definition notice.h:13
@ UI_NOTICE_DANGER
Definition notice.h:13
@ UI_NOTICE_FATAL
Definition notice.h:13
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_log(int level, const char *file, int line, const char *function, const char *format, va_list args)
Definition otel.c:679
📂 Path Manipulation Utilities
void log_search_destroy(void)
Clean up interactive grep subsystem.
Definition search.c:203
Interactive search filtering for terminal screens.
asciichat_error_t acip_send_remote_log(acip_transport_t *transport, uint8_t log_level, uint8_t direction, const char *message)
Send remote log packet.
Definition send.c:446
ACIP shared/bidirectional packet sending functions.
session_log_buffer_t * session_log_buffer_create(void)
Create a new session log buffer instance.
void session_log_buffer_append(session_log_buffer_t *buf, const char *message)
Append a log message to the buffer.
void session_log_buffer_destroy(session_log_buffer_t *buf)
Cleanup session log buffer instance.
Thread-safe circular log buffer for session screens (status, splash).
int platform_strcasecmp(const char *s1, const char *s2)
bool terminal_should_color_output(int fd, const terminal_options_t *options)
void detect_terminal_capabilities_into(const terminal_options_t *options, terminal_capabilities_t *out)
bool terminal_is_piped_output(void)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
Color scheme definition.
Definition colorscheme.h:76
Compiled log format ready for use in log_template_apply().
Definition log/format.h:72
bool quiet
Quiet mode (suppress logs).
Definition options.h:1140
ssize_t platform_write(int fd, const void *buf, size_t count)
Definition system.c:78
⏱️ High-precision timing utilities using sokol_time.h and uthash
bool ui_controller_is_presenting(void)
bool ui_controller_is_owner(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
#define LOG_DEV
Definition types.h:42
#define LOG_DEBUG
Definition types.h:43
#define LOG_FATAL
Definition types.h:47
#define LOG_ERROR
Definition types.h:46
#define LOG_WARN
Definition types.h:45
#define LOG_INFO
Definition types.h:44
🔤 UTF-8 Encoding and Decoding Utilities
int platform_isatty(int fd)
Definition util.c:70
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57