Boost Log 基本使用方法


Boost Log 基本使用方法
flyfish 2014-11-5



依據boost提供的代碼演示樣例,學習Boost Log 的基本使用方法


前提
boost版本號boost_1_56_0
演示樣例代碼目錄 boost_1_56_0\libs\log\example\basic_usage


使用的單詞非常形象。整個過程就像流水一樣
如果要輸出的日志比作水

  水                     (Hello, World!)
  水槽                 (sink)
  流向哪里        (console,file)
  從哪里取        (source)

  水的等級        (severity level)
  過濾輸出        (filter)
  格式輸出        (format)
  各部分連接者(core)


演示樣例

#include <iostream>


#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>


#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>


#include <boost/log/attributes/timer.hpp>
#include <boost/log/attributes/named_scope.hpp>


#include <boost/log/sources/logger.hpp>


#include <boost/log/support/date_time.hpp>


namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;


using boost::shared_ptr;


// Here we define our application severity levels.
enum severity_level
{
    normal,
    notification,
    warning,
    error,
    critical
};


// The formatting logic for the severity level
template< typename CharT, typename TraitsT >
inline std::basic_ostream< CharT, TraitsT >& operator<< (
    std::basic_ostream< CharT, TraitsT >& strm, severity_level lvl)
{
    static const char* const str[] =
    {
        "normal",
        "notification",
        "warning",
        "error",
        "critical"
    };
    if (static_cast< std::size_t >(lvl) < (sizeof(str) / sizeof(*str)))
        strm << str[lvl];
    else
        strm << static_cast< int >(lvl);
    return strm;
}


int _tmain(int argc, char* argv[])
{
    // This is a simple tutorial/example of Boost.Log usage


    // The first thing we have to do to get using the library is
    // to set up the logging sinks - i.e. where the logs will be written to.
    logging::add_console_log(std::clog, keywords::format = "%TimeStamp%: %Message%");


    // One can also use lambda expressions to setup filters and formatters
    logging::add_file_log
    (
        "sample.log",
        keywords::filter = expr::attr< severity_level >("Severity") >= warning,
        keywords::format = expr::stream
            << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d, %H:%M:%S.%f")
            << " [" << expr::format_date_time< attrs::timer::value_type >("Uptime", "%O:%M:%S")
            << "] [" << expr::format_named_scope("Scope", keywords::format = "%n (%f:%l)")
            << "] <" << expr::attr< severity_level >("Severity")
            << "> " << expr::message
/*
        keywords::format = expr::format("%1% [%2%] [%3%] <%4%> %5%")
            % expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d, %H:%M:%S.%f")
            % expr::format_date_time< attrs::timer::value_type >("Uptime", "%O:%M:%S")
            % expr::format_named_scope("Scope", keywords::format = "%n (%f:%l)")
            % expr::attr< severity_level >("Severity")
            % expr::message
*/
    );


    // Also let's add some commonly used attributes, like timestamp and record counter.
    logging::add_common_attributes();
    logging::core::get()->add_thread_attribute("Scope", attrs::named_scope());


    BOOST_LOG_FUNCTION();


    // Now our logs will be written both to the console and to the file.
    // Let's do a quick test and output something. We have to create a logger for this.
    src::logger lg;


    // And output...
    BOOST_LOG(lg) << "Hello, World!";


    // Now, let's try logging with severity
    src::severity_logger< severity_level > slg;


    // Let's pretend we also want to profile our code, so add a special timer attribute.
    slg.add_attribute("Uptime", attrs::timer());


    BOOST_LOG_SEV(slg, normal) << "A normal severity message, will not pass to the file";
    BOOST_LOG_SEV(slg, warning) << "A warning severity message, will pass to the file";
    BOOST_LOG_SEV(slg, error) << "An error severity message, will pass to the file";


    return 0;
}

從上到下依次分析

一  日志嚴重性等級
enum severity_level
{
    normal,
    notification,
    warning,
    error,
    critical
};


二  日志等級輸出
template< typename CharT, typename TraitsT >
inline std::basic_ostream< CharT, TraitsT >& operator<< (
    std::basic_ostream< CharT, TraitsT >& strm, severity_level lvl)
{
...
}


輸出已經定義的等級描寫敘述,日志等級的數值與字符串一一相應,假設在enum severity_level假設未定義則輸出數值。




std::basic_ostream對全部的內建類型,進行了重載,輸入各種內置類型
重載operator <<,使得自定的用戶定義類型severity_level 集成到IOStream library中
IOStream library的類都帶有兩個參數,當中一個是字符的類型,一個是與字符類型相關的信息
就像std::cout一樣輸出各種類型,編譯器自己會進行正確的推導輸出的什么類型。

static const char* const 表示數組里面的指針不可改變  並且指針所指向的字符串也不可改變

三 日志輸出位置

logging::add_console_log
日志輸出到控制台


 logging::add_file_log
日志輸出到文件


四 定義源。像std::cout一樣輸出

src::logger lg;

BOOST_LOG(lg) << "Hello, World!";

五 結果

文件的輸出

2014-11-05, 19:46:19.513082 [00:00:00] 
[int __cdecl wmain(int,char *[]) (文件路徑:代碼行)] <warning> A warning severity message, will pass to the file


2014-11-05, 19:46:19.518082 [00:00:00] 
[int __cdecl wmain(int,char *[]) (文件路徑:代碼行)] <error> An error severity message, will pass to the file


控制台的輸出

2014-Nov-05 19:51:30.261856: Hello, World!
2014-Nov-05 19:51:30.268856: A normal severity message, will not pass to the file
2014-Nov-05 19:51:30.275856: A warning severity message, will pass to the file
2014-Nov-05 19:51:30.284857: An error severity message, will pass to the file


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM