log4cpp 日誌庫的使用

2021-10-16 17:07:24 字數 2826 閱讀 3255

平時除錯c++、c程式和記錄一些程式列印資訊時,使用的最多的就是printf,但是終端顯示有限,而且不利於統計,所以想把開源的日誌庫加入到工程中;測試對比了一些日誌庫,發現log4cpp比較適合我們的工程。

1)可以自由控制日誌在終端和日誌中的輸出,同時或只記錄在檔案;

2)有配置檔案,只需修改配置檔案即可達到功能適配;

3)日誌排版多樣化,可自己定製;

4)日誌可以分標籤或者按模組輸出;

5)控制日誌個數和大小,不用擔心日誌無限增多,導致空間不足;

在此記錄我的編譯和測試過程,方便以後其他工程可以直接使用。

測試使用的是log4cpp-1.1.3.tar.gz

交叉編譯庫配置,在pc上編譯庫,不用這麼麻煩

./configure cc=arm-linux-gnueabihf-gcc cxx=arm-linux-gnueabihf-g++  --prefix=/home/xiangang/work/test/log4cpp/log4cpp/build --host=arm

make -j8

make install

這樣在build目錄下就可以生成4個目錄

xiangang@xiangang:~/work/test/log4cpp/build$ ls

bin include lib share

xiangang@xiangang:~/work/test/log4cpp/build/lib$ ls

liblog4cpp.a liblog4cpp.la pkgconfig

其中liblog4cpp.a就是我們所需要的靜態庫,標頭檔案在include下面。

在pc上測試

cmakelists.txt

project(test)

#新增c++11支援

add_definitions(-std=c++11)

#新增標頭檔案搜尋路徑

include_directories(/usr/local/include)

#新增庫檔案搜尋路徑

link_directories(/usr/local/lib)

#用於將當前目錄下的所有原始檔的名字儲存在變數 dir_srcs 中

aux_source_directory(. dir_srcs)

add_executable(test $)

#在這裡根據名字log4cpp尋找檔案

target_link_libraries(test log4cpp pthread)

clog4util.h

#ifndef clog4util_include

#define clog4util_include

#include "log4cpp/category.hh"

#include "log4cpp/layout.hh"

#include "log4cpp/basiclayout.hh"

#include "log4cpp/priority.hh"

#include "log4cpp/propertyconfigurator.hh"

#include #include using namespace std;

#define debug(tag, ...)

#define info(tag, ...)

#endif

在同檔案中,巨集定義了debug和info,只是演示,後續我會定義更多的功能。

clog4util.cpp

#include "clog4util.h"

int init(string initfilename)

catch (log4cpp::configurefailure&f)

return 0;

}

這個init函式是為了載入配置檔案。

main.cpp

#include #include #include #include #include #include #include #include #include "clog4util.h"

int main(int argc, char *ar**)

init(ar**[1]);

int count = 0;

while(1)

debug("mytest %s %d %x", "asdfaf", 1, 0x58);

} return 0;

}

配置檔案 log4cpp.conf

#-------定義rootcategory的屬性-------

#-------定義console屬性-------

#下面這三條語句表示控制台輸出的log輸出的布局按照指定的格式;輸出格式是:[%p] %d (%c): %m%n

#下面的語句表示檔案輸出到指定的log檔案,輸出的布局按照指定的格式,輸出的格式是:[%d - %p] (%c): %m%n

#當日誌檔案到達maxfilesize大小時,將會自動滾動 1024 = 1k

#maxbackupindex指定可以產生的滾動檔案的最大數

#filename指定資訊輸出到logs/irismatch.log檔案

#patternlayout 表示可以靈活指定布局模式

編譯好後:./test log4cpp.conf 執行,即可看見log.log日誌檔案了。多次執行程式,日誌會累加,當乙個檔案大小達到1024k時,會自動備份記錄到新檔案中,備份數量達到4個時,會進行覆蓋。當然這是按我配置檔案來的。

C 日誌框架log4cpp

c 日誌框架log4cpp 使用說明詳見log4cpp官網。windows平台編譯log4cpp庫詳見連線 附件中包括x64 release的庫檔案。lib庫 dll庫 編寫log4cpp.properties配置檔案,如下文 定義rootcategory的屬性 log4cpp.rootcatego...

Cpp呼叫Log4cpp生成日誌

初始化 log4cpp patternlayout playout new log4cpp patternlayout playout setconversionpattern d p c x m n log4cpp category root log4cpp category getroot ge...

log4cpp應用速成手冊

log4cpp應用手冊 2 開啟 log4cpp 0.3.4b msvc6 msvc6.dsw 編譯log4cpp工程release版。3 將編譯後的log4cpp.lib複製到vc的lib目錄中。4 將標頭檔案的目錄log4cpp 0.3.4b include log4cpp 複製到vc的incl...