ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
Logging System

📝 Logging API with multiple log levels and terminal output control More...

Files

file  apple.c
 Apple unified logging (os_log) integration.
file  colorize.c
 Log message colorization for terminal output.
file  format.c
 Log format parser implementation.
file  json.c
 📝 JSON structured logging output using yyjson
file  log.c
 📝 Multi-level logging with terminal color support, file rotation, and async output
file  mmap.c
 Lock-free memory-mapped text logging implementation.
file  named.c
 Format named objects in log messages (replaces hex addresses with type/name descriptions).
file  wasm.c
 WASM logging support for routing to browser console.
file  colorize.h
 Log message colorization for terminal output.
file  json.h
 📝 JSON structured logging output
file  log.h
 📝 Logging API with multiple log levels and terminal output control
file  mmap.h
 Lock-free memory-mapped text logging with crash safety.
file  named.h
 Format named objects in log messages (replaces hex addresses with type/name descriptions).
file  types.h
 Log level types and constants.

Data Structures

struct  log_buffer_entry_t
 Heap-backed message waiting for the logging output thread. More...

Macros

#define ASCII_CHAT_LOG_LOG_H
#define LOG_ATOMIC_UINT64   atomic_t
#define LOG_ATOMIC_UINT64_INIT(val)
#define DEFAULT_LOG_LEVEL   LOG_DEBUG
 Default log level for debug builds (DEBUG and above).
#define MAX_LOG_SIZE   (3 * 1024 * 1024)
 Maximum log file size in bytes (3MB) before rotation.
#define MAX_TERMINAL_BUFFER_SIZE   (64 * 1024)
 Maximum size of terminal output buffer (64KB).
#define MAX_TERMINAL_BUFFER_ENTRIES   256
 Maximum number of buffered log entries.
#define LOG_MSG_BUFFER_SIZE   4096
 Maximum size of a single log message (including formatting).
#define LOG_MMAP_MSG_BUFFER_SIZE   1024
 Maximum size of a log message in mmap mode.
#define LOG_HEADER_BUFFER_SIZE   512
 Maximum size of a log header (timestamp, level, file:line:func).
#define LOG_TIMESTAMP_BUFFER_SIZE   32
 Maximum size of a timestamp string.
#define LOG_TERMINAL_BUFFER_SIZE   16384
#define LOG_TERMINAL_ENTRY_BUFFER_SIZE   (LOG_HEADER_BUFFER_SIZE + LOG_TERMINAL_BUFFER_SIZE)
#define log_colored_msg(level, colored_message, plain_message)
#define log_terminal_colored_msg(level, colored_message, plain_message)
#define log_plain(...)
 Plain logging - writes to both log file and stderr without timestamps or log levels.
#define log_plain_stderr(...)
 Plain logging to stderr with newline.
#define log_plain_stdout(...)
 Plain logging to stdout with newline.
#define log_plain_stderr_nonewline(...)
 Plain logging to stderr without newline - for interactive prompts.
#define log_file(...)
 File-only logging - writes to log file only, no stderr output.
#define log_every(log_level, interval_us, fmt, ...)
 Rate-limited logging macro (thread-safe).
#define log_nth(log_level, n, fmt, ...)
 Log every nth call to this code location (thread-safe).
#define log_once(log_level, fmt, ...)
 Log exactly once per call site (thread-safe).
#define LOG_BIT(n)
 Logging bit conversion.
#define LOG_CLIENT_IMPL(client, level, fmt, ...)
#define log_debug_client(client, fmt, ...)
 Server sends DEBUG log message to client.
#define log_info_client(client, fmt, ...)
 Server sends INFO log message to client.
#define log_warn_client(client, fmt, ...)
 Server sends WARN log message to client.
#define log_error_client(client, fmt, ...)
 Server sends ERROR log message to client.
#define log_fatal_client(client, fmt, ...)
 Server sends FATAL log message to client.
#define LOG_SERVER_IMPL(transport, level, fmt, ...)
#define log_debug_server(transport, fmt, ...)
 Client sends DEBUG log message to server.
#define log_info_server(transport, fmt, ...)
 Client sends INFO log message to server.
#define log_warn_server(transport, fmt, ...)
 Client sends WARN log message to server.
#define log_error_server(transport, fmt, ...)
 Client sends ERROR log message to server.
#define log_fatal_server(transport, fmt, ...)
 Client sends FATAL log message to server.

Typedefs

typedef struct color_scheme_t color_scheme_t
typedef struct session_log_buffer session_log_buffer_t
 Thread-safe fixed-size history ring for session-screen log lines.
typedef enum remote_log_direction remote_log_direction_t
 Remote log packet direction enumeration.

Enumerations

enum  log_level_t {
  ASCIICHAT_LOG_DEV = 0 , ASCIICHAT_LOG_DEBUG , ASCIICHAT_LOG_INFO , ASCIICHAT_LOG_WARN ,
  ASCIICHAT_LOG_ERROR , ASCIICHAT_LOG_FATAL
}
 Logging levels enumeration. More...
enum  remote_log_direction { REMOTE_LOG_DIRECTION_UNKNOWN = 0 , REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT = 1 , REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER = 2 }
 Remote log packet direction enumeration. More...

Functions

log_template_t * log_template_parse (const char *format_str, bool console_only)
 Parse a format string into compiled format structure.
void log_template_free (log_template_t *format)
 Free compiled format structure.
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.
void log_init (const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
 Initialize the logging system.
void log_destroy (void)
 Destroy the logging system and close log file.
void log_system_init (void)
 Initialize the logging system internal state (system-level init).
void log_system_destroy (void)
 Shutdown the logging system internal state (system-level cleanup).
void log_set_level (log_level_t level)
 Set the minimum log level.
log_level_t log_get_level (void)
 Get the current minimum log level.
asciichat_error_t log_set_format (const char *format_str, bool console_only)
 Set a custom log format string.
void log_set_terminal_output (bool enabled)
 Control stderr output to terminal.
bool log_get_terminal_output (void)
 Get current terminal output setting.
void log_set_force_stderr (bool enabled)
 Force all terminal log output to stderr.
bool log_get_force_stderr (void)
 Get current force_stderr setting.
void log_disable_file_output (void)
 Disable file output and use stderr instead.
void log_truncate_if_large (void)
 Manually truncate large log files.
void log_msg (log_level_t level, const char *file, int line, const char *func, const char *fmt,...)
 Log a message at a specific level.
void log_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).
void log_colored_msg_impl (log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message)
 Write semantically colored terminal text and an ANSI-free log equivalent.
void log_terminal_colored_msg_impl (log_level_t level, const char *file, int line, const char *func, const char *colored_message, const char *plain_message)
 Write semantically colored terminal text without persistent logging.
void log_plain_msg (const char *fmt,...)
 Plain logging without timestamps or levels.
void log_plain_stderr_msg (const char *fmt,...)
 Plain logging to stderr with newline.
void log_plain_stdout_msg (const char *fmt,...)
 Plain logging to stdout with newline.
void log_plain_stderr_nonewline_msg (const char *fmt,...)
 Plain logging to stderr without trailing newline.
void log_file_msg (const char *fmt,...)
 Log to file only, no stderr output.
void log_labeled (const char *label, log_color_t color, const char *message,...)
 Print a labeled message with color.
const char * log_level_color (log_color_t color)
 Get color string for a given color enum.
const char * log_level_color_for_output (log_color_t color, bool enabled)
const char ** log_get_color_array (void)
 Get the appropriate color array based on terminal capabilities.
const char * log_get_foreground_color (void)
int log_get_color_mode (void)
void log_redetect_terminal_capabilities (void)
 Re-detect terminal capabilities after logging is initialized.
void log_init_colors (void)
 Initialize logging color system with current terminal capabilities.
void log_set_color_scheme (const color_scheme_t *scheme)
 Set the color scheme for logging output.
bool log_lock_terminal (void)
 Lock terminal output for exclusive access by the calling thread.
void log_unlock_terminal (bool previous_state)
 Release terminal lock and flush buffered messages.
void log_set_flush_delay (unsigned int delay_ms)
 Set the delay between flushing buffered log entries.
char * format_message (const char *format, va_list args)
 Format a message using va_list.
size_t get_current_time_formatted (char *time_buf)
 Get current time as formatted string.
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).
asciichat_error_t log_enable_mmap (const char *log_path)
 Enable lock-free mmap-based logging.
asciichat_error_t log_enable_mmap_sized (const char *log_path, size_t max_size)
 Enable lock-free mmap logging with custom file size.
void log_disable_mmap (void)
 Disable mmap logging and return to mutex-based logging.
void log_shutdown_begin (void)
 Begin shutdown phase - disable console logging but keep file logging.
void log_shutdown_end (void)
 End shutdown phase - restore previous logging settings.
void log_cleanup_colors (void)
 Clean up compiled color scheme.
void log_set_session_log_buffer (session_log_buffer_t *buf)
 Register a session log buffer with the logger.
void log_clear_session_log_buffer (void)
 Unregister the session log buffer.
session_log_buffer_t * log_get_session_log_buffer (void)
 Get the currently registered session log buffer.
size_t log_recolor_plain_entry (const char *plain_line, char *colored_buf, size_t buf_size)
 Recolor a plain (non-colored) log line with proper ANSI codes.
void * log_get_template (void)
 Get the current log format template (opaque pointer).
int log_named_format_message (const char *message, char *output, size_t output_size)
 Format hex addresses in a message as named object descriptions.
const char * log_named_format_or_original (const char *message)
 Format named objects in a message (thread-local buffer).
const char * colorize_named_string (const char *name_str)
 Colorize a "type/name" string for display.

Logging Macros

Note
Compile-time log level stripping: In release builds, log_dev() and log_debug() are compiled out completely (no runtime overhead). Override with LOG_COMPILE_LEVEL.
#define log_as(level, ...)
 Log a message given the associated level.
#define log_only(bitmask, level, ...)
 Log a message given its level and if the bitmask allows so.
#define log_dev(...)
 Log a DEV message (most verbose, development only).
#define log_debug(...)
 Log a DEBUG message.
#define log_info(...)
 Log an INFO message.
#define log_warn(...)
 Log a WARN message.
#define log_error(...)
 Log an ERROR message.
#define log_fatal(...)
 Log a FATAL message.

Detailed Description

📝 Logging API with multiple log levels and terminal output control

This header provides a comprehensive logging system with:

  • Multiple log levels (DEV, DEBUG, INFO, WARN, ERROR, FATAL)
  • File and terminal output with automatic color coding
  • Terminal capability detection (16-color, 256-color, truecolor)
  • Rate-limited logging macros for high-frequency logging
  • Thread-safe logging operations
  • Automatic log file rotation when size limit is reached
Note
In debug builds, log macros include file/line/function information. In release builds, this information is omitted.

This module formats named objects in log messages by scanning for hex addresses and replacing them with friendly descriptions from the named object registry when available.

For example:

  • Input: "Locked 0x7f1234567890 successfully"
  • Output: "Locked mutex: recv_mutex.2 (0x7f1234567890) successfully"

When an address is not registered, it's left unchanged.

Logging Subsystem Architecture

Overview

The ascii-chat logging subsystem provides a comprehensive, high-performance logging system designed for terminal-based applications with multiple concurrent threads and real-time constraints.

Key features:

  • Six severity levels (DEV, DEBUG, INFO, WARN, ERROR, FATAL)
  • Simultaneous file and terminal output with automatic color coding
  • Lock-free memory-mapped logging for high-performance scenarios
  • PCRE2-based regex filtering with context display
  • Flexible format customization for both console and file output
  • Rate-limited and call-count-based logging macros
  • Thread-safe logging with optional terminal locking for interactive prompts

System Architecture

The logging system is organized into modular layers:

┌──────────────────────────────────────────────────────────┐
│ Application Code (log_info, log_warn, etc.) │
└────────────────────┬─────────────────────────────────────┘
│
┌────────────────────▼─────────────────────────────────────┐
│ lib/log/logging.c - Core logging system │
│ - Terminal locking for interactive prompts │
└──┬──────────────────┬───────────────────┬────────────────┘
│ │ │
┌──▼──────────┐ ┌───▼──────────┐ ┌────▼─────────────────┐
│ Output │ │ Formatting │ │ Filtering & Colors │
│ │ │ │ │ │
│ - File I/O │ │- format.c │ │ - grep.c (PCRE2) │
│ - mmap.c │ │- Custom │ │ - colorize.c │
│ - Buffering │ │ templates │ │ - Terminal detection │
└─────────────┘ └──────────────┘ └─────────────────────┘
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
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_destroy(void)
Destroy the logging system and close log file.
Definition log/log.c:737
void log_set_level(log_level_t level)
Set the minimum log level.
Definition log/log.c:809
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_info(...)
Log an INFO message.
Definition log/log.h:578
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
platform_mmap_t mmap
Definition mmap.c:38

Log Levels

The logging system defines six severity levels, from most to least verbose:

Level Value Purpose Compile-Time Stripping Example
DEV 0 Development/trace logs Strippable in release Frame timing, buffer state, handshake details
DEBUG 1 Debug diagnostic messages Strippable in release Algorithm decisions, state transitions
INFO 2 Informational messages Strippable via LOG_COMPILE_LEVEL=LOG_WARN Initialization, connection events
WARN 3 Warning conditions Strippable via LOG_COMPILE_LEVEL=LOG_ERROR Recoverable errors, performance concerns
ERROR 4 Error conditions Strippable via LOG_COMPILE_LEVEL=LOG_FATAL Failed operations, broken connections
FATAL 5 Fatal errors (program exit) Never stripped Out of memory, crypto failure

Key characteristics:

  • DEV/DEBUG are compile-time strippable, allowing verbose debug builds while keeping release builds small. Override with LOG_COMPILE_LEVEL=LOG_DEV to keep them.
  • INFO/WARN use log_info_every() and log_warn_every() for high-frequency paths (video/audio loops) to avoid log spam while maintaining visibility.
  • ERROR/FATAL go to stderr; others go to stdout (unless force_stderr is enabled). This keeps stdout clean for client mode where ASCII art is rendered.

Macro API:

log_dev("Development message"); // Compile-time strippable
log_debug("Debug message"); // Compile-time strippable
log_info("Info message"); // Production-safe
log_warn("Warning: %d", value); // Warning condition
log_error("Error: %s", error_msg); // Error condition
log_fatal("Fatal: exiting"); // Program termination
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_fatal(...)
Log a FATAL message.
Definition log/log.h:616
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565

Message Formatting

The logging system uses a templated formatting system that allows customization of message output while maintaining performance.

Default format (debug mode):

[14:30:45] [DEBUG] [tid:1234] src/client.c:42 in client_init(): Starting client
int client_init(void)

Default format (release mode):

[14:30:45] [DEBUG] Starting client

Custom format support via log_set_format():

// Compact format
log_set_format("[%time(%H:%M:%S)] [%level_aligned] %message", false);
// Detailed format with colors
log_set_format("%color(LOG_DEBUG, [%level_aligned]) %message", false);
// Relative file paths
log_set_format("[%time(%H:%M:%S.%microseconds)] %file_relative:%line %message", false);
asciichat_error_t log_set_format(const char *format_str, bool console_only)
Set a custom log format string.
Definition log/log.c:859

Format specifiers:

  • time(fmt) - Time in strftime format (e.g., H:M:S, Y-m-d)
  • level - Log level name (DEBUG, INFO, WARN, ERROR)
  • level_aligned - Log level padded to 5 chars (for alignment)
  • file - Full file path (debug mode only)
  • file_relative - Relative file path (debug mode only)
  • line - Line number (debug mode only)
  • func - Function name (debug mode only)
  • tid - Thread ID (debug mode only)
  • message - Log message body
  • microseconds - Microsecond component of timestamp
  • nanoseconds - Nanosecond component of timestamp

Console-only formatting: By passing console_only=true to log_set_format(), the custom format applies only to terminal output. File logging uses the default format, which is useful for preserving readable logs while having fancy terminal colors.

Log Filtering with Grep

The filtering system uses PCRE2 regex to dynamically filter log output, with support for highlighting matched text.

CLI usage:

# Plain regex - matches "error" or "warning" case-insensitive
./ascii-chat server --grep "/error|warning/i"
# With context - show 2 lines before and after match
./ascii-chat client --grep "/handshake/C2"
# Fixed string search (no regex)
./ascii-chat server --grep "/DEBUG/F"
# Multiple patterns - OR logic
./ascii-chat client --grep "/error/i" --grep "/connection/i"
# Invert match - show everything EXCEPT matches
./ascii-chat server --grep "/debug|trace/iI"

Supported flags:

  • i - Case-insensitive matching
  • m - Multiline mode (^ and $ match line boundaries)
  • s - Dotall mode (. matches newlines)
  • x - Extended regex (ignore whitespace in pattern)
  • F - Fixed string literal (no regex, exact match)
  • g - Global highlighting (highlight all matches in line)
  • I - Invert match (show lines that DON'T match)
  • B<n> - Show n lines before match (context)
  • A<n> - Show n lines after match (context)
  • C<n> - Show n lines before and after (context)

Filter performance:

  • Each pattern is compiled once at startup (not on every log)
  • Matching uses thread-local storage (no allocations per match)
  • Matched text is highlighted with yellow background
  • Filtering is applied after formatting, so matches include colored output

Output Routing

The logging system routes messages to different outputs based on level and configuration.

Default routing:

  • DEV, DEBUG, INFO → stdout (unless force_stderr enabled)
  • WARN, ERROR, FATAL → stderr
  • All levels → log file (if configured)

Client mode special handling: Client mode keeps stdout clean for ASCII art rendering by enabling force_stderr:

log_init("client.log", LOG_DEBUG, true, false); // force_stderr=true
#define LOG_DEBUG
Definition log/types.h:43

This routes all log messages (including INFO) to stderr, keeping stdout available.

Output control functions:

log_set_terminal_output(false); // Disable all terminal output
log_set_force_stderr(true); // Force all logs to stderr
log_disable_file_output(); // Disable file output, use stderr fallback
void log_set_force_stderr(bool enabled)
Force all terminal log output to stderr.
Definition log/log.c:840
void log_disable_file_output(void)
Disable file output and use stderr instead.
Definition log/log.c:848
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log/log.c:818

Buffering for interactive prompts: When prompting for user input (passwords, yes/no questions), use terminal locking to ensure clean output:

bool prev = log_lock_terminal(); // Lock out other threads
fputs("Enter password: ", stdout);
// user types input
log_unlock_terminal(prev); // Unlock and flush buffered logs
bool log_lock_terminal(void)
Lock terminal output for exclusive access by the calling thread.
Definition log/log.c:905
void log_unlock_terminal(bool previous_state)
Release terminal lock and flush buffered messages.
Definition log/log.c:914

Performance Characteristics

The logging system is designed for low-latency, high-throughput scenarios common in real-time multimedia applications.

Lock-free mmap mode (recommended for production):

  • File output: Lock-free atomic operations on mmap'd memory
  • Terminal output: Atomic fprintf/fwrite (no mutex held)
  • No contention: Multiple threads can log simultaneously without blocking
  • Crash-safe: Text written directly to file, readable after crash
  • Performance: ~5-10 microseconds per log message (x86-64)

Mutex-based mode (fallback):

  • Single mutex protects both file and terminal output
  • Suitable for applications with low logging volume
  • Fallback when mmap initialization fails

Optimizations for high-frequency logging:

// Log at most once per second (1,000,000 microseconds)
log_info_every(1000000, "Frame buffer utilization: %d%%", percent);
// Log every 60th call (for 60 FPS, logs ~1x per second)
log_debug_nth(60, "Processing frame %zu", frame_count);
// Log exactly once per session
log_info_once("Client connected from %s", client_address);
#define log_info_every(interval_us, fmt,...)
Rate-limited INFO logging.
Definition log/log.h:722
#define log_debug_nth(n, fmt,...)
Log DEBUG message every nth call.
Definition log/log.h:825
#define log_info_once(fmt,...)
Log INFO message exactly once.
Definition log/log.h:853

Memory usage:

  • Terminal buffer: 64 KB maximum (256 buffered entries)
  • Single message: 4 KB maximum (truncated if exceeded)
  • File buffer: Variable (mmap mode) or unbuffered
  • Per-format specifier: ~100 bytes compiled size

CPU characteristics:

  • Message formatting: ~2-5% of CPU in typical scenarios
  • PCRE2 filtering: <1% overhead for simple patterns
  • Terminal color detection: One-time cost at startup
  • Rate-limited macros: Atomic operations only (no syscalls)

Appropriate Use Cases

Good use cases for logging:

  • Connection lifecycle events (connected, disconnected, handshake)
  • Configuration changes or mode transitions
  • Recoverable errors and retry attempts
  • Performance metrics and statistics (with rate limiting)
  • Authentication and security events
  • Frame drops or quality degradation
  • Shader compilation or resource loading

Poor use cases (leads to spam):

  • Every video frame processed (use log_nth or log_every)
  • Every byte received (use log_every instead)
  • Every mutex acquisition/release (use log_once or don't log)
  • Every packet in a high-frequency network loop (use sampling)

Performance-sensitive code patterns:

// ❌ BAD: 60 logs per second (60 FPS scenario)
void process_frame(void) {
log_debug("Processing frame %zu", frame_count);
}
// ✅ GOOD: 1 log per second using rate limiting
void process_frame(void) {
log_debug_every(1000000, "Processed %zu frames", frame_count);
}
// ✅ GOOD: 1 log per 60 frames using call counting
void process_frame(void) {
log_debug_nth(60, "Processing frames (batch complete)");
}
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719

Error Handling in Logs

The logging system integrates with the application's error tracking system. For critical failures, use SET_ERRNO() to capture error context:

// Set errno with context message
if (crypto_failed) {
log_error("Crypto handshake failed: %s", reason);
return SET_ERRNO(ERROR_CRYPTO_FAILED, "Key exchange timeout");
}
// Check and log errors from other functions
asciichat_error_t result = process_network_packet();
if (result != ASCIICHAT_OK) {
log_error("Network error: %d", result);
return result;
}
#define SET_ERRNO(code,...)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50

Initialization and Shutdown

Standard initialization (debug mode):

log_init("output.log", // Log file path
LOG_DEBUG, // Minimum log level
false, // force_stderr: no (INFO to stdout)
false); // use_mmap: no (use mutex-based)

Production initialization (server mode with mmap):

log_init("/var/log/asciichat.log",
LOG_INFO, // Only INFO and above
false, // Normal routing
true); // use_mmap: yes (lock-free)
// Optionally upgrade to lock-free mode
log_enable_mmap("/var/log/asciichat.log");
asciichat_error_t log_enable_mmap(const char *log_path)
Enable lock-free mmap-based logging.
Definition log/log.c:2188
#define LOG_INFO
Definition log/types.h:44

Client mode (keep stdout clean):

log_init("client.log",
true, // force_stderr: yes
false);

Graceful shutdown:

// Disable console output, keep file logging for shutdown messages
log_info("Shutting down server");
log_info("All clients disconnected");
// Destroy logging system
void log_shutdown_end(void)
End shutdown phase - restore previous logging settings.
Definition log/log.c:2231
void log_shutdown_begin(void)
Begin shutdown phase - disable console logging but keep file logging.
Definition log/log.c:2219

Thread Safety

All logging functions are thread-safe:

Interactive prompt pattern:

// Thread 1 (main thread) - handle user input
bool prev = log_lock_terminal();
char *password = getpass("Password: ");
// Now buffered logs from other threads are flushed
// Thread 2 (network thread) - can log normally
log_info("Received %d bytes", packet_size); // Buffered during lock

Debugging with Logs

Enable verbose logging:

# -V increases verbosity (can be stacked)
./ascii-chat --log-level debug -V server
./ascii-chat -VVV client # Maximum verbosity with DEV level

Log to file for analysis:

./ascii-chat --log-file debug.log server
# Or using CLI options
./ascii-chat --log-level dev --log-file debug.log server

Filter logs during execution:

# Watch crypto handshake
./ascii-chat --log-level debug server --grep "/handshake|crypto/ig"
# See only errors and warnings with context
./ascii-chat client --grep "/error|warn/iC3"
# Monitor specific component
./ascii-chat server --grep "/\\‍[AUDIO\\‍]/i"

Post-mortem analysis (from log file):

# Check for errors
grep -i error debug.log
# Find performance issues
grep "timeout\|delay\|slow" debug.log
# Track connection lifecycle
grep "connected\|disconnected\|handshake" debug.log

Code Examples

Basic logging:

log_info("Server started on port %d", 27224);
log_warn("Connection timeout after %d seconds", timeout);
log_error("Failed to bind socket: %s", strerror(errno));

Conditional logging:

if (verbose_mode) {
log_debug("Processing frame %zu in %llu µs", frame_num, elapsed_us);
}
// Or use compile-time stripping for release builds
log_dev("Frame pipeline state: input=%d, processing=%d, output=%d",
input_queue, process_queue, output_queue);

Labeled output:

log_labeled("[INIT]", LOG_COLOR_DEBUG, "Initializing subsystem");
log_labeled("[ERROR]", LOG_COLOR_ERROR, "Failed to create thread");
@ LOG_COLOR_ERROR
Definition color.h:11
@ LOG_COLOR_DEBUG
Definition color.h:8
void log_labeled(const char *label, log_color_t color, const char *message,...)
Print a labeled message with color.

Raw output (no formatting):

// Write to file only (no terminal)
log_file("Raw packet dump follows:");
log_file(" 00 01 02 03 04 05 06 07");
// Plain message to stderr
log_plain_stderr("Critical condition detected");
#define log_plain_stderr(...)
Plain logging to stderr with newline.
Definition log/log.h:642
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:663

Network logging:

// Log to remote server, file, and terminal simultaneously
log_net_message(server_socket, crypto_ctx, LOG_INFO, REMOTE_LOG_OUTBOUND,
NULL, 0, NULL, "Video quality: %d%% (%d kbps)", quality, bitrate);
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

Macro Definition Documentation

◆ ASCII_CHAT_LOG_LOG_H

#define ASCII_CHAT_LOG_LOG_H

#include <include/ascii-chat/log/log.h>

Definition at line 26 of file log/log.h.

◆ DEFAULT_LOG_LEVEL

#define DEFAULT_LOG_LEVEL   LOG_DEBUG

#include <include/ascii-chat/log/log.h>

Default log level for debug builds (DEBUG and above).

Definition at line 63 of file log/log.h.

Referenced by parse_log_level().

◆ log_as

#define log_as ( level,
... )

#include <include/ascii-chat/log/log.h>

Value:
log_msg(level, __FILE__, __LINE__, __func__, __VA_ARGS__)

Log a message given the associated level.

Parameters
levelThe log level to use
...Format string and arguments (printf-style)

Definition at line 525 of file log/log.h.

◆ LOG_ATOMIC_UINT64

#define LOG_ATOMIC_UINT64   atomic_t

#include <include/ascii-chat/log/log.h>

Definition at line 35 of file log/log.h.

◆ LOG_ATOMIC_UINT64_INIT

#define LOG_ATOMIC_UINT64_INIT ( val)

#include <include/ascii-chat/log/log.h>

Value:
{}

Definition at line 38 of file log/log.h.

◆ LOG_BIT

#define LOG_BIT ( n)

#include <include/ascii-chat/log/types.h>

Value:
(1ULL << (n))

Logging bit conversion.

Converts a log level to a bit flag. Used to pack multiple log levels in the same number (array of flags).

Definition at line 23 of file log/types.h.

◆ LOG_CLIENT_IMPL

#define LOG_CLIENT_IMPL ( client,
level,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
do { \
if ((client)->security_ready && (client)->transport) { \
log_net_message((client)->transport, level, \
__LINE__, __func__, fmt, ##__VA_ARGS__); \
} \
} while (asciichat_macro_block_continue())
@ REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT
Definition network/log.h:22

Definition at line 59 of file network/log.h.

59#define LOG_CLIENT_IMPL(client, level, fmt, ...) \
60 do { \
61 if ((client)->security_ready && (client)->transport) { \
62 log_net_message((client)->transport, level, \
63 REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT, __FILE__, \
64 __LINE__, __func__, fmt, ##__VA_ARGS__); \
65 } \
66 } while (asciichat_macro_block_continue())

◆ log_colored_msg

#define log_colored_msg ( level,
colored_message,
plain_message )

#include <include/ascii-chat/log/log.h>

Value:
log_colored_msg_impl((level), __FILE__, __LINE__, __func__, (colored_message), (plain_message))
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

Definition at line 294 of file log/log.h.

◆ log_debug

#define log_debug ( ...)

#include <include/ascii-chat/log/log.h>

Value:
#define log_only(bitmask, level,...)
Log a message given its level and if the bitmask allows so.
Definition log/log.h:536
#define LOG_BIT(n)
Logging bit conversion.
Definition log/types.h:23

Log a DEBUG message.

Parameters
...Format string and arguments (printf-style)
Note
DEBUG messages are stripped at compile-time in release builds.
In debug builds, includes file/line/function.

Definition at line 565 of file log/log.h.

Referenced by acds_client_disconnect(), acds_identity_generate(), acds_server_shutdown(), acds_sign_session_create(), acds_sign_session_join(), acds_validate_timestamp(), acds_verify_session_create(), acds_verify_session_join(), acip_send_ascii_frame_contract(), acip_send_image_frame_h265(), acip_tcp_transport_create(), acip_transport_destroy(), acip_websocket_client_transport_create(), acip_websocket_server_transport_create(), add_known_host(), add_transport_client(), apply_palette_config(), ascii_otel_shutdown(), ascii_write_destroy(), asciichat_mdns_advertise(), asciichat_mdns_destroy(), asciichat_mdns_query(), asciichat_mdns_update(), audio_cleanup(), audio_client_init(), audio_connection_init(), audio_destroy(), audio_init(), audio_process_received_samples(), audio_ring_buffer_read(), audio_sender_cleanup(), audio_set_realtime_priority(), audio_start_duplex(), audio_start_thread(), audio_stop_duplex(), audio_stop_thread(), audio_terminate_portaudio_final(), buffer_domain_log_stats(), capture_init(), capture_start_thread(), check_gpg_key_expiry(), check_known_host_with_key(), client_audio_pipeline_create(), client_audio_pipeline_process_duplex(), client_audio_render_thread(), client_connection_checkpoint(), client_crypto_init(), client_main(), client_protocol_start(), client_video_render_thread(), config_schema_build_from_configs(), consensus_coordinator_create(), consensus_coordinator_on_stats_update(), create_client_render_threads(), crypto_destroy(), crypto_generate_keypair(), crypto_handshake_client_auth_response(), crypto_handshake_client_key_exchange(), crypto_handshake_server_auth_challenge(), crypto_handshake_server_complete(), crypto_handshake_server_send_parameters(), crypto_handshake_server_start(), crypto_handshake_set_parameters(), crypto_process_auth_challenge(), crypto_process_auth_response(), crypto_rekey_commit(), crypto_rekey_init(), crypto_rekey_process_request(), crypto_rekey_process_response(), crypto_set_peer_public_key(), crypto_should_rekey(), crypto_verify_auth_response(), database_close(), database_session_add_key(), database_session_get_keys(), database_session_is_migration_ready(), database_session_lookup(), database_session_revoke_key(), database_stats_session_count(), database_stats_unique_clients(), detect_client_utf8_support(), detect_default_ssh_key(), disconnect_client_for_bad_data(), discover_session_parallel(), discovery_keys_clear_cache(), discovery_keys_download_https(), discovery_keys_load_file(), discovery_keys_save_cached(), discovery_keys_verify(), discovery_main(), discovery_session_check_host_alive(), discovery_session_create(), discovery_session_process(), dns_test_connectivity(), ed25519_sign_message(), ed25519_verify_signature(), env_pop_prompt_response(), ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), ffmpeg_encoder_create_scaled(), ffmpeg_encoder_set_snapshot_actual_duration(), ffmpeg_encoder_write_frame(), fps_counter_format(), frame_validate_integrity(), framebuffer_write_multi_frame(), get_known_hosts_path(), get_manpage_content(), get_manpage_template(), gpg_agent_connect(), gpg_agent_sign(), gpg_get_public_key(), gpg_homedir_create(), gpg_homedir_destroy(), gpg_sign_detached_ed25519(), gpg_sign_with_key(), gpg_verify_detached_ed25519(), gpg_verify_signature(), gpg_verify_signature_with_binary(), h265_encoder_flush(), h265_server_get_client_decoder(), h265_server_remove_client(), handle_client_leave_packet(), handle_image_frame_packet(), handle_protocol_version_packet(), handle_stream_start_packet(), ice_add_remote_candidate(), ice_gather_candidates(), keepalive_stop_thread(), log_io_stop(), log_mmap_destroy(), log_recolor_plain_entry(), log_redetect_terminal_capabilities(), log_template_apply(), manpage_content_generate_environment(), manpage_content_generate_environment_with_manual(), manpage_content_generate_examples(), manpage_content_generate_options(), manpage_content_generate_positional(), manpage_content_generate_usage(), manpage_merger_generate_synopsis(), manpage_merger_generate_usage(), manpage_merger_merge_environment(), manpage_merger_merge_options(), manpage_merger_merge_positional(), manpage_resources_load(), media_source_create_interruptible(), media_source_read_audio(), media_source_read_video(), media_source_seek(), memory_backend_create(), mirror_convert_frame(), mirror_main(), mixer_create_channels(), mixer_destroy(), mixer_set_source_active(), nat_compare_quality(), nat_detect_quality(), nat_upnp_close(), nat_upnp_open_protocol(), negotiate_init(), openpgp_extract_ed25519_from_mpi(), openpgp_parse_armored_pubkey(), openpgp_parse_armored_seckey(), openpgp_parse_packet_header(), openpgp_parse_public_key_packet(), openpgp_parse_secret_key_packet(), options_collect_identity_keys(), options_config_generate_manpage_merged(), options_config_generate_manpage_template(), options_state_destroy(), options_state_init(), opus_codec_create_decoder_channels(), opus_codec_create_encoder_channels(), opus_codec_set_bitrate(), opus_codec_set_dtx(), parallel_connect(), parse_client_address(), parse_gpg_keys_from_response(), parse_mirror_media(), parse_private_key(), parse_public_keys(), process_decrypted_packet(), prompt_unknown_host_no_identity(), recv_with_timeout(), remove_known_host(), render_file_create(), sdp_detect_terminal_capabilities(), sdp_generate_answer(), sdp_generate_offer(), sdp_get_selected_video_codec(), sdp_parse(), send_crypto_parameters_packet(), send_server_state_to_client(), server_connection_set_ip(), server_connection_set_port(), server_main(), session_capture_create(), session_client_like_run(), session_consensus_create(), session_display_create(), session_display_encode_frame(), session_display_set_render_fps(), session_display_set_snapshot_actual_duration(), session_display_set_stdin_reader(), session_display_write_ascii_frame(), session_network_capture_create(), session_participant_connect(), session_pipeline_create(), session_pipeline_destroy(), session_pipeline_run_main(), session_protocol_build_capabilities(), session_render_loop(), session_server_like_run(), signaling_broadcast(), signaling_relay_ice(), signaling_relay_sdp(), splash_set_update_notification(), sqlite_backend_create(), ssh_agent_add_key(), ssh_agent_has_key(), ssh_agent_sign(), start_transport_client_threads(), stats_runtime_toggle(), tcp_server_destroy(), term_renderer_create(), terminal_fd_reader_create(), terminal_fd_reader_next(), terminal_fd_writer_create(), thread_pool_create(), thread_pool_create_with_workers(), thread_pool_destroy(), thread_pool_interrupt_all(), thread_pool_spawn(), thread_pool_stop_all(), threaded_send_packet(), time_format_now(), timer_system_destroy(), turn_generate_credentials(), update_check_startup(), validate_palette_chars(), video_frame_buffer_create(), webrtc_add_remote_candidate(), webrtc_cleanup_transport(), webrtc_close_datachannel(), webrtc_close_peer_connection(), webrtc_create_datachannel(), webrtc_create_offer(), webrtc_create_peer_connection(), webrtc_datachannel_set_callbacks(), webrtc_peer_connection_close(), webrtc_peer_connection_destroy(), webrtc_peer_manager_connect(), webrtc_peer_manager_destroy(), webrtc_peer_manager_handle_ice(), webrtc_peer_manager_handle_sdp(), webrtc_set_acds_transport(), webrtc_set_remote_description(), webrtc_set_transport(), websocket_server_destroy(), websocket_server_init(), websocket_transport_send(), and yt_dlp_extract_with_options().

◆ log_debug_client

#define log_debug_client ( client,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_CLIENT_IMPL(client, LOG_DEBUG, fmt, ##__VA_ARGS__)
#define LOG_CLIENT_IMPL(client, level, fmt,...)
Definition network/log.h:59

Server sends DEBUG log message to client.

Definition at line 70 of file network/log.h.

70#define log_debug_client(client, fmt, ...) \
71 LOG_CLIENT_IMPL(client, LOG_DEBUG, fmt, ##__VA_ARGS__)

◆ log_debug_server

#define log_debug_server ( transport,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_SERVER_IMPL(transport, LOG_DEBUG, fmt, ##__VA_ARGS__)
#define LOG_SERVER_IMPL(transport, level, fmt,...)
Definition network/log.h:95

Client sends DEBUG log message to server.

Definition at line 101 of file network/log.h.

101#define log_debug_server(transport, fmt, ...) \
102 LOG_SERVER_IMPL(transport, LOG_DEBUG, fmt, ##__VA_ARGS__)

◆ log_dev

◆ log_error

#define log_error ( ...)

#include <include/ascii-chat/log/log.h>

Value:
#define LOG_ERROR
Definition log/types.h:46

Log an ERROR message.

Parameters
...Format string and arguments (printf-style)
Note
ERROR messages can be stripped via LOG_COMPILE_LEVEL=LOG_FATAL.

Definition at line 604 of file log/log.h.

Referenced by acds_identity_fingerprint(), acip_client_receive_packet(), acip_handle_server_packet(), acip_send_image_frame_h265(), acip_server_receive_and_dispatch(), acip_tcp_transport_create(), acip_websocket_client_transport_create(), action_completions(), action_create_config(), add_transport_client(), ascii_convert(), ascii_convert_with_buffers_stabilized(), ascii_write_init(), asciichat_fatal_with_context(), asciichat_pcre2_extract_group(), asciichat_pcre2_extract_named_group(), audio_client_init(), audio_start_thread(), check_gpg_key_expiry(), check_known_host_with_key(), client_audio_pipeline_create(), client_audio_pipeline_process_duplex(), client_audio_pipeline_reset(), client_audio_render_thread(), client_crypto_init(), client_protocol_start(), client_video_render_thread(), consensus_coordinator_process(), create_client_render_threads(), create_mixed_ascii_frame_for_client(), crypto_handshake_client_key_exchange(), crypto_handshake_server_start(), crypto_rekey_init(), database_init(), database_session_cleanup_expired(), database_session_find_by_id(), database_session_find_by_string(), database_session_is_migration_ready(), database_session_leave(), database_session_verify_key(), detect_default_ssh_key(), digital_rain_init(), digital_rain_render_at(), discovery_session_check_host_alive(), discovery_session_start(), get_known_hosts_path(), get_required_argument(), gpg_agent_connect(), gpg_agent_sign(), gpg_get_public_key(), gpg_homedir_create(), gpg_sign_detached_ed25519(), gpg_sign_with_key(), gpg_verify_detached_ed25519(), gpg_verify_signature(), gpg_verify_signature_with_binary(), grep_init(), h265_client_init_media_source(), h265_encode(), h265_encoder_flush(), handle_audio_batch_packet(), handle_audio_opus_batch_packet(), handle_audio_opus_packet(), handle_audio_packet(), handle_image_frame_h265_packet(), handle_image_frame_packet(), handle_stream_start_packet(), https_get(), is_session_string(), keepalive_start_thread(), log_named_format_or_original(), log_search_exit_mode(), log_set_format(), mcp_server_main(), media_source_create_interruptible(), memory_backend_create(), mirror_convert_frame(), mixer_add_source(), mutex_stack_detect_deadlocks(), options_collect_identity_keys(), packet_parse_opus_batch(), parse_color_mode_option(), parse_height_option(), parse_log_level_option(), parse_palette_chars_option(), parse_palette_option(), parse_render_mode_option(), parse_snapshot_delay_option(), parse_webcam_index_option(), parse_width_option(), precalc_rgb_palettes(), process_decrypted_packet(), rate_limiter_create_memory(), rate_limiter_create_sqlite(), render_file_create(), server_connection_init(), server_main(), session_audio_create(), session_capture_destroy(), session_display_create(), session_display_init_render_file(), session_display_write_ascii_frame(), session_host_start_render(), session_participant_create(), session_participant_start_audio(), session_participant_start_video(), session_participant_stop_audio(), session_participant_stop_video(), session_pipeline_run_main(), session_render_loop(), session_server_like_run(), sqlite_backend_create(), term_renderer_feed(), thread_pool_create_with_workers(), thread_pool_destroy(), thread_pool_stop_all(), time_format_is_valid_strftime(), time_format_now(), ui_mdns_prompt_selection(), ui_session_key(), update_check_load_cache(), update_check_perform(), video_frame_buffer_create(), webrtc_datachannel_send(), webrtc_peer_manager_check_gathering_timeouts(), webrtc_set_session_context(), websocket_server_init(), websocket_server_run(), websocket_transport_send(), windows_service_dispatch(), and yt_dlp_extract_with_options().

◆ log_error_client

#define log_error_client ( client,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_CLIENT_IMPL(client, LOG_ERROR, fmt, ##__VA_ARGS__)

Server sends ERROR log message to client.

Definition at line 82 of file network/log.h.

82#define log_error_client(client, fmt, ...) \
83 LOG_CLIENT_IMPL(client, LOG_ERROR, fmt, ##__VA_ARGS__)

◆ log_error_server

#define log_error_server ( transport,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_SERVER_IMPL(transport, LOG_ERROR, fmt, ##__VA_ARGS__)

Client sends ERROR log message to server.

Definition at line 113 of file network/log.h.

113#define log_error_server(transport, fmt, ...) \
114 LOG_SERVER_IMPL(transport, LOG_ERROR, fmt, ##__VA_ARGS__)

◆ log_every

#define log_every ( log_level,
interval_us,
fmt,
... )

#include <include/ascii-chat/log/log.h>

Value:
do { \
static LOG_ATOMIC_UINT64 _log_every_last_time = LOG_ATOMIC_UINT64_INIT(0); \
uint64_t _log_every_now = platform_get_monotonic_time_us(); \
uint64_t _log_every_last = atomic_load_u64(&_log_every_last_time); \
if (_log_every_now - _log_every_last >= (uint64_t)(interval_us)) { \
if (atomic_cas_u64(&_log_every_last_time, &_log_every_last, _log_every_now)) { \
log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
} \
} \
} while (asciichat_macro_block_continue())
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
unsigned long long uint64_t
#define LOG_ATOMIC_UINT64
Definition log/log.h:35
#define LOG_ATOMIC_UINT64_INIT(val)
Definition log/log.h:38

Rate-limited logging macro (thread-safe).

Logs at most once per specified time interval. Useful for threads that have an FPS and functions they call to prevent spammy logs.

Parameters
log_levelLog level (DEV, DEBUG, INFO, WARN, ERROR, FATAL)
interval_usMinimum microseconds between log messages
fmtFormat string (printf-style)
...Format arguments
Note
Each call site maintains its own static atomic timer, so different call sites can log independently. Thread-safe via atomic compare-exchange.
Uses platform_get_monotonic_time_us() for cross-platform time.

Definition at line 697 of file log/log.h.

697#define log_every(log_level, interval_us, fmt, ...) \
698 do { \
699 static LOG_ATOMIC_UINT64 _log_every_last_time = LOG_ATOMIC_UINT64_INIT(0); \
700 uint64_t _log_every_now = platform_get_monotonic_time_us(); \
701 uint64_t _log_every_last = atomic_load_u64(&_log_every_last_time); \
702 if (_log_every_now - _log_every_last >= (uint64_t)(interval_us)) { \
703 if (atomic_cas_u64(&_log_every_last_time, &_log_every_last, _log_every_now)) { \
704 log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
705 } \
706 } \
707 } while (asciichat_macro_block_continue())

◆ log_fatal

#define log_fatal ( ...)

#include <include/ascii-chat/log/log.h>

Value:
#define LOG_FATAL
Definition log/types.h:47

Log a FATAL message.

Parameters
...Format string and arguments (printf-style)
Note
FATAL messages are never stripped (always compiled in).

Definition at line 616 of file log/log.h.

Referenced by discovery_main().

◆ log_fatal_client

#define log_fatal_client ( client,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_CLIENT_IMPL(client, LOG_FATAL, fmt, ##__VA_ARGS__)

Server sends FATAL log message to client.

Definition at line 86 of file network/log.h.

86#define log_fatal_client(client, fmt, ...) \
87 LOG_CLIENT_IMPL(client, LOG_FATAL, fmt, ##__VA_ARGS__)

◆ log_fatal_server

#define log_fatal_server ( transport,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_SERVER_IMPL(transport, LOG_FATAL, fmt, ##__VA_ARGS__)

Client sends FATAL log message to server.

Definition at line 117 of file network/log.h.

117#define log_fatal_server(transport, fmt, ...) \
118 LOG_SERVER_IMPL(transport, LOG_FATAL, fmt, ##__VA_ARGS__)

◆ log_file

#define log_file ( ...)

#include <include/ascii-chat/log/log.h>

Value:
log_file_msg(__VA_ARGS__)
void log_file_msg(const char *fmt,...)
Log to file only, no stderr output.
Definition log/log.c:1952

File-only logging - writes to log file only, no stderr output.

Parameters
...Format string and arguments (printf-style)

Definition at line 663 of file log/log.h.

Referenced by asciichat_shared_init().

◆ LOG_HEADER_BUFFER_SIZE

#define LOG_HEADER_BUFFER_SIZE   512

#include <include/ascii-chat/log/log.h>

Maximum size of a log header (timestamp, level, file:line:func).

Definition at line 92 of file log/log.h.

Referenced by log_msg(), and log_plain_msg().

◆ log_info

#define log_info ( ...)

#include <include/ascii-chat/log/log.h>

Value:

Log an INFO message.

Parameters
...Format string and arguments (printf-style)
Note
INFO messages can be stripped via LOG_COMPILE_LEVEL=LOG_WARN.

Definition at line 578 of file log/log.h.

Referenced by acds_client_connect(), acds_identity_load(), acds_identity_save(), acds_on_host_announcement_ex(), acds_server_init(), acds_server_shutdown(), acip_server_receive_and_dispatch(), acip_tcp_transport_create(), action_create_config(), action_create_manpage(), ascii_otel_init(), asciichat_mdns_query(), asciichat_mdns_unadvertise(), audio_analysis_destroy(), audio_analysis_init(), audio_init(), audio_ring_buffer_read(), audio_start_duplex(), browser_client_init(), check_known_host_with_key(), client_audio_pipeline_create(), client_audio_pipeline_reset(), client_connection_create(), client_connection_destroy(), client_connection_start(), client_init(), consensus_coordinator_on_election_result(), consensus_coordinator_on_ring_members(), crypto_handshake_client_complete(), crypto_handshake_client_key_exchange(), crypto_handshake_server_auth_challenge(), crypto_handshake_server_complete(), database_init(), database_session_cleanup_expired(), database_session_clear_host(), database_session_leave(), database_session_start_migration(), database_session_update_host(), debug_stats_print(), digital_rain_init(), discover_session_parallel(), discovery_keys_verify(), discovery_keys_verify_change(), discovery_mdns_query(), discovery_session_create(), discovery_session_start(), discovery_session_stop(), ffmpeg_encoder_create_scaled(), ffmpeg_encoder_set_snapshot_actual_duration(), ffmpeg_encoder_write_frame(), grep_init(), h265_client_context_create(), h265_client_init_media_source(), h265_decoder_create(), h265_server_context_create(), handle_client_capabilities_packet(), handle_client_join_packet(), handle_client_leave_packet(), handle_image_frame_h265_packet(), handle_image_frame_packet(), handle_protocol_version_packet(), handle_size_packet(), handle_stream_start_packet(), handle_stream_stop_packet(), https_get(), log_disable_mmap(), log_enable_mmap_sized(), log_mmap_init(), log_server_stats(), mcp_server_main(), media_source_start_video(), mirror_init(), mixer_add_source(), mixer_remove_source(), nat_detect_quality(), nat_upnp_close(), nat_upnp_open_protocol(), nat_upnp_refresh(), negotiate_determine_result(), network_connection_open(), options_collect_identity_keys(), parallel_connect(), render_file_create(), server_main(), session_capture_create(), session_connection_establish(), session_display_create(), session_display_init_render_file(), session_host_add_memory_participant(), session_host_receive_packet(), session_host_set_client_transport(), session_host_start_render(), session_host_stop_render(), session_participant_connect(), session_participant_create(), session_participant_set_transport(), session_participant_start_audio(), session_participant_start_video(), session_protocol_dispatch(), session_quic_listeners_open(), session_server_like_mdns_advertise(), session_server_like_run(), signal_exit(), stats_logger_thread(), terminal_fd_reader_next(), thread_pool_create_with_workers(), ui_mdns_log_append(), ui_session_key(), update_check_perform(), video_encoder_create(), video_frame_buffer_create(), webrtc_create_peer_connection(), webrtc_peer_manager_check_gathering_timeouts(), webrtc_peer_manager_connect(), webrtc_peer_manager_create(), webrtc_peer_manager_handle_sdp(), webrtc_set_session_context(), websocket_callback_timing_log_stats(), websocket_server_init(), and websocket_server_run().

◆ log_info_client

#define log_info_client ( client,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_CLIENT_IMPL(client, LOG_INFO, fmt, ##__VA_ARGS__)

Server sends INFO log message to client.

Definition at line 74 of file network/log.h.

74#define log_info_client(client, fmt, ...) \
75 LOG_CLIENT_IMPL(client, LOG_INFO, fmt, ##__VA_ARGS__)

Referenced by handle_client_join_packet(), handle_image_frame_h265_packet(), handle_image_frame_packet(), handle_stream_start_packet(), and handle_stream_stop_packet().

◆ log_info_server

#define log_info_server ( transport,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_SERVER_IMPL(transport, LOG_INFO, fmt, ##__VA_ARGS__)

Client sends INFO log message to server.

Definition at line 105 of file network/log.h.

105#define log_info_server(transport, fmt, ...) \
106 LOG_SERVER_IMPL(transport, LOG_INFO, fmt, ##__VA_ARGS__)

◆ LOG_MMAP_MSG_BUFFER_SIZE

#define LOG_MMAP_MSG_BUFFER_SIZE   1024

#include <include/ascii-chat/log/log.h>

Maximum size of a log message in mmap mode.

Definition at line 89 of file log/log.h.

Referenced by log_mmap_write(), and log_msg().

◆ LOG_MSG_BUFFER_SIZE

#define LOG_MSG_BUFFER_SIZE   4096

#include <include/ascii-chat/log/log.h>

Maximum size of a single log message (including formatting).

Definition at line 86 of file log/log.h.

Referenced by colorize_log_message_with_color(), log_file_msg(), log_msg(), log_plain_msg(), and log_recolor_plain_entry().

◆ log_nth

#define log_nth ( log_level,
n,
fmt,
... )

#include <include/ascii-chat/log/log.h>

Value:
do { \
static LOG_ATOMIC_UINT64 _log_nth_counter = LOG_ATOMIC_UINT64_INIT(0); \
uint64_t _log_nth_count = atomic_load_u64(&_log_nth_counter); \
uint64_t _log_nth_new = _log_nth_count + 1; \
atomic_store_u64(&_log_nth_counter, _log_nth_new); \
if (_log_nth_new % (uint64_t)(n) == 0) { \
log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
} \
} while (asciichat_macro_block_continue())

Log every nth call to this code location (thread-safe).

Logs a message every nth time the code is executed. Useful for logging periodic events in tight loops without spamming the log. For example, log_nth(INFO, 1000, "Processed items") logs every 1000 calls.

Each call site maintains its own static counter, so different call sites can log independently at different frequencies.

Parameters
log_levelLog level (DEV, DEBUG, INFO, WARN, ERROR, FATAL)
nLog every nth call (1 = every call, 2 = every 2nd call, etc.)
fmtFormat string (printf-style)
...Format arguments
Note
Thread-safe via atomic fetch_add.

Definition at line 765 of file log/log.h.

765#define log_nth(log_level, n, fmt, ...) \
766 do { \
767 static LOG_ATOMIC_UINT64 _log_nth_counter = LOG_ATOMIC_UINT64_INIT(0); \
768 uint64_t _log_nth_count = atomic_load_u64(&_log_nth_counter); \
769 uint64_t _log_nth_new = _log_nth_count + 1; \
770 atomic_store_u64(&_log_nth_counter, _log_nth_new); \
771 if (_log_nth_new % (uint64_t)(n) == 0) { \
772 log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
773 } \
774 } while (asciichat_macro_block_continue())

◆ log_once

#define log_once ( log_level,
fmt,
... )

#include <include/ascii-chat/log/log.h>

Value:
do { \
static LOG_ATOMIC_UINT64 _log_once_counter = LOG_ATOMIC_UINT64_INIT(0); \
uint64_t _log_once_count = atomic_load_u64(&_log_once_counter); \
if (_log_once_count == 0) { \
atomic_store_u64(&_log_once_counter, 1); \
log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
} \
} while (asciichat_macro_block_continue())

Log exactly once per call site (thread-safe).

Logs a message exactly once, no matter how many times the code is executed. Each call site maintains its own static counter, so different call sites can log independently.

Useful for one-time initialization messages, warnings, or debug output that should only appear once per session.

Parameters
log_levelLog level (DEV, DEBUG, INFO, WARN, ERROR, FATAL)
fmtFormat string (printf-style)
...Format arguments
Note
Thread-safe via atomic operations.

Definition at line 805 of file log/log.h.

805#define log_once(log_level, fmt, ...) \
806 do { \
807 static LOG_ATOMIC_UINT64 _log_once_counter = LOG_ATOMIC_UINT64_INIT(0); \
808 uint64_t _log_once_count = atomic_load_u64(&_log_once_counter); \
809 if (_log_once_count == 0) { \
810 atomic_store_u64(&_log_once_counter, 1); \
811 log_msg(LOG_##log_level, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__); \
812 } \
813 } while (asciichat_macro_block_continue())

◆ log_only

#define log_only ( bitmask,
level,
... )

#include <include/ascii-chat/log/log.h>

Value:
do { \
if (log_only_enabled((bitmask), (level))) \
log_as(level, __VA_ARGS__); \
} while (asciichat_macro_block_continue())

Log a message given its level and if the bitmask allows so.

Parameters
bitmaskThe severity bitmask, where level n is encoded as 2^n.
levelThe log level used by the message
...Format string and arguments (printf-style)

Definition at line 536 of file log/log.h.

536#define log_only(bitmask, level, ...) \
537 do { \
538 if (log_only_enabled((bitmask), (level))) \
539 log_as(level, __VA_ARGS__); \
540 } while (asciichat_macro_block_continue())

◆ log_plain

#define log_plain ( ...)

#include <include/ascii-chat/log/log.h>

Value:
log_plain_msg(__VA_ARGS__)

Plain logging - writes to both log file and stderr without timestamps or log levels.

Parameters
...Format string and arguments (printf-style)

Definition at line 635 of file log/log.h.

Referenced by action_completions(), asciichat_error_stats_print(), audio_analysis_print_report(), config_create_default(), errno_print_chain(), errno_print_hash_stats(), errno_print_history(), errno_print_stacks(), named_print_hash_stats(), and prompt_unknown_host_no_identity().

◆ log_plain_stderr

#define log_plain_stderr ( ...)

#include <include/ascii-chat/log/log.h>

Value:
void log_plain_stderr_msg(const char *fmt,...)
Plain logging to stderr with newline.
Definition log/log.c:1843

Plain logging to stderr with newline.

Parameters
...Format string and arguments (printf-style)

Definition at line 642 of file log/log.h.

◆ log_plain_stderr_nonewline

#define log_plain_stderr_nonewline ( ...)

#include <include/ascii-chat/log/log.h>

Value:
void log_plain_stderr_nonewline_msg(const char *fmt,...)
Plain logging to stderr without trailing newline.
Definition log/log.c:1857

Plain logging to stderr without newline - for interactive prompts.

Parameters
...Format string and arguments (printf-style)

Definition at line 656 of file log/log.h.

◆ log_plain_stdout

#define log_plain_stdout ( ...)

#include <include/ascii-chat/log/log.h>

Value:
void log_plain_stdout_msg(const char *fmt,...)
Plain logging to stdout with newline.
Definition log/log.c:1938

Plain logging to stdout with newline.

Parameters
...Format string and arguments (printf-style)

Definition at line 649 of file log/log.h.

◆ LOG_SERVER_IMPL

#define LOG_SERVER_IMPL ( transport,
level,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
__FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:23

Definition at line 95 of file network/log.h.

95#define LOG_SERVER_IMPL(transport, level, fmt, ...) \
96 log_net_message(transport, level, REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER, \
97 __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)

◆ LOG_TERMINAL_BUFFER_SIZE

#define LOG_TERMINAL_BUFFER_SIZE   16384

#include <include/ascii-chat/log/log.h>

Terminal formatting budget, including NUL; distinct from persisted message storage.

Definition at line 98 of file log/log.h.

Referenced by grep_highlight_colored().

◆ log_terminal_colored_msg

#define log_terminal_colored_msg ( level,
colored_message,
plain_message )

#include <include/ascii-chat/log/log.h>

Value:
log_terminal_colored_msg_impl((level), __FILE__, __LINE__, __func__, (colored_message), (plain_message))
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

Definition at line 306 of file log/log.h.

◆ LOG_TERMINAL_ENTRY_BUFFER_SIZE

#define LOG_TERMINAL_ENTRY_BUFFER_SIZE   (LOG_HEADER_BUFFER_SIZE + LOG_TERMINAL_BUFFER_SIZE)

#include <include/ascii-chat/log/log.h>

Header plus terminal formatting budget, including NUL.

Definition at line 101 of file log/log.h.

◆ LOG_TIMESTAMP_BUFFER_SIZE

#define LOG_TIMESTAMP_BUFFER_SIZE   32

#include <include/ascii-chat/log/log.h>

Maximum size of a timestamp string.

Definition at line 95 of file log/log.h.

Referenced by log_json_async_safe(), log_json_write(), log_mmap_write(), log_msg(), log_plain_msg(), and log_terminal_msg().

◆ log_warn

#define log_warn ( ...)

#include <include/ascii-chat/log/log.h>

Value:
#define LOG_WARN
Definition log/types.h:45

Log a WARN message.

Parameters
...Format string and arguments (printf-style)
Note
WARN messages can be stripped via LOG_COMPILE_LEVEL=LOG_ERROR.

Definition at line 591 of file log/log.h.

Referenced by acds_on_host_announcement_ex(), acds_send_current_host(), acds_server_init(), acds_validate_timestamp(), acds_verify_session_create(), acds_verify_session_join(), acip_tcp_transport_create(), acip_transport_destroy(), actions_execute_deferred(), add_transport_client(), ascii_convert_with_buffers_stabilized(), ascii_otel_shutdown(), ascii_otel_sqlite(), ascii_otel_sqlite_catalog(), ascii_write(), ascii_write_destroy(), ascii_write_init(), audio_process_received_samples(), audio_start_duplex(), audio_start_thread(), audio_stop_duplex(), audio_stop_thread(), broadcast_clear_console_to_all_clients(), capture_start_thread(), capture_stop_thread(), check_gpg_key_expiry(), check_known_host_no_identity(), client_audio_pipeline_create(), client_audio_pipeline_process_duplex(), client_protocol_start(), client_video_render_thread(), config_schema_build_from_configs(), connect_with_timeout(), consensus_coordinator_on_collection_start(), consensus_coordinator_on_election_result(), consensus_coordinator_on_ring_members(), consensus_coordinator_on_stats_update(), consensus_coordinator_process(), crypto_handshake_client_key_exchange(), crypto_rekey_abort(), crypto_rekey_init(), database_init(), database_session_join(), disconnect_client_for_bad_data(), discover_session_parallel(), discovery_keys_verify(), discovery_mdns_query(), discovery_session_check_host_alive(), discovery_session_create(), discovery_session_handle_host_disconnect(), display_init(), dns_test_connectivity(), env_pop_prompt_response(), ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), ffmpeg_decoder_stop_prefetch(), find_client_by_id(), frame_validate_integrity(), gpg_agent_connect(), gpg_agent_sign(), gpg_get_public_key(), gpg_homedir_create(), gpg_homedir_destroy(), h265_decode(), handle_audio_opus_batch_packet(), handle_client_leave_packet(), handle_image_frame_h265_packet(), handle_image_frame_packet(), handle_protocol_version_packet(), keepalive_start_thread(), keepalive_stop_thread(), log_mmap_init(), log_search_enter_mode(), log_search_exit_mode(), media_source_create_interruptible(), media_source_seek(), media_source_set_loop(), mixer_add_source(), nat_upnp_close(), nat_upnp_refresh(), options_state_init(), options_warn_uninitialized(), packet_receive(), packet_receive_via_transport(), packet_send_error(), parse_gpg_keys_from_response(), parse_public_keys(), precalc_rgb_palettes(), prompt_password(), prompt_password_simple_kind(), prompt_unknown_host(), render_file_create(), select_compatible_palette(), session_capture_create(), session_display_create(), session_display_encode_frame(), session_host_broadcast_frame(), session_host_receive_packet(), session_host_render_audio(), session_host_set_client_transport(), session_protocol_build_capabilities(), session_protocol_dispatch(), session_render_loop(), session_server_like_mdns_advertise(), session_server_like_run(), setup_signal_handlers(), signaling_broadcast(), socket_configure_buffers(), splash_intro_start(), splash_wait_for_animation(), ssh_agent_has_key(), stun_servers_parse(), tcp_server_init(), term_renderer_create(), terminal_fd_reader_next(), thread_pool_interrupt_all(), thread_pool_stop_all(), ui_controller_toggle_logs(), ui_notice_first_use_complete(), ui_session_key(), update_banner_install_update(), update_banner_wait_for_check(), update_check_load_cache(), update_check_perform(), update_dimensions_to_terminal_size(), validate_gpg_key_format(), video_encoder_create(), webcam_cleanup_context(), webrtc_get_gathering_state(), webrtc_get_state(), webrtc_get_user_data(), webrtc_peer_manager_check_gathering_timeouts(), and websocket_server_init().

◆ log_warn_client

#define log_warn_client ( client,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_CLIENT_IMPL(client, LOG_WARN, fmt, ##__VA_ARGS__)

Server sends WARN log message to client.

Definition at line 78 of file network/log.h.

78#define log_warn_client(client, fmt, ...) \
79 LOG_CLIENT_IMPL(client, LOG_WARN, fmt, ##__VA_ARGS__)

◆ log_warn_server

#define log_warn_server ( transport,
fmt,
... )

#include <include/ascii-chat/network/log.h>

Value:
LOG_SERVER_IMPL(transport, LOG_WARN, fmt, ##__VA_ARGS__)

Client sends WARN log message to server.

Definition at line 109 of file network/log.h.

109#define log_warn_server(transport, fmt, ...) \
110 LOG_SERVER_IMPL(transport, LOG_WARN, fmt, ##__VA_ARGS__)

◆ MAX_LOG_SIZE

#define MAX_LOG_SIZE   (3 * 1024 * 1024)

#include <include/ascii-chat/log/log.h>

Maximum log file size in bytes (3MB) before rotation.

Definition at line 70 of file log/log.h.

Referenced by log_truncate_if_large().

◆ MAX_TERMINAL_BUFFER_ENTRIES

#define MAX_TERMINAL_BUFFER_ENTRIES   256

#include <include/ascii-chat/log/log.h>

Maximum number of buffered log entries.

Definition at line 76 of file log/log.h.

◆ MAX_TERMINAL_BUFFER_SIZE

#define MAX_TERMINAL_BUFFER_SIZE   (64 * 1024)

#include <include/ascii-chat/log/log.h>

Maximum size of terminal output buffer (64KB).

Definition at line 73 of file log/log.h.

Typedef Documentation

◆ color_scheme_t

typedef struct color_scheme_t color_scheme_t

#include <include/ascii-chat/log/log.h>

Definition at line 48 of file log/log.h.

◆ remote_log_direction_t

#include <include/ascii-chat/network/log.h>

Remote log packet direction enumeration.

Indicates the originator of a remote log message so receivers can annotate logs clearly.

Note
This typedef MUST be defined before includes to avoid circular dependency issues with packet.h

◆ session_log_buffer_t

#include <src/common/session/session_log_buffer.c>

Thread-safe fixed-size history ring for session-screen log lines.

Opaque handle to log buffer instance.

Thread-safe fixed-size history ring for session-screen log lines.

entries stores formatted messages, while the atomic write position and sequence counter preserve ordering as new lines overwrite old ones. The mutex protects snapshots and clearing; the buffer owns its synchronization state until destruction.

Enumeration Type Documentation

◆ log_level_t

#include <include/ascii-chat/log/types.h>

Logging levels enumeration.

Defines the severity levels for log messages. Used throughout the logging system without circular dependencies.

Enumerator
ASCIICHAT_LOG_DEV 

Development messages (most verbose)

ASCIICHAT_LOG_DEBUG 

Debug messages

ASCIICHAT_LOG_INFO 

Informational messages

ASCIICHAT_LOG_WARN 

Warning messages

ASCIICHAT_LOG_ERROR 

Error messages

ASCIICHAT_LOG_FATAL 

Fatal error messages (most severe)

Definition at line 33 of file log/types.h.

33 {
log_level_t
Logging levels enumeration.
Definition log/types.h:33
@ ASCIICHAT_LOG_DEBUG
Definition log/types.h:35
@ ASCIICHAT_LOG_WARN
Definition log/types.h:37
@ ASCIICHAT_LOG_INFO
Definition log/types.h:36
@ ASCIICHAT_LOG_DEV
Definition log/types.h:34
@ ASCIICHAT_LOG_FATAL
Definition log/types.h:39
@ ASCIICHAT_LOG_ERROR
Definition log/types.h:38

◆ remote_log_direction

#include <include/ascii-chat/network/log.h>

Remote log packet direction enumeration.

Indicates the originator of a remote log message so receivers can annotate logs clearly.

Note
This typedef MUST be defined before includes to avoid circular dependency issues with packet.h
Enumerator
REMOTE_LOG_DIRECTION_UNKNOWN 
REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT 
REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER 

Definition at line 20 of file network/log.h.

20 {
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:21

Function Documentation

◆ colorize_named_string()

const char * colorize_named_string ( const char * name_str)

#include <include/ascii-chat/log/named.h>

Colorize a "type/name" string for display.

Parameters
name_strString in "type/name" or "type/name.id" format
Returns
Colorized string with ANSI codes: type(yellow)/name(blue)

Used by memory report and other displays to colorize named objects. Applies colors:

  • Type: yellow (LOG_COLOR_WARN)
  • Name: blue (LOG_COLOR_DEV)
  • Separator: uncolored

Example: "thread/splash_anim.0" displays with type in yellow, name in blue

Note
Returns pointer to rotating static buffer (4 buffers)
Safe to use in printf-style calls: "%s"

Colorize a "type/name" string for display.

Parameters
name_strString in "type/name (0xaddress)" format (e.g., "thread/splash_anim.0 (0x7f123456)")
Returns
Colorized string with ANSI codes: type(yellow)/name(blue) (id(grey))

Used by memory report to colorize named object display. Returns a pointer to a static rotating buffer (4 buffers, valid until next call).

Example: "thread/splash_anim.0 (0x7f123456)" displays with:

  • "thread" in yellow
  • "splash_anim.0" in blue
  • "0x7f123456" in grey

Definition at line 897 of file log/named.c.

897 {
898#define COLORIZE_BUFFERS 4
899#define COLORIZE_BUFFER_SIZE 512
900 static char buffers[COLORIZE_BUFFERS][COLORIZE_BUFFER_SIZE];
901 static int buffer_idx = 0;
902
903 if (!name_str || name_str[0] == '\0') {
904 return name_str;
905 }
906
907 char *current_buf = buffers[buffer_idx];
908 buffer_idx = (buffer_idx + 1) % COLORIZE_BUFFERS;
909
910 /* Find the slash separator (type/name) */
911 const char *slash = strchr(name_str, '/');
912 if (!slash) {
913 /* No slash found - just return the string as-is */
914 return name_str;
915 }
916
917 /* Find opening paren for address */
918 const char *paren = strchr(name_str, '(');
919
920 /* Extract type (before slash) */
921 size_t type_len = slash - name_str;
923 size_t copy_len =
924 type_len < sizeof(type_buf) - 1 ? type_len : sizeof(type_buf) - 1;
925 memcpy(type_buf, name_str, copy_len);
926 type_buf[copy_len] = '\0';
927
928 /* Extract name (between slash and paren, or end of string) */
929 const char *name_start = slash + 1;
930 size_t name_len;
931 if (paren && paren > slash) {
932 /* Skip spaces before paren */
933 const char *name_end = paren - 1;
934 while (name_end > name_start && *name_end == ' ') {
935 name_end--;
936 }
937 name_len = name_end - name_start + 1;
938 } else {
939 name_len = strlen(name_start);
940 }
941
942 char name_buf[LOG_NAMED_NAME_BUFFER_SIZE];
943 size_t name_copy_len =
944 name_len < sizeof(name_buf) - 1 ? name_len : sizeof(name_buf) - 1;
945 memcpy(name_buf, name_start, name_copy_len);
946 name_buf[name_copy_len] = '\0';
947
948 /* Apply colors */
949 const char *type_colored = colored_string(LOG_COLOR_WARN, type_buf);
950 const char *name_colored = colored_string(LOG_COLOR_DEV, name_buf);
951
952 /* Format: type(yellow)/name(blue) and add address part if present */
953 if (paren) {
954 /* Extract address (0x...) from parentheses */
955 const char *addr_start = paren + 1;
956 const char *addr_end = strchr(addr_start, ')');
957 if (addr_end) {
958 size_t addr_len = addr_end - addr_start;
959 char addr_buf[LOG_NAMED_ADDR_BUFFER_SIZE];
960 size_t addr_copy_len =
961 addr_len < sizeof(addr_buf) - 1 ? addr_len : sizeof(addr_buf) - 1;
962 memcpy(addr_buf, addr_start, addr_copy_len);
963 addr_buf[addr_copy_len] = '\0';
964
965 const char *addr_colored = colored_string(LOG_COLOR_GREY, addr_buf);
966 safe_snprintf(current_buf, COLORIZE_BUFFER_SIZE, "%s/%s (%s)",
967 type_colored, name_colored, addr_colored);
968 } else {
969 safe_snprintf(current_buf, COLORIZE_BUFFER_SIZE, "%s/%s %s", type_colored,
970 name_colored, paren);
971 }
972 } else {
973 safe_snprintf(current_buf, COLORIZE_BUFFER_SIZE, "%s/%s", type_colored,
974 name_colored);
975 }
976
977 return current_buf;
978#undef COLORIZE_BUFFERS
979#undef COLORIZE_BUFFER_SIZE
980}
@ LOG_COLOR_GREY
Definition color.h:13
@ LOG_COLOR_DEV
Definition color.h:7
@ LOG_COLOR_WARN
Definition color.h:10
const char * colored_string(log_color_t color, const char *text)
Build a colored string for terminal output.
#define LOG_NAMED_ADDR_BUFFER_SIZE
Definition log/named.c:27
#define COLORIZE_BUFFER_SIZE
#define LOG_NAMED_TYPE_EXTENDED_BUFFER_SIZE
Definition log/named.c:25
#define COLORIZE_BUFFERS
#define LOG_NAMED_NAME_BUFFER_SIZE
Definition log/named.c:26

References colored_string(), COLORIZE_BUFFER_SIZE, COLORIZE_BUFFERS, LOG_COLOR_DEV, LOG_COLOR_GREY, LOG_COLOR_WARN, LOG_NAMED_ADDR_BUFFER_SIZE, LOG_NAMED_NAME_BUFFER_SIZE, and LOG_NAMED_TYPE_EXTENDED_BUFFER_SIZE.

◆ format_message()

char * format_message ( const char * format,
va_list args )

#include <include/ascii-chat/log/log.h>

Format a message using va_list.

Parameters
formatFormat string
argsVariable arguments list
Returns
Formatted message string (must be freed by caller)

Definition at line 305 of file log/log.c.

305 {
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}
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
@ ERROR_INVALID_STATE
#define LOGGING_INTERNAL_ERROR(error, message,...)
Definition log/log.c:257
action_args_t args

References args, ERROR_INVALID_STATE, LOGGING_INTERNAL_ERROR, SAFE_FREE, and SAFE_MALLOC.

Referenced by log_net_message().

◆ get_current_time_formatted()

size_t get_current_time_formatted ( char * time_buf)

#include <include/ascii-chat/log/log.h>

Get current time as formatted string.

Parameters
time_bufOutput buffer for formatted time
Returns
Number of characters written (excluding null terminator)

Definition at line 272 of file log/log.c.

272 {
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}
#define NS_PER_SEC_INT
Definition time.h:173
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57

References ERROR_INVALID_STATE, LOGGING_INTERNAL_ERROR, NS_PER_SEC_INT, and platform_localtime().

Referenced by log_msg(), log_plain_msg(), and log_terminal_msg().

◆ log_cleanup_colors()

void log_cleanup_colors ( void )

#include <include/ascii-chat/log/log.h>

Clean up compiled color scheme.

Should be called AFTER memory reporting to ensure colored output. Safe to call multiple times (idempotent).

Definition at line 2248 of file log/log.c.

2248{}

Referenced by asciichat_shared_destroy().

◆ log_clear_session_log_buffer()

void log_clear_session_log_buffer ( void )

#include <include/ascii-chat/log/log.h>

Unregister the session log buffer.

No-op if no buffer is currently registered.

Definition at line 2272 of file log/log.c.

2272 {
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}
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
uint64_t atomic_load_u64_impl(const atomic_t *a)

References atomic_load_u64_impl(), and atomic_ptr_store().

Referenced by log_system_destroy(), splash_log_destroy(), ui_mdns_log_destroy(), ui_session_destroy(), and ui_status_log_destroy().

◆ log_colored_msg_impl()

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 )

#include <include/ascii-chat/log/log.h>

Write semantically colored terminal text and an ANSI-free log equivalent.

Parameters
levelSeverity used for terminal routing and JSON output
colored_messageMessage containing semantic ANSI colors
plain_messageEquivalent message without ANSI colors

Preserves caller-supplied semantic coloring for terminal output while using the plain version for filtering, file/mmap logging, JSON, and non-color terminals. Both representations are routed as one logical log entry.

Definition at line 1670 of file log/log.c.

1672 {
1673 log_colored_msg_internal(level, file, line, func, colored_message,
1674 plain_message, true);
1675}

◆ log_destroy()

void log_destroy ( void )

#include <include/ascii-chat/log/log.h>

Destroy the logging system and close log file.

Definition at line 737 of file log/log.c.

737 {
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}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
int atomic_load_int(atomic_t *a)
Atomically load an int value.
int platform_close(int fd)
Definition filesystem.c:91
void grep_destroy(void)
Clean up filter resources.
Definition grep.c:1065
void log_template_free(log_template_t *format)
Free compiled format structure.
Definition log/format.c:341
bool log_mmap_is_active(void)
Check if mmap logging is active.
Definition mmap.c:426
void log_mmap_destroy(void)
Shutdown mmap logging.
Definition mmap.c:284

References atomic_load_int(), atomic_store_bool(), atomic_store_int(), grep_destroy(), log_mmap_destroy(), log_mmap_is_active(), log_template_free(), and platform_close().

Referenced by asciichat_shared_destroy(), and main().

◆ log_disable_file_output()

void log_disable_file_output ( void )

#include <include/ascii-chat/log/log.h>

Disable file output and use stderr instead.

Closes the current log file and redirects file output to stderr. Used when switching to JSON-only logging or when disabling text file output.

Definition at line 848 of file log/log.c.

848 {
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}

References atomic_load_int(), atomic_store_int(), and platform_close().

◆ log_disable_mmap()

void log_disable_mmap ( void )

#include <include/ascii-chat/log/log.h>

Disable mmap logging and return to mutex-based logging.

Flushes remaining entries and closes the mmap file.

Definition at line 2207 of file log/log.c.

2207 {
2208 if (log_mmap_is_active()) {
2210 log_info("Lock-free mmap logging disabled");
2211 }
2212}

References log_info, log_mmap_destroy(), and log_mmap_is_active().

◆ log_enable_mmap()

asciichat_error_t log_enable_mmap ( const char * log_path)

#include <include/ascii-chat/log/log.h>

Enable lock-free mmap-based logging.

When enabled, log messages bypass the mutex and use atomic operations to write directly to a memory-mapped log file as human-readable text.

Benefits:

  • No mutex contention between logging threads
  • Crash-safe: text is written directly to mmap'd file, readable after crash
  • Fast path uses atomic fetch_add, no locks
  • ERROR/FATAL messages sync immediately for visibility
  • Simple: log file IS the mmap file (no separate binary format)
Parameters
log_pathPath to the log file (will be memory-mapped)
Returns
ASCIICHAT_OK on success, error code on failure
Note
Call log_init() first, then log_enable_mmap() to upgrade to lock-free

Definition at line 2188 of file log/log.c.

2188 {
2189 return log_enable_mmap_sized(log_path, 0); /* Use default size */
2190}
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

References log_enable_mmap_sized().

◆ log_enable_mmap_sized()

asciichat_error_t log_enable_mmap_sized ( const char * log_path,
size_t max_size )

#include <include/ascii-chat/log/log.h>

Enable lock-free mmap logging with custom file size.

Parameters
log_pathPath to the log file
max_sizeMaximum file size in bytes (0 = default 4MB)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 2192 of file log/log.c.

2192 {
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}
@ ERROR_INVALID_PARAM
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

References ASCIICHAT_OK, ERROR_INVALID_PARAM, log_info, log_mmap_init_simple(), and SET_ERRNO.

Referenced by log_enable_mmap().

◆ log_file_msg()

void log_file_msg ( const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Log to file only, no stderr output.

Parameters
fmtFormat string (printf-style)
...Format arguments

Writes to log file only, without terminal output.

Definition at line 1952 of file log/log.c.

1952 {
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}
#define LOG_MSG_BUFFER_SIZE
Maximum size of a single log message (including formatting).
Definition log/log.h:86
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
void session_log_buffer_append(session_log_buffer_t *buf, const char *message)
Append a log message to the buffer.

References args, atomic_load_u64(), LOG_INFO, log_mmap_is_active(), log_mmap_write(), LOG_MSG_BUFFER_SIZE, and session_log_buffer_append().

Referenced by session_display_write_ascii_frame().

◆ log_get_color_array()

const char ** log_get_color_array ( void )

#include <include/ascii-chat/log/log.h>

Get the appropriate color array based on terminal capabilities.

Returns
Pointer to color array (16-color, 256-color, or truecolor)

Automatically detects terminal capabilities and returns the appropriate color array.

Definition at line 2117 of file log/log.c.

2117 {
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}
void colorscheme_current_palette(colorscheme_palette_t *palette, terminal_color_mode_t mode)

References colorscheme_current_palette().

Referenced by log_get_foreground_color(), log_level_color(), log_msg(), and log_recolor_plain_entry().

◆ log_get_color_mode()

int log_get_color_mode ( void )

#include <include/ascii-chat/log/log.h>

Current detected terminal color depth, shared by UI components.

Definition at line 2126 of file log/log.c.

2126 {
2127 init_terminal_capabilities();
2128 return g_log.terminal_caps.color_level;
2129}

Referenced by log_level_color_for_output(), and ui_buttons_render().

◆ log_get_force_stderr()

bool log_get_force_stderr ( void )

#include <include/ascii-chat/log/log.h>

Get current force_stderr setting.

Returns
true if all logs are forced to stderr, false otherwise

Definition at line 844 of file log/log.c.

844{ return atomic_load_u64(&g_log.force_stderr); }

References atomic_load_u64().

Referenced by terminal_choose_log_fd().

◆ log_get_foreground_color()

const char * log_get_foreground_color ( void )

#include <include/ascii-chat/log/log.h>

Theme- and capability-aware neutral text color from the active scheme.

Definition at line 2131 of file log/log.c.

2131 {
2133 return live_log_palette.foreground;
2134}
const char ** log_get_color_array(void)
Get the appropriate color array based on terminal capabilities.
Definition log/log.c:2117

References log_get_color_array().

◆ log_get_level()

log_level_t log_get_level ( void )

#include <include/ascii-chat/log/log.h>

Get the current minimum log level.

Returns
Current log level

Definition at line 814 of file log/log.c.

814 {
815 return (log_level_t)atomic_load_u64(&g_log.level);
816}

References atomic_load_u64().

Referenced by errno_print_chain().

◆ log_get_session_log_buffer()

session_log_buffer_t * log_get_session_log_buffer ( void )

#include <include/ascii-chat/log/log.h>

Get the currently registered session log buffer.

Returns the buffer that was previously registered with log_set_session_log_buffer(). Returns NULL if no buffer is currently registered.

Returns
Pointer to registered buffer, or NULL

Returns the buffer that was previously registered with log_set_session_log_buffer(). Returns NULL if no buffer is currently registered.

Definition at line 2287 of file log/log.c.

2287 {
2288 return (session_log_buffer_t *)atomic_ptr_load(&g_log.session_log_buffer);
2289}
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
struct session_log_buffer session_log_buffer_t
Thread-safe fixed-size history ring for session-screen log lines.

References atomic_ptr_load().

Referenced by log_search_gather_and_filter_logs(), and ui_session_destroy().

◆ log_get_template()

void * log_get_template ( void )

#include <include/ascii-chat/log/log.h>

Get the current log format template (opaque pointer).

Returns
Opaque pointer to the current log format template (may be NULL if not set) Cast to log_template_t* after including log/format.h

Returns the compiled log format template used by the logging system. This is useful for code that needs to format log entries using the same template as the rest of the logging system (e.g., platform code).

Note
The returned pointer is valid only for the lifetime of the logging system
It's safe to call before log_init() (will return NULL)
Return type is void* (opaque) to avoid circular dependency with format.h

Get the current log format template (opaque pointer).

Returns
Opaque pointer to the current log format template (may be NULL if not set)

Returns the compiled log format template used by the logging system. This is used by platform code (e.g., backtrace formatting) to format log entries using the same template as the rest of the logging system. Returns void* (opaque) to avoid circular dependency with format.h.

Definition at line 2607 of file log/log.c.

2607{ return (void *)g_log.format; }

◆ log_get_terminal_output()

bool log_get_terminal_output ( void )

#include <include/ascii-chat/log/log.h>

Get current terminal output setting.

Returns
true if terminal output is enabled, false otherwise

Definition at line 836 of file log/log.c.

836 {
837 return atomic_load_u64(&g_log.terminal_output_enabled);
838}

References atomic_load_u64().

Referenced by config_load_and_apply().

◆ log_init()

void log_init ( const char * filename,
log_level_t level,
bool force_stderr,
bool use_mmap )

#include <include/ascii-chat/log/log.h>

Initialize the logging system.

Parameters
filenameLog file path (or NULL for no file logging)
levelMinimum log level to output
force_stderrIf true, route ALL logs to stderr (for client mode to keep stdout clean)
use_mmapIf true, use fully lock-free mmap logging (recommended). If mmap fails, uses stderr only (no mutex fallback).
Note
When use_mmap=true, the entire logging path is lock-free:
  • File output uses atomic operations on mmap'd memory
  • Terminal output uses atomic fprintf/fwrite to fd
  • No mutex is ever acquired in the hot path

Definition at line 627 of file log/log.c.

628 {
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}
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_GETENV(name)
void log_redetect_terminal_capabilities(void)
Re-detect terminal capabilities after logging is initialized.
Definition log/log.c:2078
session_log_buffer_t * session_log_buffer_create(void)
Create a new session log buffer instance.
bool terminal_is_piped_output(void)

References ASCIICHAT_OK, atomic_load_int(), atomic_load_u64(), atomic_store_bool(), atomic_store_int(), atomic_store_u64(), log_mmap_init_simple(), log_redetect_terminal_capabilities(), log_set_format(), platform_close(), platform_open(), SAFE_GETENV, SAFE_STRNCPY, session_log_buffer_create(), and terminal_is_piped_output().

Referenced by asciichat_shared_init(), browser_client_init(), client_init(), main(), and mirror_init().

◆ log_init_colors()

void log_init_colors ( void )

#include <include/ascii-chat/log/log.h>

Initialize logging color system with current terminal capabilities.

Compiles the active color scheme to ANSI codes based on terminal capabilities. Called automatically during terminal capability detection.

Definition at line 2172 of file log/log.c.

2172 {
2173 if (g_log.terminal_caps_detecting ||
2174 !lifecycle_is_initialized(&g_log.lifecycle))
2175 return;
2177}
const color_scheme_t * colorscheme_get_active_scheme(void)
Get currently active color scheme.

References colorscheme_get_active_scheme().

Referenced by log_system_init().

◆ log_labeled()

void log_labeled ( const char * label,
log_color_t color,
const char * message,
... )

#include <include/ascii-chat/log/log.h>

Print a labeled message with color.

Parameters
labelThe label text to print (appears before the message)
colorColor for the label (from log_color_t enum)
messageFormat string (printf-style) for the message
...Format arguments

Used for consistent formatting of section headers and labeled output. The label is colored, followed by the message content. Output goes to both stderr and log file.

References args, and enabled.

◆ log_level_color()

const char * log_level_color ( log_color_t color)

#include <include/ascii-chat/log/log.h>

Get color string for a given color enum.

Parameters
colorColor enum value
Returns
ANSI color code string

Definition at line 2136 of file log/log.c.

2136 {
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}
@ LOG_COLOR_RESET
Definition color.h:14
@ LOG_COLOR_WHITE
Definition color.h:15
unsigned char colors[(512 *256 *2) *3]
Definition fft.c:23

References colors, LOG_COLOR_RESET, LOG_COLOR_WHITE, and log_get_color_array().

◆ log_level_color_for_output()

const char * log_level_color_for_output ( log_color_t color,
bool enabled )

#include <include/ascii-chat/log/log.h>

Resolve a color after the caller has selected an output policy. Explicitly colored non-terminal output uses the portable 16-color palette. The returned thread-local string is valid until the next call.

Definition at line 2149 of file log/log.c.

2149 {
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}
int color_mode
Definition fft.c:26
bool enabled
Is filtering active?
Definition grep.c:63
int log_get_color_mode(void)
Definition log/log.c:2126
#define GET_OPTION(field)
Definition options.h:1339

References color_mode, colorscheme_current_palette(), enabled, GET_OPTION, LOG_COLOR_RESET, LOG_COLOR_WHITE, and log_get_color_mode().

Referenced by colored_string(), and log_template_apply().

◆ log_lock_terminal()

bool log_lock_terminal ( void )

#include <include/ascii-chat/log/log.h>

Lock terminal output for exclusive access by the calling thread.

Call this before interactive prompts (like password entry, yes/no questions) to ensure only the calling thread can output to the terminal. Other threads' log messages will be buffered and flushed when the terminal is unlocked.

While locked:

  • The locking thread can use log_plain() to write to terminal
  • Other threads' log messages go to log file and are buffered
  • Buffered messages are flushed to terminal on unlock

Must be paired with log_unlock_terminal().

Returns
The previous terminal lock state (for nested calls)

Definition at line 905 of file log/log.c.

905 {
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}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.

References atomic_cas_bool(), atomic_load_bool(), and atomic_store_u64().

◆ log_msg()

void log_msg ( log_level_t level,
const char * file,
int line,
const char * func,
const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Log a message at a specific level.

Parameters
levelLog level (LOG_DEV, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL)
fileSource file name (or NULL to omit)
lineSource line number (or 0 to omit)
funcFunction name (or NULL to omit)
fmtFormat string (printf-style)
...Format arguments

Definition at line 1313 of file log/log.c.

1314 {
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}
void platform_log_hook(log_level_t level, const char *message)
Definition apple.c:55
const char * colorize_log_message(const char *message)
Colorize a log message for terminal output.
Definition colorize.c:560
#define LOG_HEADER_BUFFER_SIZE
Maximum size of a log header (timestamp, level, file:line:func).
Definition log/log.h:92
size_t get_current_time_formatted(char *time_buf)
Get current time as formatted string.
Definition log/log.c:272
#define LOG_TIMESTAMP_BUFFER_SIZE
Maximum size of a timestamp string.
Definition log/log.h:95
#define LOG_MMAP_MSG_BUFFER_SIZE
Maximum size of a log message in mmap mode.
Definition log/log.h:89
#define options_terminal_settings()
Definition options.h:1287
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
int terminal_choose_log_fd(int level)
void ascii_otel_log(int level, const char *file, int line, const char *function, const char *format, va_list args)
Definition otel.c:844
bool terminal_should_color_output(int fd, const terminal_options_t *options)
bool ui_controller_is_presenting(void)

References args, ascii_otel_log(), atomic_load_bool(), atomic_load_int(), atomic_load_u64(), colorize_log_message(), colors, ERROR_INVALID_STATE, get_current_time_formatted(), LOG_COLOR_RESET, log_get_color_array(), LOG_HEADER_BUFFER_SIZE, log_json_write(), log_mmap_is_active(), LOG_MMAP_MSG_BUFFER_SIZE, log_mmap_write(), LOG_MSG_BUFFER_SIZE, LOG_TIMESTAMP_BUFFER_SIZE, LOGGING_INTERNAL_ERROR, options_terminal_settings, platform_log_hook(), session_log_buffer_append(), terminal_choose_log_fd(), terminal_should_color_output(), and ui_controller_is_presenting().

Referenced by handle_remote_log_packet_from_client(), log_net_message(), and ui_notice_confirm_kind().

◆ log_named_format_message()

int log_named_format_message ( const char * message,
char * output,
size_t output_size )

#include <include/ascii-chat/log/named.h>

Format hex addresses in a message as named object descriptions.

Parameters
messageInput message (may contain hex addresses like 0x123456)
outputOutput buffer for formatted message
output_sizeSize of output buffer (must be > 0)
Returns
Length of output string (excluding null terminator) if any formatting was applied, -1 if no formatting was applied or on error

Scans the input message for hex addresses in the format 0x[0-9a-fA-F]+. For each address found, checks the named object registry. If registered, replaces the address with "type: name (0xaddress)" format. If not registered, leaves the original hex address unchanged.

The output buffer is always null-terminated.

Note
The formatting is idempotent - applying it twice gives the same result
This function is efficient for messages with few hex addresses (common case)
Works correctly with 32-bit and 64-bit address formats

Definition at line 560 of file log/named.c.

561 {
562 if (!message || !output || output_size == 0) {
563 return -1;
564 }
565
566 size_t out_pos = 0;
567 const char *p = message;
568 bool any_transformed = false;
569
570 while (*p && out_pos < output_size - 1) {
571 /* Look for "0x" prefix indicating a hex address */
572 if (*p == '0' && *(p + 1) == 'x' && isxdigit(*(p + 2))) {
573 const char *hex_start = p;
574 if (try_format_hex_address(message, hex_start, output, output_size,
575 &out_pos, &p)) {
576 any_transformed = true;
577 continue;
578 }
579
580 /* Not registered or formatting failed - copy original hex address */
581 const char *hex_end = hex_start + 2; /* Start after "0x" */
582 while (*hex_end && isxdigit(*hex_end)) {
583 hex_end++;
584 }
585 size_t hex_len = hex_end - hex_start;
586 if (hex_len < output_size - out_pos) {
587 memcpy(output + out_pos, hex_start, hex_len);
588 out_pos += hex_len;
589 p = hex_end;
590 } else {
591 /* Buffer overflow - truncate and stop */
592 break;
593 }
594 } else if (isdigit(*p)) {
595 /* Look for decimal integers that might be FDs or packet types */
596 const char *int_start = p;
597 int fd_value = 0;
598 int digit_count = 0;
599
600 /* Parse decimal digits */
601 while (*p && isdigit(*p) &&
602 digit_count < 6) { /* FDs rarely exceed 999999 */
603 fd_value = fd_value * 10 + (*p - '0');
604 p++;
605 digit_count++;
606 }
607
608 /* Skip if this integer is part of already-formatted output like "(fd=20)"
609 * or "(type/name (...))" */
610 bool is_already_formatted = false;
611 if (int_start - message >= 5) {
612 /* Check for "(fd=", "(pkt_type=", "(socket=", "(sockfd=", or "(type/"
613 * patterns to prevent re-formatting. Named objects are formatted as:
614 * type/name (0xaddress) or type/name (key=value) We need to detect if
615 * we're already inside a formatted output.
616 */
617 const char *check = int_start - 1;
618 while (check > message && isspace(*check))
619 check--;
620
621 // Only access *check if pointer is within bounds
622 if (check >= message && *check == '=') {
623 /* Found "=", now check what prefix it has for patterns like "(fd=20)"
624 * or "(socket=20)" or "(pkt_type=123)" */
625 const char *eq_pos = check;
626 check--;
627 while (check > message && (isalnum(*check) || *check == '_')) {
628 check--;
629 }
630 check++;
631
632 size_t prefix_len = eq_pos - check;
633 if ((prefix_len == 2 && strncmp(check, "fd", 2) == 0) ||
634 (prefix_len == 6 && strncmp(check, "socket", 6) == 0) ||
635 (prefix_len == 6 && strncmp(check, "sockfd", 6) == 0) ||
636 (prefix_len == 8 && strncmp(check, "pkt_type", 8) == 0)) {
637 /* Only mark as already-formatted if inside formatted output:
638 * - "(" before keyword: parenthesized value like "(sockfd=15)"
639 * - "/" before keyword: name part of type/name like "fd/fd=7"
640 * Raw log patterns like "sockfd=15" should still be eligible for
641 * replacement. */
642 const char *before_kw = check - 1;
643 while (before_kw > message && isspace(*before_kw))
644 before_kw--;
645 if (before_kw >= message &&
646 (*before_kw == '(' || *before_kw == '/')) {
647 is_already_formatted = true;
648 }
649 }
650 } else if (check >= message && *check == '/') {
651 /* Found "/", now check if this is a type/name pattern.
652 * Format is "(type/name (...)" where type is word characters (thread,
653 * mutex, socket, etc.) Must verify "/" is preceded by word characters
654 * AND "(" to ensure it's a formatted type.
655 */
656 const char *slash_pos = check;
657 check--;
658 while (check > message && (isalnum(*check) || *check == '_')) {
659 check--;
660 }
661 check++;
662
663 /* Check that the "/" was preceded by word characters (indicating a
664 * type name) */
665 size_t type_len = slash_pos - check;
666 if (type_len > 0 && (isalpha(*check) || *check == '_')) {
667 /* Verify this is a registered type/name pattern by checking for "("
668 * before the type AND checking if the type actually exists in the
669 * registry */
670 const char *type_start = check;
671 const char *before_type = type_start - 1;
672 while (before_type > message && isspace(*before_type)) {
673 before_type--;
674 }
675
676 /* Only mark as formatted if:
677 * 1. Preceded by "(" - ensures pattern looks like "(type/name ...)"
678 * 2. Type exists in registry - prevents false positives on random
679 * text */
680 if (before_type >= message && *before_type == '(' &&
681 is_type_in_registry(type_start, type_len)) {
682 is_already_formatted = true;
683 }
684 }
685 }
686 }
687
688 /* Check if this is a registered packet type */
689 if (!is_already_formatted && digit_count > 0 &&
690 has_packet_type_prefix(message, int_start)) {
691 named_metadata_t metadata;
692 const char *name = named_packet_metadata_copy(fd_value, &metadata)
693 ? metadata.name
694 : NULL;
695 if (name) {
696 const char *prefix_start =
697 find_packet_type_prefix_start(message, int_start);
698 size_t prefix_len = int_start - prefix_start;
699 size_t saved_pos = out_pos;
700
701 if (out_pos >= prefix_len) {
702 out_pos -= prefix_len;
703 }
704
705 if (write_formatted_packet_type(fd_value, name, output, output_size,
706 &out_pos)) {
707 any_transformed = true;
708 continue;
709 }
710
711 out_pos = saved_pos; /* Restore on failure */
712 }
713 }
714
715 /* Check if this is a registered file descriptor */
716 if (!is_already_formatted && digit_count > 0 &&
717 has_fd_prefix(message, int_start)) {
718 named_metadata_t metadata;
719 const char *name =
720 named_fd_metadata_copy(fd_value, &metadata) ? metadata.name : NULL;
721 const char *reg_type = NULL;
722 if (!name &&
723 named_metadata_copy((uintptr_t)(intptr_t)fd_value, &metadata)) {
724 name = metadata.name;
725 reg_type = metadata.type;
726 }
727
728 if (name) {
729 const char *prefix_start = find_fd_prefix_start(message, int_start);
730 size_t prefix_len = int_start - prefix_start;
731 size_t saved_pos = out_pos;
732
733 if (out_pos >= prefix_len) {
734 out_pos -= prefix_len;
735 }
736
737 bool formatted = false;
738 if (reg_type) {
739 /* From main registry — use registered type and original prefix
740 * keyword */
741 const char *kw_end = prefix_start;
742 while (kw_end < int_start && (isalnum(*kw_end) || *kw_end == '_'))
743 kw_end++;
744 size_t kw_len = kw_end - prefix_start;
745
746 char kw_buf[LOG_NAMED_KW_BUFFER_SIZE];
747 if (kw_len > 0 && kw_len < sizeof(kw_buf)) {
748 memcpy(kw_buf, prefix_start, kw_len);
749 kw_buf[kw_len] = '\0';
750 } else {
751 snprintf(kw_buf, sizeof(kw_buf), "%.*s",
752 (int)(sizeof(kw_buf) - 1), reg_type);
753 }
754
756 int written = snprintf(temp, sizeof(temp), "%s/%s (%s=%d)",
757 reg_type, name, kw_buf, fd_value);
758 if (written > 0 && (size_t)written < sizeof(temp) &&
759 out_pos + (size_t)written < output_size - 1) {
760 memcpy(output + out_pos, temp, (size_t)written);
761 out_pos += (size_t)written;
762 formatted = true;
763 }
764 } else {
765 formatted = write_formatted_fd(fd_value, name, output, output_size,
766 &out_pos);
767 }
768
769 if (formatted) {
770 any_transformed = true;
771 continue;
772 }
773
774 out_pos = saved_pos; /* Restore on failure */
775 }
776 }
777
778 /* Not a registered FD or formatting failed - copy original number */
779 if (!copy_unformatted_decimal(int_start, p, output, output_size,
780 &out_pos)) {
781 break;
782 }
783 } else {
784 /* Check if this is the start of "type=DIGIT" pattern */
785 if (*p == 't' && p + 4 < message + strlen(message) &&
786 is_type_equals_pattern(p)) {
787 if (!type_equals_inside_parens(p, message)) {
788 const char *digit_end = p + 5;
789 int pkt_value = parse_decimal_digits(digit_end, &digit_end);
790
791 if (pkt_value > 0) {
792 named_metadata_t metadata;
793 const char *name = named_packet_metadata_copy(pkt_value, &metadata)
794 ? metadata.name
795 : NULL;
796 if (name && write_formatted_type_equals(pkt_value, name, output,
797 output_size, &out_pos)) {
798 p = digit_end;
799 any_transformed = true;
800 continue;
801 }
802 }
803 }
804 }
805
806 /* Regular character - copy it */
807 copy_char_to_output(output, &out_pos, *p++);
808 }
809 }
810
811 /* Null terminate */
812 if (out_pos < output_size) {
813 output[out_pos] = '\0';
814 } else {
815 output[output_size - 1] = '\0';
816 }
817
818 return any_transformed ? (int)out_pos : -1;
819}
bool named_packet_metadata_copy(int packet_type, named_metadata_t *output)
bool named_metadata_copy(uintptr_t key, named_metadata_t *output)
bool named_fd_metadata_copy(int fd, named_metadata_t *output)
#define LOG_NAMED_KW_BUFFER_SIZE
Definition log/named.c:23
#define LOG_NAMED_TEMP_BUFFER_SIZE
Definition log/named.c:24
The useful part of named metadata is in its fields: together they describe what is pending,...

References LOG_NAMED_KW_BUFFER_SIZE, LOG_NAMED_TEMP_BUFFER_SIZE, named_metadata_t::name, named_fd_metadata_copy(), named_metadata_copy(), named_packet_metadata_copy(), and named_metadata_t::type.

Referenced by log_named_format_or_original().

◆ log_named_format_or_original()

const char * log_named_format_or_original ( const char * message)

#include <include/ascii-chat/log/named.h>

Format named objects in a message (thread-local buffer).

Parameters
messageInput message
Returns
Formatted message string if any formatting was applied, original message if no formatting was applied

Convenience wrapper that handles buffer management internally using a thread-local buffer. The returned pointer is valid only until the next call to this function from the same thread.

Safe to use directly in log macros:

const char * log_named_format_or_original(const char *message)
Format named objects in a message (thread-local buffer).
Definition log/named.c:831
Note
Maximum formatted message length is 4096 bytes
If format buffer overflows, returns original message
Parameters
messageInput message
Returns
Formatted message string (thread-local buffer, valid only until next call)

Convenience wrapper that uses a thread-local buffer internally. Applies formatting iteratively until the message stops changing (fixpoint). Returns the original message if no formatting was applied.

Definition at line 831 of file log/named.c.

831 {
832 if (!message) {
833 return message;
834 }
835
836 static _Thread_local char format_buffer[NAMED_FORMAT_BUFFER_SIZE];
837 static _Thread_local char work_buffer[NAMED_FORMAT_BUFFER_SIZE];
838
839 /* Apply formatting iteratively until the message stabilizes (no more changes)
840 */
841 const char *current = message;
842 size_t max_iterations = 3; /* Reduce iterations to prevent recursion (prevent
843 transforming already-transformed output) */
844
845 for (size_t iter = 0; iter < max_iterations; iter++) {
846 int result =
847 log_named_format_message(current, format_buffer, sizeof(format_buffer));
848
849 if (result <= 0) {
850 /* No transformation was made, we've reached a fixpoint */
851 return current == message ? message : format_buffer;
852 }
853
854 /* Check if the message changed */
855 if (strcmp(current, format_buffer) == 0) {
856 /* No actual change, return the current version */
857 return format_buffer;
858 }
859
860 /* Message changed, prepare for next iteration */
861 if (current == message) {
862 /* First iteration, use format_buffer as input for next iteration */
863 current = format_buffer;
864 } else {
865 /* Subsequent iterations, swap buffers */
866 asciichat_error_t strcpy_result =
867 SAFE_STRCPY(work_buffer, sizeof(work_buffer), format_buffer);
868 if (strcpy_result != ASCIICHAT_OK) {
869 log_error("Failed to copy format buffer: %s",
870 asciichat_error_format(NULL, strcpy_result));
871 return format_buffer;
872 }
873 current = work_buffer;
874 }
875 }
876
877 /* Max iterations reached, return last formatted version */
878 return format_buffer;
879}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SAFE_STRCPY(dest, dest_size, src)
int log_named_format_message(const char *message, char *output, size_t output_size)
Format hex addresses in a message as named object descriptions.
Definition log/named.c:560
#define NAMED_FORMAT_BUFFER_SIZE
Definition log/named.c:50

References asciichat_error_format(), ASCIICHAT_OK, log_error, log_named_format_message(), NAMED_FORMAT_BUFFER_SIZE, and SAFE_STRCPY.

Referenced by log_template_apply().

◆ log_net_message()

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,
... )

#include <include/ascii-chat/log/log.h>

Log a message to all destinations (network, file, and terminal).

Parameters
transportDestination connection transport
levelLog severity used for remote and local logging
directionRemote log direction metadata
fileSource file name (or NULL to omit)
lineSource line number (or 0 to omit)
funcFunction name (or NULL to omit)
fmtFormat string (printf-style)
...Format arguments
Returns
ASCIICHAT_OK on success, error code otherwise

Definition at line 1998 of file log/log.c.

2002 {
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}
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
asciichat_errno_scope_t errno_checkpoint(void)
@ ERROR_MEMORY
Definition error_codes.h:55
char * format_message(const char *format, va_list args)
Format a message using va_list.
Definition log/log.c:305
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
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...

References acip_send_remote_log(), ASCIICHAT_OK, asciichat_error_context_t::code, errno_checkpoint(), errno_peek_since(), ERROR_INVALID_PARAM, ERROR_MEMORY, format_message(), log_msg(), LOG_WARN, SAFE_FREE, and SET_ERRNO.

Referenced by threaded_send_client_join_packet().

◆ log_plain_msg()

void log_plain_msg ( const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Plain logging without timestamps or levels.

Parameters
fmtFormat string (printf-style)
...Format arguments

Writes to both log file and stderr without timestamps or log levels.

Definition at line 1685 of file log/log.c.

1685 {
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}
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87

References args, atomic_load_int(), atomic_load_u64(), colorize_log_message(), get_current_time_formatted(), LOG_HEADER_BUFFER_SIZE, LOG_INFO, log_json_write(), log_mmap_is_active(), log_mmap_write(), LOG_MSG_BUFFER_SIZE, LOG_TIMESTAMP_BUFFER_SIZE, options_terminal_settings, session_log_buffer_append(), shutdown_is_requested(), terminal_choose_log_fd(), and terminal_should_color_output().

◆ log_plain_stderr_msg()

void log_plain_stderr_msg ( const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Plain logging to stderr with newline.

Parameters
fmtFormat string (printf-style)
...Format arguments

Writes to both log file and stderr without timestamps or log levels, with trailing newline.

Definition at line 1843 of file log/log.c.

1843 {
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}

References args, and shutdown_is_requested().

◆ log_plain_stderr_nonewline_msg()

void log_plain_stderr_nonewline_msg ( const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Plain logging to stderr without trailing newline.

Parameters
fmtFormat string (printf-style)
...Format arguments

Writes to both log file and stderr without timestamps, log levels, or trailing newline. Useful for interactive prompts where the user's response should be on the same line.

Definition at line 1857 of file log/log.c.

1857 {
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}

References args, and shutdown_is_requested().

◆ log_plain_stdout_msg()

void log_plain_stdout_msg ( const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Plain logging to stdout with newline.

Parameters
fmtFormat string (printf-style)
...Format arguments

Writes to both log file and stdout without timestamps or log levels, with trailing newline. Used for informational output like device listings.

Definition at line 1938 of file log/log.c.

1938 {
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}

References args, and shutdown_is_requested().

◆ log_recolor_plain_entry()

size_t log_recolor_plain_entry ( const char * plain_line,
char * colored_buf,
size_t buf_size )

#include <include/ascii-chat/log/log.h>

Recolor a plain (non-colored) log line with proper ANSI codes.

Converts a plain text log line (from log file) into a colored version matching the format used for terminal output. Applies colors to:

  • Timestamp and level based on log level
  • Thread ID in grey
  • File path in cyan
  • Line number in magenta
  • Function name in orange/DEV color
  • Message body colorized appropriately

Expected plain format (debug mode): [TIMESTAMP] [LEVEL] [tid:THREAD_ID] FILE:LINE in FUNC(): MESSAGE

Parameters
plain_linePlain text log line (from log file)
colored_bufOutput buffer for colored version (must be large enough)
buf_sizeSize of colored_buf
Returns
Length of colored string, 0 on error or invalid format
Note
Uses static buffer internally, result is reused across calls

Parses plain log format: [TIMESTAMP] [LEVEL] [tid:THREAD_ID] FILE:LINE in FUNC(): MESSAGE And recolors it with appropriate ANSI codes matching the colored format.

Definition at line 2303 of file log/log.c.

2304 {
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}
#define LOG_LEVEL_BUFFER_SIZE
Definition log/log.c:6
#define LOG_FILE_PATH_BUFFER_SIZE
Definition log/log.c:7
#define LOG_PARSE_TIMESTAMP_BUFFER_SIZE
Definition log/log.c:5
#define LOG_FUNC_NAME_BUFFER_SIZE
Definition log/log.c:8
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:44

References colorize_log_message(), colors, file_path, LOG_COLOR_RESET, LOG_DEBUG, log_debug, LOG_ERROR, LOG_FATAL, LOG_FILE_PATH_BUFFER_SIZE, LOG_FUNC_NAME_BUFFER_SIZE, log_get_color_array(), LOG_INFO, LOG_LEVEL_BUFFER_SIZE, LOG_MSG_BUFFER_SIZE, LOG_PARSE_TIMESTAMP_BUFFER_SIZE, LOG_WARN, and SAFE_STRNCPY.

◆ log_redetect_terminal_capabilities()

void log_redetect_terminal_capabilities ( void )

#include <include/ascii-chat/log/log.h>

Re-detect terminal capabilities after logging is initialized.

Useful when terminal capabilities change or need to be refreshed.

Definition at line 2078 of file log/log.c.

2078 {
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}
void detect_terminal_capabilities_into(const terminal_options_t *options, terminal_capabilities_t *out)

References detect_terminal_capabilities_into(), log_debug, and options_terminal_settings.

Referenced by log_init(), and log_system_init().

◆ log_set_color_scheme()

void log_set_color_scheme ( const color_scheme_t * scheme)

#include <include/ascii-chat/log/log.h>

Set the color scheme for logging output.

Parameters
schemeColor scheme to apply (must not be NULL)

Updates the compiled ANSI color codes based on the new color scheme. Must be called after colors_init() to have an effect.

Definition at line 2179 of file log/log.c.

2179 {
2180 colorscheme_apply(scheme);
2181}
void colorscheme_apply(const color_scheme_t *scheme)

References colorscheme_apply().

◆ log_set_flush_delay()

void log_set_flush_delay ( unsigned int delay_ms)

#include <include/ascii-chat/log/log.h>

Set the delay between flushing buffered log entries.

When terminal output is re-enabled after an interactive prompt, buffered log entries are flushed to the terminal. This setting adds a delay between each entry for a visual animation effect.

Parameters
delay_msDelay in milliseconds between each log entry (0 = no delay)

Definition at line 921 of file log/log.c.

921 {
922 atomic_store_u64(&g_log.flush_delay_ms, delay_ms);
923}

References atomic_store_u64().

◆ log_set_force_stderr()

void log_set_force_stderr ( bool enabled)

#include <include/ascii-chat/log/log.h>

Force all terminal log output to stderr.

Parameters
enabledtrue to force all logs to stderr, false for normal routing

When enabled, all log messages (including INFO, DEBUG, DEV) go to stderr instead of the default behavior where INFO/DEBUG/DEV go to stdout and WARN/ERROR/FATAL go to stderr. This is used by the client to keep stdout clean for ASCII art output.

Definition at line 840 of file log/log.c.

840 {
841 atomic_store_u64(&g_log.force_stderr, enabled);
842}

References atomic_store_u64(), and enabled.

Referenced by session_display_create().

◆ log_set_format()

asciichat_error_t log_set_format ( const char * format_str,
bool console_only )

#include <include/ascii-chat/log/log.h>

Set a custom log format string.

Parameters
format_strFormat string with specifiers like time(H:M:S), level, message, etc. Pass NULL to use default format. Empty string "" also uses default.
console_onlyIf true, apply format only to console output (file logs use default)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 859 of file log/log.c.

859 {
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}
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 OPT_LOG_TEMPLATE_DEFAULT
Default log template string (selected based on build mode).
Definition options.h:386
Compiled log format ready for use in log_template_apply().
Definition log/format.h:82

References ASCIICHAT_OK, atomic_store_u64(), ERROR_INVALID_STATE, log_error, log_template_free(), log_template_parse(), OPT_LOG_TEMPLATE_DEFAULT, and SET_ERRNO.

Referenced by browser_client_init(), client_init(), log_init(), and mirror_init().

◆ log_set_level()

void log_set_level ( log_level_t level)

#include <include/ascii-chat/log/log.h>

Set the minimum log level.

Parameters
levelMinimum log level to output

Definition at line 809 of file log/log.c.

809 {
810 atomic_store_u64(&g_log.level, (int)level);
811 atomic_store_bool(&g_log.level_manually_set, true);
812}

References atomic_store_bool(), and atomic_store_u64().

Referenced by initial_options().

◆ log_set_session_log_buffer()

void log_set_session_log_buffer ( session_log_buffer_t * buf)

#include <include/ascii-chat/log/log.h>

Register a session log buffer with the logger.

Once registered, all log messages are appended to the buffer in addition to being written to files/terminal. Used by splash and status screens.

Parameters
bufBuffer instance to register (can be NULL to unregister)

Definition at line 2263 of file log/log.c.

2263 {
2264 atomic_ptr_store(&g_log.session_log_buffer, (void *)buf);
2265}

References atomic_ptr_store().

Referenced by splash_log_init(), ui_mdns_log_init(), ui_session_capture_logs(), and ui_status_log_init().

◆ log_set_terminal_output()

void log_set_terminal_output ( bool enabled)

#include <include/ascii-chat/log/log.h>

Control stderr output to terminal.

Parameters
enabledtrue to enable terminal output, false to disable

Definition at line 818 of file log/log.c.

818 {
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}
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
bool quiet
Quiet mode (suppress logs).
Definition options.h:1140

References atomic_store_u64(), enabled, options_get(), and options_state::quiet.

Referenced by asciichat_shared_init(), discovery_main(), display_disable_logging_for_first_frame(), mcp_server_main(), mirror_main(), options_init(), and session_render_loop().

◆ log_shutdown_begin()

void log_shutdown_begin ( void )

#include <include/ascii-chat/log/log.h>

Begin shutdown phase - disable console logging but keep file logging.

Call this before logging shutdown messages. Disables console output but keeps file logging so messages are recorded for debugging.

Useful when you want final messages (like "no servers found") to go to the log file only, not to stdout where it might interfere with output.

Definition at line 2219 of file log/log.c.

2219 {
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}

References atomic_load_u64(), and atomic_store_bool().

Referenced by asciichat_shared_destroy().

◆ log_shutdown_end()

void log_shutdown_end ( void )

#include <include/ascii-chat/log/log.h>

End shutdown phase - restore previous logging settings.

Call after shutdown messages have been logged to restore console output.

Definition at line 2231 of file log/log.c.

2231 {
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}

References atomic_store_u64().

Referenced by asciichat_shared_destroy().

◆ log_system_destroy()

void log_system_destroy ( void )

#include <include/ascii-chat/log/log.h>

Shutdown the logging system internal state (system-level cleanup).

Restores terminal state and clears registered session log buffer. Must be called once at program shutdown AFTER log_destroy(). Safe to call multiple times (idempotent).

Clears registered session log buffer. Color cleanup is handled separately in asciichat_shared_destroy() after memory reporting. Must be called once at program shutdown AFTER log_destroy(). Safe to call multiple times (idempotent).

Definition at line 801 of file log/log.c.

801 {
802 // Unregister session log buffer if registered
806 g_history = NULL;
807}
void log_clear_session_log_buffer(void)
Unregister the session log buffer.
Definition log/log.c:2272
void log_search_destroy(void)
Clean up interactive grep subsystem.
Definition search.c:210
void session_log_buffer_destroy(session_log_buffer_t *buf)
Cleanup session log buffer instance.

References log_clear_session_log_buffer(), log_search_destroy(), and session_log_buffer_destroy().

Referenced by asciichat_shared_destroy().

◆ log_system_init()

void log_system_init ( void )

#include <include/ascii-chat/log/log.h>

Initialize the logging system internal state (system-level init).

Initializes g_log struct, detects terminal capabilities, and compiles colors. Must be called once at program startup BEFORE log_init(). Safe to call multiple times (idempotent).

Definition at line 784 of file log/log.c.

784 {
785
786 // Detect terminal capabilities if not already done
788
789 // Initialize color scheme based on terminal capabilities
791}
void log_init_colors(void)
Initialize logging color system with current terminal capabilities.
Definition log/log.c:2172

References log_init_colors(), and log_redetect_terminal_capabilities().

Referenced by asciichat_shared_init().

◆ log_template_apply()

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 )

#include <include/ascii-chat/log/format.h>

Apply format to a log entry and write result to buffer.

Parameters
formatCompiled format (from log_template_parse)
bufOutput buffer
buf_sizeOutput buffer size
levelLog level
timestampPre-formatted timestamp string
fileSource file name (or NULL)
lineSource line number (or 0)
funcFunction name (or NULL)
tidThread ID
messageLog message text
use_colorsIf true, apply ANSI color codes
time_nanosecondsRaw wall-clock time in nanoseconds (for microseconds and nanoseconds)
Returns
Number of characters written (excluding null terminator), or -1 on error

Renders the compiled format using provided log entry values. Evaluates each specifier and writes results to output buffer.

Example:

log_template_t *fmt = log_template_parse("[%time(%H:%M:%S)] [%level]
%microseconds %message", false); char output[512]; uint64_t now =
time_get_realtime_ns(); int len = log_template_apply(fmt, output,
sizeof(output), LOG_INFO, "14:30:45", "test.c", 42, "main", 1234, "Test
message", false, now);
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

Definition at line 516 of file log/format.c.

520 {
521 /* Check all critical pointers - format could be freed by another thread
522 * (TOCTOU race) */
523 if (!format || !buf || buf_size == 0) {
524 return -1;
525 }
526
527 int total_written = 0;
528 char *p = buf;
529 size_t remaining = buf_size - 1; /* Reserve space for null terminator */
530
531 (void)timestamp; /* May be used in future; for now, LOG_FORMAT_TIME uses
532 custom formatting */
533
534 /* Safety check: verify format->specs is valid before dereferencing
535 * This protects against use-after-free if format is freed by another thread
536 * (TOCTOU race). Between our initial NULL check and here, the main thread may
537 * have freed this memory. */
538 if (!format || !format->specs || format->spec_count == 0) {
539 return -1;
540 }
541
542 for (size_t i = 0; i < format->spec_count; i++) {
543 /* Re-check specs pointer in loop to catch use-after-free during iteration
544 */
545 if (!format->specs || i >= format->spec_count) {
546 break; /* Format was freed, stop processing */
547 }
548 const log_format_spec_t *spec = &format->specs[i];
549
550 /* Additional safety check: if spec is null or invalid, stop processing */
551 if (!spec) {
552 break;
553 }
554
555 int written = 0;
556
557 switch (spec->type) {
559 written = safe_snprintf(p, remaining + 1, "%s",
560 spec->literal ? spec->literal : "");
561 break;
562
563 case LOG_FORMAT_TIME:
564 /* Format time using custom time formatter */
565 if (spec->literal) {
566 written = time_format_now(spec->literal, p, remaining + 1);
567 if (written <= 0) {
568 log_debug("time_format_now failed for format: %s", spec->literal);
569 written = 0;
570 }
571 }
572 break;
573
574 case LOG_FORMAT_LEVEL:
575 /* Log level as string (DEV, DEBUG, INFO, WARN, ERROR, FATAL) */
576 written = safe_snprintf(p, remaining + 1, "%s", get_level_string(level));
577 break;
578
580 /* Log level padded to exactly 5 characters (prevents truncation to
581 * [DEBU]/[ERRO]) */
582 written =
583 safe_snprintf(p, remaining + 1, "%s", get_level_string_padded(level));
584 break;
585
586 case LOG_FORMAT_FILE:
587 if (file) {
588 written = safe_snprintf(p, remaining + 1, "%s", file);
589 }
590 break;
591
593 if (file) {
594 const char *rel_file =
595 extract_project_relative_path(file, ASCIICHAT_OWNED_SOURCE_DIRS);
596 written = safe_snprintf(p, remaining + 1, "%s", rel_file);
597 }
598 break;
599
600 case LOG_FORMAT_LINE:
601 if (line > 0) {
602 written = safe_snprintf(p, remaining + 1, "%d", line);
603 }
604 break;
605
606 case LOG_FORMAT_FUNC:
607 if (func) {
608 written = safe_snprintf(p, remaining + 1, "%s", func);
609 }
610 break;
611
612 case LOG_FORMAT_TID:
613 written =
614 safe_snprintf(p, remaining + 1, "%llu", (unsigned long long)tid);
615 break;
616
617 case LOG_FORMAT_TNAME: {
618 // Registry thread keys use the same numeric identity as log records.
619 uintptr_t key = (uintptr_t)tid;
620 named_metadata_t metadata;
621 if (named_metadata_copy(key, &metadata)) {
622 written = safe_snprintf(p, remaining + 1, "%s", metadata.name);
623 } else {
624 written =
625 safe_snprintf(p, remaining + 1, "%llu", (unsigned long long)tid);
626 }
627 break;
628 }
629
631 /* Extract microseconds from nanoseconds (ns_value % 1_000_000_000 / 1000)
632 */
633 long nanoseconds = (long)(time_nanoseconds % NS_PER_SEC_INT);
634 long microseconds = nanoseconds / 1000;
635 if (microseconds < 0)
636 microseconds = 0;
637 if (microseconds > 999999)
638 microseconds = 999999;
639 written = safe_snprintf(p, remaining + 1, "%06ld", microseconds);
640 break;
641 }
642
644 /* Extract nanoseconds component (ns_value % 1_000_000_000) */
645 long nanoseconds = (long)(time_nanoseconds % NS_PER_SEC_INT);
646 if (nanoseconds < 0)
647 nanoseconds = 0;
648 if (nanoseconds > 999999999)
649 nanoseconds = 999999999;
650 written = safe_snprintf(p, remaining + 1, "%09ld", nanoseconds);
651 break;
652 }
653
655 /* strftime format code (like %H, %M, %S, %A, %B, etc.)
656 * Let strftime handle all the parsing and validation */
657 if (spec->literal &&
659 /* Construct format string with % prefix on stack */
660 char format_str[LOG_FORMAT_FORMAT_BUFFER_SIZE]; /* 1 (%) + 64 (literal)
661 + 1 (null) */
662 format_str[0] = '%';
663 memcpy(format_str + 1, spec->literal, spec->literal_len);
664 format_str[spec->literal_len + 1] = '\0';
665 written = time_format_now(format_str, p, remaining + 1);
666 if (written <= 0) {
667 log_debug("time_format_now failed for format code: %s", format_str);
668 written = 0;
669 }
670 }
671 break;
672 }
673
675 if (message) {
676 /* Format hex addresses as named object descriptions (type/name format)
677 */
678 const char *formatted_msg = log_named_format_or_original(message);
679 written = safe_snprintf(p, remaining + 1, "%s", formatted_msg);
680 }
681 break;
682
684 /* Apply colorize_log_message() for number/unit/hex highlighting, then
685 * format named objects */
686 if (message) {
687 const char *formatted_msg = log_named_format_or_original(message);
688 const char *colorized_msg =
689 colorize_log_message_with_color(formatted_msg, use_colors);
690 written = safe_snprintf(p, remaining + 1, "%s", colorized_msg);
691 }
692 break;
693 }
694
696 /* Color code for the log level (placeholder for future color support) */
697 (void)use_colors; /* Suppress unused parameter warning */
698 written = 0;
699 break;
700
701 case LOG_FORMAT_COLOR: {
702 /* Parse and apply %color(LEVEL, content)
703 * literal stores "LEVEL,content" where LEVEL is the color level name (or
704 * "*" for current level) and content is a format string to render and
705 * colorize */
706 if (!spec->literal || spec->literal_len == 0) {
707 written = 0;
708 break;
709 }
710
711 /* Find the comma separating LEVEL and content */
712 const char *comma_pos = strchr(spec->literal, ',');
713 if (!comma_pos) {
714 /* Invalid format - no comma found */
715 log_debug("%%color format missing comma in: %s", spec->literal);
716 written = 0;
717 break;
718 }
719
720 /* Extract level name (before comma) */
721 size_t level_len = comma_pos - spec->literal;
722 char level_name[LOG_FORMAT_LEVEL_NAME_BUFFER_SIZE];
723 if (level_len >= sizeof(level_name)) {
724 /* Level name too long */
725 written = 0;
726 break;
727 }
728 memcpy(level_name, spec->literal, level_len);
729 level_name[level_len] = '\0';
730
731 /* Parse level name to log_color_t (pass current level for "*" support) */
732 log_color_t color = parse_color_level(level_name, level);
733
734 /* Extract content (after comma), skip leading whitespace */
735 const char *content_start = comma_pos + 1;
736 while (*content_start == ' ' || *content_start == '\t') {
737 content_start++;
738 }
739
740 /* Render content recursively */
741 char content_buf[LOG_FORMAT_CONTENT_BUFFER_SIZE];
742 int content_len = render_format_content(
743 content_start, content_buf, sizeof(content_buf), level, timestamp,
744 file, line, func, tid, message, use_colors, time_nanoseconds);
745
746 if (content_len < 0 || content_len >= (int)sizeof(content_buf)) {
747 written = 0;
748 break;
749 }
750
751 // The caller already selected colors. Respect that policy for both file
752 // and session logs instead of asking the console again for every field.
753 const char *start = log_level_color_for_output(color, use_colors);
754 const char *reset =
756 written = safe_snprintf(p, remaining + 1, "%s%s%s", start ? start : "",
757 content_buf, reset ? reset : "");
758 break;
759 }
760
762 /* Platform-aware newline */
763#ifdef _WIN32
764 written = safe_snprintf(p, remaining + 1, "\r\n");
765#else
766 written = safe_snprintf(p, remaining + 1, "\n");
767#endif
768 break;
769
770 default:
771 break;
772 }
773
774 if (written < 0) {
775 /* snprintf error */
776 return -1;
777 }
778
779 if ((size_t)written > remaining) {
780 /* Buffer overflow prevention */
781 log_debug("buffer overflow prevented");
782 return -1;
783 }
784
785 p += written;
786 remaining -= written;
787 total_written += written;
788 }
789
790 *p = '\0';
791 return total_written;
792}
log_color_t
Definition color.h:6
const char * colorize_log_message_with_color(const char *message, bool enabled)
Definition colorize.c:568
const char * log_level_color_for_output(log_color_t color, bool enabled)
Definition log/log.c:2149
int time_format_now(const char *format_str, char *buf, size_t buf_size)
Format current time using strftime format string.
Definition time.c:778
const char * extract_project_relative_path(const char *file, const char *const *owned_dirs)
Extract a path relative to the source root embedded by CMake.
Definition path.c:137
#define LOG_FORMAT_FORMAT_BUFFER_SIZE
Definition log/format.c:9
#define LOG_FORMAT_CONTENT_BUFFER_SIZE
Definition log/format.c:11
#define LOG_FORMAT_STRFTIME_LITERAL_MAX
Definition log/format.c:8
#define LOG_FORMAT_LEVEL_NAME_BUFFER_SIZE
Definition log/format.c:10
@ LOG_FORMAT_LEVEL
Definition log/format.h:31
@ LOG_FORMAT_COLOR
Definition log/format.h:42
@ LOG_FORMAT_NEWLINE
Definition log/format.h:52
@ LOG_FORMAT_FILE_RELATIVE
Definition log/format.h:34
@ LOG_FORMAT_LINE
Definition log/format.h:36
@ LOG_FORMAT_MICROSECONDS
Definition log/format.h:46
@ LOG_FORMAT_TID
Definition log/format.h:38
@ LOG_FORMAT_COLORED_MESSAGE
Definition log/format.h:44
@ LOG_FORMAT_LITERAL
Definition log/format.h:29
@ LOG_FORMAT_COLORLOG_LEVEL
Definition log/format.h:41
@ LOG_FORMAT_MESSAGE
Definition log/format.h:40
@ LOG_FORMAT_TIME
Definition log/format.h:30
@ LOG_FORMAT_LEVEL_ALIGNED
Definition log/format.h:32
@ LOG_FORMAT_FUNC
Definition log/format.h:37
@ LOG_FORMAT_NANOSECONDS
Definition log/format.h:48
@ LOG_FORMAT_TNAME
Definition log/format.h:39
@ LOG_FORMAT_STRFTIME_CODE
Definition log/format.h:50
@ LOG_FORMAT_FILE
Definition log/format.h:33
const char * get_level_string_padded(log_level_t level)
Get padded level string for consistent alignment.
Definition log/log.c:203
One literal or conversion token in a compiled log format.
Definition log/format.h:67
log_template_type_t type
Definition log/format.h:68
log_format_spec_t * specs
Definition log/format.h:83
size_t spec_count
Definition log/format.h:84

References colorize_log_message_with_color(), extract_project_relative_path(), get_level_string_padded(), log_format_spec_t::literal, log_format_spec_t::literal_len, LOG_COLOR_RESET, log_debug, LOG_FORMAT_COLOR, LOG_FORMAT_COLORED_MESSAGE, LOG_FORMAT_COLORLOG_LEVEL, LOG_FORMAT_CONTENT_BUFFER_SIZE, LOG_FORMAT_FILE, LOG_FORMAT_FILE_RELATIVE, LOG_FORMAT_FORMAT_BUFFER_SIZE, LOG_FORMAT_FUNC, LOG_FORMAT_LEVEL, LOG_FORMAT_LEVEL_ALIGNED, LOG_FORMAT_LEVEL_NAME_BUFFER_SIZE, LOG_FORMAT_LINE, LOG_FORMAT_LITERAL, LOG_FORMAT_MESSAGE, LOG_FORMAT_MICROSECONDS, LOG_FORMAT_NANOSECONDS, LOG_FORMAT_NEWLINE, LOG_FORMAT_STRFTIME_CODE, LOG_FORMAT_STRFTIME_LITERAL_MAX, LOG_FORMAT_TID, LOG_FORMAT_TIME, LOG_FORMAT_TNAME, log_level_color_for_output(), log_named_format_or_original(), named_metadata_t::name, named_metadata_copy(), NS_PER_SEC_INT, log_template_t::spec_count, log_template_t::specs, time_format_now(), and log_format_spec_t::type.

◆ log_template_free()

void log_template_free ( log_template_t * format)

#include <include/ascii-chat/log/format.h>

Free compiled format structure.

Parameters
formatPointer to format to free (safe to call with NULL)

Definition at line 341 of file log/format.c.

341 {
342 if (!format) {
343 SET_ERRNO(ERROR_INVALID_PARAM, "null format");
344 return;
345 }
346
347 if (format->specs) {
348 for (size_t i = 0; i < format->spec_count; i++) {
349 if (format->specs[i].literal) {
350 free(format->specs[i].literal);
351 format->specs[i].literal = NULL;
352 }
353 }
354 free(format->specs);
355 format->specs = NULL;
356 }
357
358 if (format->original) {
359 free(format->original);
360 format->original = NULL;
361 }
362
363 free(format);
364 format = NULL;
365}
char * original
Definition log/format.h:85

References ERROR_INVALID_PARAM, log_format_spec_t::literal, log_template_t::original, SET_ERRNO, log_template_t::spec_count, and log_template_t::specs.

Referenced by log_destroy(), and log_set_format().

◆ log_template_parse()

log_template_t * log_template_parse ( const char * format_str,
bool console_only )

#include <include/ascii-chat/log/format.h>

Parse a format string into compiled format structure.

Parameters
format_strFormat string (e.g., "[%time(%H:%M:%S)] [%level_aligned] %message")
console_onlyIf true, format applies only to console (not file)
Returns
Compiled format, or NULL on parse error

Parses format string and compiles it into efficient specifier array. Format string must be valid UTF-8. Returns NULL on:

  • Invalid UTF-8 in format string
  • Invalid format specifiers
  • Malformed time(format) syntax
  • Memory allocation failure
Note
Errors are logged with details about what failed

Definition at line 337 of file log/format.c.

337 {
338 return parse_format_string(format_str, console_only);
339}

Referenced by log_set_format().

◆ log_terminal_colored_msg_impl()

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 )

#include <include/ascii-chat/log/log.h>

Write semantically colored terminal text without persistent logging.

Parameters
levelSeverity used for terminal routing and JSON console output
colored_messageMessage containing semantic ANSI colors
plain_messageEquivalent message without ANSI colors

This is the terminal-only counterpart to log_colored_msg().

Definition at line 1677 of file log/log.c.

1680 {
1681 log_colored_msg_internal(level, file, line, func, colored_message,
1682 plain_message, false);
1683}

◆ log_terminal_msg()

void log_terminal_msg ( log_level_t level,
const char * file,
int line,
const char * func,
const char * fmt,
... )

#include <include/ascii-chat/log/log.h>

Log a message to terminal only (no file output).

Parameters
levelLog level (LOG_DEV, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL)
fileSource file name (or NULL to omit)
lineSource line number (or 0 to omit)
funcFunction name (or NULL to omit)
fmtFormat string (printf-style)
...Format arguments

Logs to terminal only, skipping file/mmap output. WARN/ERROR/FATAL go to stderr, other levels go to stdout (unless force_stderr is enabled).

Definition at line 1546 of file log/log.c.

1547 {
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}

References args, atomic_load_u64(), get_current_time_formatted(), and LOG_TIMESTAMP_BUFFER_SIZE.

◆ log_truncate_if_large()

void log_truncate_if_large ( void )

#include <include/ascii-chat/log/log.h>

Manually truncate large log files.

Checks if the log file exceeds MAX_LOG_SIZE and truncates it if necessary.

Definition at line 925 of file log/log.c.

925 {
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}
#define MAX_LOG_SIZE
Maximum log file size in bytes (3MB) before rotation.
Definition log/log.h:70

References atomic_load_int(), atomic_store_u64(), and MAX_LOG_SIZE.

◆ log_unlock_terminal()

void log_unlock_terminal ( bool previous_state)

#include <include/ascii-chat/log/log.h>

Release terminal lock and flush buffered messages.

Call this after interactive prompts complete to release the terminal lock. Buffered log messages from other threads will be flushed to terminal.

Parameters
previous_stateThe value returned by log_lock_terminal()

Definition at line 914 of file log/log.c.

914 {
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}

References atomic_store_u64().