POCO日誌庫使用示例
阿新 • • 發佈:2019-01-28
Poco是一個開源的C++庫,各方面功能比較全面,包括日誌\多執行緒\檔案系統\定時器\網路\配之檔案等,同時使用也十分簡單.
本文對其中的日誌模組進行了簡單的試用.
1.使用示例
Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> pConf = new Poco::Util::PropertyFileConfiguration("log_conf.properties"); Poco::Util::LoggingConfigurator log_configurator; log_configurator.configure(pConf); _log = &Poco::Logger::root(); _log->debug("debug"); _log->information("information"); _log->warning("warning"); _log->error("error"); _log->fatal("fatal");
在程式碼中使用十分簡單。
2.Log的配置檔案
以上程式碼通過載入配置檔案log_conf.propeties對其進行配置。
Poco本身對log配置檔案似乎沒有詳細說明,不過可以通過閱讀原始碼總結出來。
下面是我整理的一個配置檔案,其內容如下:
logging.formatters.f1.class = PatternFormatter logging.formatters.f1.pattern = [%p %Y-%m-%d %H:%M:%S %i %P %I]\n%U:%u\n%t logging.channels.c1.class = ConsoleChannel logging.channels.c1.formatter = f1 logging.channels.c2.class = FileChannel logging.channels.c2.formatter = f1 logging.channels.c2.path = ./sample.log logging.channels.c2.rotation = daily logging.channels.splitter.class = SplitterChannel logging.channels.splitter.channels = c1,c2 logging.loggers.root.channel = splitter logging.loggers.root.level = debug
可以看到配置檔案分為5個部分:
1) 前兩行 定義了一個formatter,就是定義了日誌的輸出格式:
[%p %Y-%m-%d %H:%M:%S %i %P %I]\n%U:%u\n%t
2)接下來兩行定義了一個輸出通道,輸出的Console控制檯,輸出格式就是上面定一個的f1
3) 接下來4行定義了另一個輸出通道,輸出到檔案,檔名是sample.log, 輸出格式也是f1,。
logging.channels.c2.rotation = daily
rotation=daily意思是每天寫一個檔案。當然還可以設定檔案大小,儲存天數等。
具體可看最後的參考文章。
4) 接下來兩行,把2) 3)定義的兩個輸出通道組合起來,成為一個splitter的通道。
5)最後兩行,將splitter通道設定為日誌root的通道,這樣輸出的日誌會通過splitter分別送到console 和 file。
最後定義日誌輸出級別為debug。
更多可以參考: