项目中使用到了Boost日志库,今日来探索一下:
#include"boost/log/trivial.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/date_time/posix_time/posix_time.hpp"
#include"boost/log/utility/setup/console.hpp"
#include"boost/format.hpp"//using namespace MyWorld;namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace pt = boost::posix_time;void init_boost_logging(const string& dir) {if (!boost::filesystem::exists(dir)){boost::filesystem::create_directories(dir);}// 初始化日志库 logging::add_common_attributes();// 将日志消息写入文件的 sinkauto sink = logging::add_file_log(keywords::file_name = dir + "/%Y%m%d.log", // 使用 %N 生成唯一的文件名 keywords::rotation_size = 10 * 1024 * 1024, // 文件大小达到 10 MB 时旋转 keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), // 每天旋转 keywords::format = "[%TimeStamp% %ThreadID%]: %Message%"// 日志格式 );//控制台sinkauto console_sink = logging::add_console_log(cout,keywords::format = "[%TimeStamp%]: %Message%" // 日志格式 );// 如果不写这个 它不会实时的把日志写下去, 而是等待缓冲区满了,或者程序正常退出时写下,这样做的好处是减少IO操作.提高效率, 不过我这里不需要它. 因为我的程序可能会异常退出.sink->locked_backend()->auto_flush(true);//使日志实时更新// 激活 trivial loggerlogging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
}
使用时先初始化系统
int main() {//boost::filesystem::path source_file_path(__FILE__);//boost::filesystem::path source_dir = source_file_path.parent_path();cout << boost::filesystem::current_path() << endl;init_boost_logging("../Log/"); // 初始化日志系统
}
其中,日志等级主要有以下几种
BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
BOOST_LOG_TRIVIAL(info) << "An informational severity message";
BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
BOOST_LOG_TRIVIAL(error) << "An error severity message";
BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";
先到这吧,下次再嗑