我试图使用Boost创建Log Macro,而我的宏是非线程安全的。这是我的示例代码:
初始化
inline boost::shared_ptr<cilog_async_sink_t> init_async_logger(const std::string& app_name,
const std::string& target = "./log", int64_t rotation_size = 1024 * 1024 * 1024,
bool auto_flush = true) {
namespace expr = boost::log::expressions;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;
boost::log::add_common_attributes();
boost::shared_ptr<cilog_backend> backend(
new cilog_backend(boost::filesystem::path(target), app_name, rotation_size, auto_flush));
boost::shared_ptr<cilog_async_sink_t> sink(new cilog_async_sink_t(backend));
sink->set_formatter(
expr::stream << expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "[%Y-%m-%d_%H:%M:%S.%f] ")
<< "[" << expr::attr<severity_level, severity_tag>("Severity") << "] "
<< "[" << expr::attr<attrs::current_process_id::value_type>("ProcessID") << "] "
<< "[" << expr::attr<attrs::current_thread_id::value_type>("ThreadID") << "] "
<< expr::smessage);
boost::log::core::get()->add_sink(sink);
cilog_async_sink_t::locked_backend_ptr p = sink->locked_backend();
return sink;
}
格式
class cilog_backend: public boost::log::sinks::basic_formatted_sink_backend<char,
boost::log::sinks::synchronized_feeding> {
private:
bool auto_flush_;
boost::filesystem::ofstream file_;
boost::filesystem::path target_path_;
boost::filesystem::path file_path_;
std::string file_name_suffix_;
uintmax_t rotation_size_;
uintmax_t characters_written_;
boost::gregorian::date current_date_;
public:
explicit cilog_backend(boost::filesystem::path const& target_path,
std::string const& file_name_suffix, uintmax_t rotation_size,
bool auto_flush) :
auto_flush_(auto_flush), target_path_(target_path), file_name_suffix_(file_name_suffix),
rotation_size_(rotation_size), characters_written_(0),
current_date_(boost::gregorian::day_clock::local_day()) {
}
void consume(boost::log::record_view const& /*rec*/,
string_type const& formatted_message) {
if (current_date_ != boost::gregorian::day_clock::local_day())
rotate_file();
if (!file_.is_open()) {
file_path_ = generate_filepath();
boost::filesystem::create_directories(file_path_.parent_path());
file_.open(file_path_, std::ofstream::out | std::ofstream::app);
if (!file_.is_open()) return; // failed to open file
characters_written_ = static_cast<std::streamoff>(file_.tellp());
}
file_.write(formatted_message.data(), static_cast<std::streamsize>(formatted_message.size()));
file_.put('\n');
characters_written_ += formatted_message.size() + 1;
if (auto_flush_)
file_.flush();
if ((file_.is_open() && (characters_written_ >= rotation_size_)) || (!file_.good()))
rotate_file();
}
};
我在Boost上发现了一些线程安全的代码:
cilog_async_sink_t::locked_backend_ptr p = sink->locked_backend();
在我的初学者但没有工作。
有人可以为我建议吗?