STM32 LOG重定向及日志框架

转载自 https://blog.csdn.net/qq_41680042/article/details/120844574

1. 在Core目录下新建一个Dev目录,添加log.h和log.c
在这里插入图片描述
2. 将log.h和log.c添加到项目编译列表
选择Project -> Properties
在这里插入图片描述
3. log.h

#ifndef __LOG_H_
#define __LOG_H_

#include <stdarg.h>

#define OPEN_LOG 1
#define LOG_LEVEL LOG_DEBUG

typedef enum{
	LOG_DEBUG = 0,
	LOG_INFO,
	LOG_WARN,
	LOG_ERROR,
} E_LOG_LEVEL;

void EM_LOG(const int level, const char* fun, const int line, const char* fmt, ...);
#define EMLOG(level, fmt, ...) EM_LOG(level, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__)


#endif

4. log.c

#include "log.h"
#include <stdio.h>

char* EM_LOG_LEVEL_GET(const int level)
{
	if (level == LOG_DEBUG) {
		return "DEBUG";
	} else if (level == LOG_INFO) {
		return "INFO";
	} else if (level == LOG_WARN) {
		return "WARN";
	} else if (level == LOG_ERROR) {
		return "ERROR";
	}

	return "UNKNOW";
}

void EM_LOG(const int level, const char* fun, const int line, const char* fmt, ...)
{
#ifdef OPEN_LOG

	va_list arg;
	va_start(arg, fmt);
	char buf[50] = {0};
	vsnprintf(buf, sizeof(buf), fmt, arg);
	va_end(arg);

	if (level >= LOG_LEVEL) {
		printf("[%-5s] [%s %4d] %s 
", EM_LOG_LEVEL_GET(level), fun, line, buf);
	}

#endif
}
  1. 在usart.c添加重定向,可以使用printf打印
/* USER CODE BEGIN 0 */
#if defined(__GNUC__)
int _write(int fd, char * ptr, int len)
{
  HAL_UART_Transmit(&huart2, (uint8_t *) ptr, len, HAL_MAX_DELAY);
  return len;
}
#endif

/* USER CODE END 0 */
  1. main.c
/* USER CODE BEGIN Includes */
#include "log.h"
/* USER CODE END Includes */

在while里可以用EMLOG打印

  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	//HAL_UART_Transmit(&huart4, "Hello world
", 14, 0xffff);
	EMLOG(LOG_DEBUG,"while start");
	HAL_Delay(500);
  }