You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
spdlog/include/c11log/sinks/async_sink.h

110 lines
2.8 KiB
C

12 years ago
#pragma once
12 years ago
#include <thread>
#include <chrono>
#include <atomic>
12 years ago
#include "base_sink.h"
#include "../logger.h"
#include "../details/blocking_queue.h"
12 years ago
namespace c11log {
namespace sinks {
12 years ago
class async_sink : public base_sink
{
12 years ago
public:
12 years ago
using size_type = c11log::details::blocking_queue<std::string>::size_type;
explicit async_sink(const size_type max_queue_size);
~async_sink();
void add_sink(logger::sink_ptr_t sink);
12 years ago
void remove_sink(logger::sink_ptr_t sink_ptr);
//Wait to remaining items (if any) in the queue to be written and shutdown
void shutdown(const std::chrono::seconds& timeout);
12 years ago
12 years ago
protected:
void sink_it_(const std::string& msg) override;
void thread_loop_();
12 years ago
private:
c11log::logger::sinks_vector_t sinks_;
12 years ago
std::atomic<bool> active_ { true };
c11log::details::blocking_queue<std::string> q_;
12 years ago
std::thread back_thread_;
//Clear all remaining messages(if any), stop the back_thread_ and join it
void shutdown_();
};
}
}
12 years ago
12 years ago
///////////////////////////////////////////////////////////////////////////////
// async_sink class implementation
///////////////////////////////////////////////////////////////////////////////
12 years ago
12 years ago
inline c11log::sinks::async_sink::async_sink(const std::size_t max_queue_size)
:q_(max_queue_size),
12 years ago
back_thread_(&async_sink::thread_loop_, this)
{}
12 years ago
inline c11log::sinks::async_sink::~async_sink()
{
shutdown_();
}
inline void c11log::sinks::async_sink::sink_it_(const std::string& msg)
{
q_.push(msg);
}
12 years ago
inline void c11log::sinks::async_sink::thread_loop_()
12 years ago
{
std::string msg;
auto pop_timeout = std::chrono::seconds(1);
12 years ago
while (active_)
{
if (q_.pop(msg, pop_timeout))
{
for (auto &sink : sinks_)
{
sink->log(msg, static_cast<level::level_enum>(_level.load()));
12 years ago
if (!active_)
return;
}
}
}
12 years ago
}
inline void c11log::sinks::async_sink::add_sink(logger::sink_ptr_t sink)
{
sinks_.push_back(sink);
}
inline void c11log::sinks::async_sink::remove_sink(logger::sink_ptr_t sink_ptr)
{
sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink_ptr), sinks_.end());
12 years ago
}
12 years ago
inline void c11log::sinks::async_sink::shutdown(const std::chrono::seconds &timeout)
{
auto until = std::chrono::system_clock::now() + timeout;
while (q_.size() > 0 && std::chrono::system_clock::now() < until)
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
shutdown_();
}
inline void c11log::sinks::async_sink::shutdown_()
12 years ago
{
12 years ago
if(active_)
{
active_ = false;
if (back_thread_.joinable())
back_thread_.join();
}
}
12 years ago