Files
433_STM32/Core/Src/debug_log.c

149 lines
3.5 KiB
C

/**
******************************************************************************
* @file debug_log.c
* @brief 增强型调试日志系统实现
* @author Application Layer
* @version 1.0
******************************************************************************
* @attention
* 本模块实现增强型调试日志系统
* 设计依据:多通信接口统一指令处理系统开发计划 第3.4节
*
* 日志格式:[LEVEL][MODULE] message
* 示例:[INFO][CMD] Command received: RL
******************************************************************************
*/
#include "debug_log.h"
#include "uart2_print.h"
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#define MAX_MODULES 16
#define MODULE_NAME_LEN 16
typedef struct {
char name[MODULE_NAME_LEN];
bool enabled;
} module_config_t;
static log_level_t g_current_level = LOG_LEVEL_DEBUG;
static module_config_t g_modules[MAX_MODULES];
static bool g_modules_initialized = false;
static const char *const g_level_str[] = {
[LOG_LEVEL_DEBUG] = "DEBUG",
[LOG_LEVEL_INFO] = "INFO ",
[LOG_LEVEL_WARN] = "WARN ",
[LOG_LEVEL_ERROR] = "ERROR",
};
static void init_modules(void)
{
if (g_modules_initialized) {
return;
}
for (int i = 0; i < MAX_MODULES; i++) {
g_modules[i].name[0] = '\0';
g_modules[i].enabled = false;
}
g_modules_initialized = true;
}
static bool is_module_enabled(const char *module)
{
if (module == NULL || module[0] == '\0') {
return true;
}
init_modules();
for (int i = 0; i < MAX_MODULES; i++) {
if (g_modules[i].name[0] != '\0' &&
strncmp(g_modules[i].name, module, MODULE_NAME_LEN - 1) == 0) {
return g_modules[i].enabled;
}
}
return true;
}
void DebugLog_Init(void)
{
g_current_level = LOG_LEVEL_DEBUG;
init_modules();
UART2_Print_String("[LOG] Debug log system initialized\r\n");
}
void DebugLog_SetLevel(log_level_t level)
{
g_current_level = level;
}
log_level_t DebugLog_GetLevel(void)
{
return g_current_level;
}
void DebugLog_EnableModule(const char *module, bool enable)
{
if (module == NULL || module[0] == '\0') {
return;
}
init_modules();
for (int i = 0; i < MAX_MODULES; i++) {
if (g_modules[i].name[0] == '\0') {
strncpy(g_modules[i].name, module, MODULE_NAME_LEN - 1);
g_modules[i].name[MODULE_NAME_LEN - 1] = '\0';
g_modules[i].enabled = enable;
return;
}
if (strncmp(g_modules[i].name, module, MODULE_NAME_LEN - 1) == 0) {
g_modules[i].enabled = enable;
return;
}
}
}
void DebugLog_Output(log_level_t level, const char *module, const char *fmt, ...)
{
if (level < g_current_level) {
return;
}
if (!is_module_enabled(module)) {
return;
}
char buffer[256];
int len = 0;
len += snprintf(buffer + len, sizeof(buffer) - len, "[%s][%s] ",
g_level_str[level], module ? module : "MAIN");
if (len < (int)sizeof(buffer) - 1) {
va_list args;
va_start(args, fmt);
len += vsnprintf(buffer + len, sizeof(buffer) - len, fmt, args);
va_end(args);
}
if (len > 0 && len < (int)sizeof(buffer)) {
buffer[len++] = '\r';
if (len < (int)sizeof(buffer)) {
buffer[len++] = '\n';
}
}
if (len > 0) {
UART2_Print_Send((const uint8_t *)buffer, len);
}
}