#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/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/support/date_time.hpp>
bool g_nInitLog = false;
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;
void InitLog()
{
//输出到文件
auto pSink = logging::add_file_log
(
keywords::open_mode = std::ios::app, //重启程序不删除日志
keywords::file_name = "log/videosnapshow_%N.log",
keywords::rotation_size=10*1024*1024, //超过此大小自动建立新文件
// keywords::time_based_rotation=sinks::file::rotation_at_time_point(0,0,0), //每隔指定时间重建新文件
// This makes the sink to write log records that look like this:
keywords::format =
(
expr::stream
<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d, %H:%M:%S.%f")
<< " " << expr::attr< boost::log::aux::thread::id >("ThreadID")
<< ": <" << logging::trivial::severity
<< "> " << expr::smessage
)
);
pSink->locked_backend()->auto_flush(true);//使日志实时更新
//pSink->imbue(std::locale("zh_CN.UTF-8")); // 本地化
logging::add_console_log();
logging::add_common_attributes();
}
使用的时候
void InitLog();
extern bool g_nInitLog;
- 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";
设置过滤也简单。在initlog中设置
logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);