boost log庫使用 十二 架構研究和主要使用總結

來源:互聯網
上載者:User

前面做了不少boost log的例子,現在來總結一下,最新代碼在我的開源項目:https://gitlab.com/mystudy/boost_log

下面是boost log庫的架構圖:


 下面總結一下和這個架構相關的知識:

1. 如何獲得Logging core

#include <boost/log/core.hpp>...boost::shared_ptr<logging::core> core = logging::core::get();

2. 如何安裝Sink對象

一個core可以安裝多個Sink,下面的代碼假定已經有了兩個Sink對象,將其安裝到core中

  core->add_sink(sink1);...  core->add_sink(sink2);

3. 如何建立一個Sink對象

需要先建立一個backend對象,然後在建立sink對象的時候,將backend對象傳遞給它。

  typedef sinks::synchronous_sink<sinks::text_file_backend> TextSink;  // init sink1  boost::shared_ptr<sinks::text_file_backend> backend1 = boost::make_shared<sinks::text_file_backend>(  keywords::file_name = "sign_%Y-%m-%d_%H-%M-%S.%N.log",  keywords::rotation_size = 10 * 1024 * 1024,  keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),  keywords::min_free_space = 30 * 1024 * 1024);  boost::shared_ptr<TextSink> sink1(new TextSink(backend1));

4. 如何建立一個backend對象指定frontend類型

前面的代碼中已經示範,注意backend的類型需要制定一個frontend類型作為其模板類。因此,當建立一個backend對象的時候,已經確定了frontend。

這個frontend模板可以用synchronous_sink類,也可以用asynchronous_sink, 後者不會阻塞調用程式,會額外的建立線程去處理log,不過會慢點,記憶體消耗大點。一般都推薦先用後者。


用keywords構造參數

這裡看到一個概念:keywords. 在boost/log/keywords/目錄下27個hpp檔案:

auto_flush.hpp  facility.hpp   ident.hpp       log_source.hpp      open_mode.hpp        rotation_size.hpp  target.hppchannel.hpp     file_name.hpp  ip_version.hpp  max_size.hpp        order.hpp            scan_method.hpp    time_based_rotation.hppdelimiter.hpp   filter.hpp     iteration.hpp   message_file.hpp    ordering_window.hpp  severity.hpp       use_impl.hppdepth.hpp       format.hpp     log_name.hpp    min_free_space.hpp  registration.hpp     start_thread.hpp

keywords是boost庫的基本概念,設計到一個宏BOOST_PARAMETER_KEYWORD,定義在boost/parameter/keywords.hpp檔案中, 主要作用就是在指定的namespace中建立一個singleton的對象。所以上面的幾行keywords:: 代碼就是給keywords namespace下面的幾個singleton對象file_name, rotation, time_based_rotation和min_free_space賦值。關鍵是要看看下面這個類的建構函式如何使用這些keywords.
sinks::text_file_backend

參考文檔:

http://boost-log.sourceforge.net/libs/log/doc/html/log/detailed/sink_backends.html

http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/boost/log/sinks/text_file_backend.html

注意,text_file_backend的建構函式文法上支援變參,但是語義上只支援有限的keywords:

    template< typename ArgsT >    void construct(ArgsT const& args)    {        construct(            filesystem::path(args[keywords::file_name | filesystem::path()]),            args[keywords::open_mode | (std::ios_base::trunc | std::ios_base::out)],            args[keywords::rotation_size | (std::numeric_limits< uintmax_t >::max)()],            args[keywords::time_based_rotation | time_based_rotation_predicate()],            args[keywords::auto_flush | false]);    }

文檔中也的確如此描述。但是在text_file_backend.hpp檔案中發現還是有關於min_free_space的代碼:

namespace aux {    //! Creates and returns a file collector with the specified parameters    BOOST_LOG_API shared_ptr< collector > make_collector(        filesystem::path const& target_dir,        uintmax_t max_size,        uintmax_t min_free_space    );    template< typename ArgsT >    inline shared_ptr< collector > make_collector(ArgsT const& args)    {        return aux::make_collector(            filesystem::path(args[keywords::target]),            args[keywords::max_size | (std::numeric_limits< uintmax_t >::max)()],            args[keywords::min_free_space | static_cast< uintmax_t >(0)]);    }} // namespace aux

所以估計還是可以使用target, max_size 和 min_free_space這些keywords. 以後試了就知道了。

5. 如何在sink中指定格式

下面到了指定日誌格式,這個需要在sink中指定,比如:

  sink1->set_formatter (expr::format("[%1%]<%2%>(%3%): %4%")% expr::format_date_time< boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")% expr::attr<sign_severity_level>("Severity")% expr::attr<attrs::current_thread_id::value_type>("ThreadID")% expr::smessage);


Boost::Format風格這裡的關鍵是理解expr::format. 文檔在這裡:http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/log/detailed/expressions.html#log.detailed.expressions.formatters

我使用的是Boost::Format風格。


attributes

參考文檔:http://boost-log.sourceforge.net/libs/log/doc/html/log/detailed/attributes.html

根據設計,日誌記錄是由attributes組成的,所以列印內容必須以attribute的方式傳給sink對象。

  sink1->set_formatter (expr::format("[%1%]<%2%>(%3%)(%4%): %5%")% expr::attr<unsigned int>("LineID")% expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")% expr::attr<sign_severity_level>("Severity")% expr::attr<attrs::current_thread_id::value_type >("ThreadID")% expr::smessage);

不要忘記添加commont attributes

  logging::add_common_attributes();
該函數定義在boost/log/utility/setup/common_attributes.hpp檔案中, 裡面添加了4個屬性:

inline void add_common_attributes(){    shared_ptr< core > pCore = core::get();    pCore->add_global_attribute(        aux::default_attribute_names::line_id(),        attributes::counter< unsigned int >(1));    pCore->add_global_attribute(        aux::default_attribute_names::timestamp(),        attributes::local_clock());    pCore->add_global_attribute(        aux::default_attribute_names::process_id(),        attributes::current_process_id());#if !defined(BOOST_LOG_NO_THREADS)    pCore->add_global_attribute(        aux::default_attribute_names::thread_id(),        attributes::current_thread_id());#endif}


6. Name scope

Name scope也是前面格式的一種解決方案,但是由於它比較複雜,所以單獨描述。

stack element

首先瞭解一下結構體named_scope_entry, 文檔在:http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/boost/log/attributes/named_scope_entry.html

named_scope_entry包含了scope_name, file_name和 line(原始碼行號), 每個stack element 就是一個name_scope_entry對象。

scope stack

scope有很多種,具體參考文檔:http://en.wikipedia.org/wiki/Scope_(computer_science)

最常見的是函數,此時scope stack就是函數棧。

boost log可以列印scope stack的資訊到日誌中

named_scope屬性

named scope屬性可以添加到全域屬性中,這是線程相關的。添加屬性代碼為:

logging::core::get()->add_global_attribute("Scope", attrs::named_scope());
參考文檔:http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/boost/log/attributes/named_scope.html

設定格式

文檔:http://www.boost.org/doc/libs/1_54_0/libs/log/doc/html/log/detailed/expressions.html#log.detailed.expressions.formatters.named_scope

下面是個簡單的例子:

首先設定格式的時候添加一種格式:

% expr::format_named_scope("Scopes", boost::log::keywords::format = "%n (%f : %l)")

然後添加屬性:

  core->add_global_attribute("Scopes", attrs::named_scope());

之後調用代碼中添加一個Bar和Foo函數,此處參考官方文檔:http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/log/detailed/attributes.html#log.detailed.attributes.named_scope

void Bar() {  int x = 0;}void Foo(int n) {  src::severity_logger_mt<sign_severity_level>& lg = my_logger::get();  // Mark the scope of the function foo  BOOST_LOG_FUNCTION();  switch (n)    {    case 0:      {// Mark the current scopeBOOST_LOG_NAMED_SCOPE("case 0");BOOST_LOG(lg) << "Some log record";Bar(); // call some function      }      break;    case 1:      {// Mark the current scopeBOOST_LOG_NAMED_SCOPE("case 1");BOOST_LOG(lg) << "Some log record";Bar(); // call some function      }      break;    default:      {// Mark the current scopeBOOST_LOG_NAMED_SCOPE("default");BOOST_LOG(lg) << "Some log record";Bar(); // call some function      }      break;    }}

最後在main.cc函數中調用:

  Foo(1);

執行結果:

[8]<2014-03-01 23:49:19>(0)(0x00007f21bf00e740)(void Foo(int) (./main.cc : 11)->case 1 (./main.cc : 27)): Some log record


注意,上面的代碼中用到兩個宏:BOOST_LOG_NAMED_SCOPE和BOOST_LOG_FUNCTION。其實就是一個宏,後面的宏只是前面宏的簡化版本,可以自動將當前函數作為scope name。定義在/boost/log/attributes/named_scope.hpp檔案

/*! * Macro for function scope markup. The scope name is constructed with help of compiler and contains current function name. * The scope name is pushed to the end of the current thread scope list. * * Not all compilers have support for this macro. The exact form of the scope name may vary from one compiler to another. */#define BOOST_LOG_FUNCTION() BOOST_LOG_NAMED_SCOPE(BOOST_CURRENT_FUNCTION)
而BOOST_LOG_NAMED_SCOPE宏也在這個檔案中定義:

/*! * Macro for scope markup. The specified scope name is pushed to the end of the current thread scope list. */#define BOOST_LOG_NAMED_SCOPE(name)\    BOOST_LOG_NAMED_SCOPE_INTERNAL(BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_named_scope_sentry_), name, __FILE__, __LINE__)

#define BOOST_LOG_NAMED_SCOPE_INTERNAL(var, name, file, line)\    BOOST_LOG_UNUSED_VARIABLE(::boost::log::attributes::named_scope::sentry, var, (name, file, line));
檔案/boost/log/utility/unused_variable.hpp中用了GCC編譯器指令__attribute__

#if defined(__GNUC__)//! The macro suppresses compiler warnings for \c var being unused#define BOOST_LOG_UNUSED_VARIABLE(type, var, initializer) __attribute__((unused)) type var initializer#else


所以在FOO函數中使用BOOST_LOG_FUNCTION的時候,也就是寫下了這行代碼:

__attribute__((unused)) ::boost::log::attributes::named_scope::sentry _boost_log_named_scope_sentry_18 (__PRETTY_FUNCTION__, "./main.cc", 18);;

所以可以看到,這裡的程式碼數是固定的18, 因此如果在記錄日誌時想要顯示代碼的行數,寫入日誌時必須至少兩行宏:

BOOST_LOG_FUNCTION 和 BOOST_LOG_SEV宏。




7. filter

filter可以過濾記錄層級,還可以更多,下面是個例子:

  sink1->set_filter(expr::attr<sign_severity_level>("Severity") >= trace);

進階filter的文檔在這裡:

http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/log/tutorial/advanced_filtering.html






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.