, , , Boost.Log.
. , , . , . , , , stdout .
severity_logger, . "" "source", "logger" , .
( "" ). . .
+
+
| +
|
+
| source |
+
|
| +
+
+
, , , .., . .
:
#include <string>
#include <fstream>
#include <boost/log/sinks.hpp>
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
namespace bl = boost::log;
:
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string);
, , - . (, "[%TimeStamp%] [%Message%]"), , . "Tag".
using logger_type = bl::sources::severity_logger<bl::trivial::severity_level>;
static logger_type g_logger;
const std::string g_format = "[%TimeStamp%] (%LineID%) [%Severity%] [%Tag%]: %Message%";
, , (g_logger). logger . . YMMV.
logger:
class logger
{
public:
logger(std::string file)
: tag_(file)
{
using backend_type = bl::sinks::text_file_backend;
using sink_type = bl::sinks::synchronous_sink<backend_type>;
namespace kw = bl::keywords;
auto backend = boost::make_shared<backend_type>(
kw::file_name = file + "_%N.log",
kw::rotation_size = 10 * 1024 * 1024,
kw::time_based_rotation = bl::sinks::file::rotation_at_time_point(0, 0, 0),
kw::auto_flush = true);
auto sink = boost::make_shared<sink_type>(backend);
sink->set_formatter(bl::parse_formatter(g_format));
sink->set_filter(tag_attr == tag_);
bl::core::get()->add_sink(sink);
}
void log(const std::string& s)
{
BOOST_LOG_SCOPED_THREAD_TAG("Tag", tag_);
BOOST_LOG_SEV(g_logger, bl::trivial::info) << s;
}
private:
const std::string tag_;
};
, , . , .
text_file_backend , . , add_file_log(), . , ( , ..).
:
sink->set_filter(tag_attr == tag_);
tag_attr . Boost.Log: , . , tag_attr == tag_. , -, , , . log() "Tag".
main():
int main()
{
bl::register_simple_formatter_factory<bl::trivial::severity_level, char>("Severity");
boost::log::add_common_attributes();
bl::add_console_log(std::clog, bl::keywords::format=g_format);
logger lg1("1");
logger lg2("2");
lg1.log("a");
lg1.log("b");
lg1.log("c");
lg2.log("d");
lg2.log("e");
lg2.log("f");
}
, logger, . "a", "b" "c" "1_0.txt" "d", "e" "f" "2_0.txt". .
+--------------+
| lg1.log("a") |
+--------------+
|
v
+-------------------------+
| Entry: |
| Timestamp: 1472660811 |
| Message: "a" |
| LineID: 1 |
| Severity: info |
| Tag: "1" |
+-------------------------+
|
v +----------------------+
+------+ | console sink |
| core | -----+----> | file: stdout | --> written
+------+ | | filter: none |
| +----------------------+
|
| +----------------------+
| | file sink |
+----> | file: "1_0.txt" | --> written
| | filter: tag == "1" |
| +----------------------+
|
| +----------------------+
| | file sink |
+----> | file: "2_0.txt" | --> discarded
| filter: tag == "2" |
+----------------------+