造實用個性的Log輸出巨集

2021-08-07 14:22:00 字數 2902 閱讀 8233

我們在除錯嵌入式程式的時候,用ide+偵錯程式是最直接的方式,但是很多時候我們還需要用串列埠輸出來列印一些debug的資訊,來幫助我們除錯。串列埠除錯最簡單的方式的話,最簡單就是用printf來列印。但是只有printf不能很好的控制輸出的資訊,或者讓**變得很臃腫。我們就用巨集來封裝下printf,讓它更好的使用,更加便利。這裡給大家分享乙個我在別人基礎再改進的log巨集**。

#ifndef __log_h__

#define __log_h__

#include "bsp.h"

#define log_error (0x01)

#define log_warning (0x02)

#define log_notice (0x04)

#define log_info (0x08)

#define log_debug (0x10)

/* this log macro must be set befor compiler, output error, warning, info debug lever */

#define debug_level_switch (0xff)

#define logheard "llfeng"

#define debugprintf(fmt, arg...) uart_printf(huart1,(const char*)fmt, ##arg)

#if ((debug_level_switch & log_error) == log_error)

#define log_err(fmt, arg...) debugprintf("%s:[%s@%s,%d]"fmt"\r\n",logheard,__function__,__file__,__line__, ##arg)

#else

#define log_err(fmt, arg...)

#endif

#if ((debug_level_switch & log_warning) == log_warning)

#define log_warn(fmt, arg...) debugprintf("%s:"fmt"\r\n",logheard, ##arg)

#else

#define log_warn(fmt, arg...)

#endif

#if ((debug_level_switch & log_notice) == log_notice)

#define log_notice(fmt, arg...) debugprintf("%s:"fmt"\r\n",logheard, ##arg)

#else

#define log_notice(fmt, arg...)

#endif

#if ((debug_level_switch & log_info) == log_info)

#define log_info(fmt, arg...) debugprintf("%s:"fmt"\r\n",logheard, ##arg)

#else

#define log_info(fmt, arg...)

#endif

#if ((debug_level_switch & log_debug) == log_debug)

#define log_debug(fmt, arg...) debugprintf("%s:[%s@%s,%d]"fmt"\r\n",logheard,__function__,__file__,__line__, ##arg)

#else

#define log_debug(fmt, arg...)

#endif

#if ((debug_level_switch & log_debug) == log_debug)

#define log_data(data,size) hal_uart_transmit(&huart1,data,size,100)

#else

#define log_data(data, size)

#endif

#endif

**裡一開始就是定義的log輸出的等級log_error,log_warning,log_notice,log_info,log_debug,每個等級控制printf輸出不同的內容,我們d 通過改變debug_level_switch的巨集定義就能近山log的等級輸出,比如定義debug_level_switch 為log_error,那最終程式只會列印log_debug這個log巨集函式的輸出,其它等級就不會有輸出。這裡的log_debug還加入了列印函式名,檔名跟行數等資訊,我們只要像printf那樣呼叫log_debug就會加上列印我們前面說的內容來幫助我們更好的定位問題,這裡還加上個性化輸出的字串logheard,我們改變logheard的定義就讓log輸出變的很有個性。如下圖用log_info和log_debug列印的輸出。

在實際寫**的過程,我們只根據實際情況去呼叫不同的log函式去列印我們所要的資訊。除錯完畢後我們再定義debug_level_switch除錯等級來控制log不同等級的輸出或者壓根就不輸出。比如我**定義debug_level_switch 為0xff,就是開啟了所有的輸出,等我們除錯完了,不需要看其它沒必須的資訊,我們不用去刪除**,只需要再改輸出等級debug_level_switch 為log_error|log_debug ,這樣log就會列印對應的這兩條巨集函式的輸出。這樣就既便利又有修改。

如何輸出xapian debug的log

xapian內部關係呼叫比較複雜,想要了解內部的函式呼叫關係比較有難度,好在內部使用logcall ctor等輸出了很多log,如何列印這些log呢?命令如下 cd xapian core 1.4.5 xapin source downloaded install mkdir build cd bu...

使用巨集的可變引數來構造列印Log巨集

define test debug ifdef test debug define dbg err fmt,args printf fmt,file function line args endif void printf erro int a,int b else void main 測試結果 c...

分享自己寫的乙個簡化版LOG輸出巨集

extern int verbose define dbg xlog 4,dbg va args define info xlog 3,inf va args define wrn xlog 2,wrn va args define err xlog 1,err va args define out...