1. 程式人生 > >boost.log從編譯到使用

boost.log從編譯到使用

最近新開專案,要用到log,雖然現在的log庫不少。但是要為C++專案增加庫還是首選boost。

首先從boost.org上下載最新的boost,編譯:

bjam --with-log link=shared runtime-link=shared

單編log庫,編譯為動態庫,本來runtime-link想選為static, 靜態依賴到C/C++庫,發現不行,乾脆直接全部使用動態庫。

編譯完成,發現生成了stage\lib目錄下不僅有log庫,還包含了其他一些庫,這些都是log在執行中需要依賴的。將這些lib和dll全部copy到需要用到的可執行檔案目錄下。

需要注意的幾點:

現在一般的應用都是由多模組組成,而且每一個模組都需要輸出log,所以將log庫編譯為動態庫是最好的選擇

依賴log庫的模組(lib/dll/exe), 需要加入預編譯巨集BOOST_ALL_DYN_LINK,否則在連結時會找不到對應的boost lib檔案

 

log庫的使用:

這部分都是參考別人的部落格來寫的, 具體請參看:https://www.cnblogs.com/liaocheng/p/4222885.html

#pragma once
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/attributes/timer.hpp>
#include <boost/log/support/date_time.hpp>

void InitLog(std::string dir);
#include "stdafx.h"
#include "log.h"

namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace expr = boost::log::expressions;
BOOST_LOG_ATTRIBUTE_KEYWORD(_timestamp, "TimeStamp", boost::posix_time::ptime);

void InitLog(std::string dir)
{
	boost::log::add_console_log(std::clog, keywords::format = expr::stream << expr::format_date_time(_timestamp, "[%Y-%m-%d,%H:%M:%S.%f] ")
		<< "[" << expr::attr< boost::log::trivial::severity_level >("Severity") << "] " 
		<< expr::message);
	boost::log::add_file_log(keywords::file_name = dir + "/yuer_%Y-%m-%d_%H-%M-%S.%N.log", keywords::auto_flush = true
		, keywords::rotation_size = 10 * 1024 * 1024
		, keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0)
		, keywords::format = expr::stream << expr::format_date_time(_timestamp, "[%Y-%m-%d,%H:%M:%S.%f] ") << "[" << expr::attr< boost::log::trivial::severity_level >("Severity") <<"] "<< expr::message
		, keywords::min_free_space = 3 * 1024 * 1024
	);
	boost::log::add_common_attributes();
}

logging::add_console_log是為控制檯輸出做定製化

logging::add_file_log是為檔案輸出做定製化

keyword::format是格式化輸出, rotation_size是日誌大小,超過該大小重新生成日誌檔案

InitLog只能在應用初始化時呼叫一次,之後其他地方可以呼叫BOOST_LOG_TRIVIAL進行輸出:

BOOST_LOG_TRIVIAL(trace) << __FUNCTION__ << ".";