#include "debug.h" #include #include /** * @file debug.c * @brief Debug and logging system implementation * * Provides a configurable logging system with timestamp formatting, * level-based filtering, and optional file:line information. */ // Global debug level (default: no debug output) debug_level_t g_debug_level = DEBUG_LEVEL_NONE; /** * @brief Initialize the debug system with a specific level * @param level Debug level (0-5, clamped to valid range) */ void debug_init(int level) { if (level < 0) level = 0; if (level > 5) level = 5; g_debug_level = (debug_level_t)level; } /** * @brief Core logging function * @param level Debug level for this message * @param file Source file name (__FILE__) * @param line Source line number (__LINE__) * @param format printf-style format string * @param ... Variable arguments for format string */ void debug_log(debug_level_t level, const char* file, int line, const char* format, ...) { // Get timestamp time_t now = time(NULL); struct tm* tm_info = localtime(&now); char timestamp[32]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_info); // Get level string const char* level_str = "UNKNOWN"; switch (level) { case DEBUG_LEVEL_ERROR: level_str = "ERROR"; break; case DEBUG_LEVEL_WARN: level_str = "WARN "; break; case DEBUG_LEVEL_INFO: level_str = "INFO "; break; case DEBUG_LEVEL_DEBUG: level_str = "DEBUG"; break; case DEBUG_LEVEL_TRACE: level_str = "TRACE"; break; default: break; } // Print prefix with timestamp and level printf("[%s] [%s] ", timestamp, level_str); // Print source location when debug level is TRACE (5) or higher if (file && g_debug_level >= DEBUG_LEVEL_TRACE) { // Extract just the filename (not full path) const char* filename = strrchr(file, '/'); filename = filename ? filename + 1 : file; printf("[%s:%d] ", filename, line); } // Print message va_list args; va_start(args, format); vprintf(format, args); va_end(args); printf("\n"); fflush(stdout); }