彩色的log信息

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

/*
 *本章博客是對linux log信息的研究
 *
 */



# define PRT_OBJECT(x) ((struct prt_object *)(x))

/** Message types */
enum msg_item_type
{
    MSG_INFO=0, /**< Important information */
    MSG_ERR,    /**< Error */
    MSG_WARN,   /**< Warning */
    MSG_DBG,    /**< Debug */
};


#define COL(x,y)  "\033[" #x ";" #y "m"
#define RED     COL(31,1)
#define GREEN   COL(32,1)
#define YELLOW  COL(0,33)
#define WHITE   COL(0,1)
#define GRAY    "\033[0m"

static const char msg_type[4][9] = { " info", " error", " warning", " debug" };
static const char msg_color[4][8] = { WHITE, RED, YELLOW, GRAY };


/*取可變參數的過程其實就是堆棧中,使用指針,遍歷堆棧段中的參數列表,
 *從低地址到高地址一個一個地把參數內容讀出來的過程.
 */
void prt_log(int type,const char *module, const char *format, ...)
{
    va_list args;
    char tmp[200];

    va_start(args, format);
    vsprintf(tmp, format, args);
    va_end(args);


    fprintf(stderr, "%s %s: %s %s", module, msg_type[type],msg_color[type],tmp);
    fputs(GRAY"\n", stderr);
}
#define MODULE_STRING "log.c"

#define msg_dbg(...) \
    prt_log(MSG_DBG,  MODULE_STRING, __VA_ARGS__)
#define msg_warn(...) \
    prt_log(MSG_WARN, MODULE_STRING, __VA_ARGS__)
#define msg_err(...) \
    prt_log(MSG_ERR,  MODULE_STRING, __VA_ARGS__)
#define msg_info(...) \
    prt_log(MSG_INFO, MODULE_STRING, __VA_ARGS__)


int main(void)
{
    msg_err("hal read err!");
    msg_info("hal read");
    msg_dbg("hal reading......");
    msg_warn("hal have not read");

    return 0;
}


效果如下圖:

發佈了41 篇原創文章 · 獲贊 36 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章