統一日誌的記錄格式,用宏調用printf

來源:互聯網
上載者:User

軟體一般都要輸出日誌,方便排錯和跟蹤運行情況。所有記錄檔的格式還是要美化點好,以免在尋找關鍵資訊時費時費力。
所以日誌函數要支援:
    1、時間和地點。即什麼時候哪個地方報的資訊。
    2、為了方便調用,必須支援多重格式的輸出,所以使用printf的格式是最好的。

下面就是我寫的一個日誌函數:

#include <stdarg.h>#include <stdio.h>#include <time.h>#define LOG_FILE"./a.log"#define LOG_DEFAULT( fmt, ... )log_out( LOG_FILE, __FILE__, __LINE__, fmt, ##__VA_ARGS__)#define LOG_TOXFILE( flog, fmt, ... )log_out( flog, __FILE__, __LINE__, fmt, ##__VA_ARGS__)int log_out(char* flog, char *file, int line, char* fmt, ...){    va_list arg;charpre[128], tmp[1024];longclock;    structtm *c_ptr;FILE*fp;time( &clock );    c_ptr = localtime(&clock);sprintf( pre, "[%04d%02d%02d%02d%02d%02d_%s.%d]",     c_ptr->tm_year+1900, c_ptr->tm_mon+1, c_ptr->tm_mday,     c_ptr->tm_hour, c_ptr->tm_min, c_ptr->tm_sec, file, line );    va_start(arg, fmt);vsprintf(tmp, fmt, arg);    va_end (arg);//log to stdoutif( !flog ){printf( "%-32.32s  %s", pre, tmp );return 0;}//log to fileif( !(fp = fopen( flog, "at" ) ) )return -1;fprintf( fp, "%-32.32s  %s", pre, tmp );fclose( fp );    return 0;}

 

調用方法:

LOG_DEFAULT     把日誌輸出到預設的記錄檔

LOG_TOXFILE      把日誌輸出大指定的記錄檔,如果參數是0,則日誌列印到標準輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.