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