some effic++ warnings fixes

This commit is contained in:
gabime 2014-02-09 01:56:21 +02:00
parent d60e971dec
commit be78e51f8c
6 changed files with 214 additions and 210 deletions

View File

@ -10,104 +10,105 @@
#include <mutex> #include <mutex>
#include <condition_variable> #include <condition_variable>
namespace c11log { namespace c11log
{
namespace details namespace details
{ {
template<typename T> template<typename T>
class blocking_queue { class blocking_queue
{
public: public:
using queue_t = std::queue<T>; using queue_t = std::queue<T>;
using size_type = typename queue_t::size_type; using size_type = typename queue_t::size_type;
using clock = std::chrono::system_clock; using clock = std::chrono::system_clock;
explicit blocking_queue(size_type max_size) :max_size_(max_size), q_() explicit blocking_queue(size_type max_size) :
{} max_size_(max_size),
blocking_queue(const blocking_queue&) = delete; q_(),
blocking_queue& operator=(const blocking_queue&) = delete; mutex_()
~blocking_queue() = default; {}
blocking_queue(const blocking_queue&) = delete;
blocking_queue& operator=(const blocking_queue&) = delete;
~blocking_queue() = default;
size_type size() size_type size() {
{ std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock(mutex_); return q_.size();
return q_.size(); }
}
// Push copy of item into the back of the queue. // Push copy of item into the back of the queue.
// If the queue is full, block the calling thread util there is room or timeout have passed. // If the queue is full, block the calling thread util there is room or timeout have passed.
// Return: false on timeout, true on successful push. // Return: false on timeout, true on successful push.
template<typename Duration_Rep, typename Duration_Period, typename TT> template<typename Duration_Rep, typename Duration_Period, typename TT>
bool push(TT&& item, const std::chrono::duration<Duration_Rep, Duration_Period>& timeout) bool push(TT&& item, const std::chrono::duration<Duration_Rep, Duration_Period>& timeout) {
{ std::unique_lock<std::mutex> ul(mutex_);
std::unique_lock<std::mutex> ul(mutex_); if (q_.size() >= max_size_) {
if (q_.size() >= max_size_) if (!item_popped_cond_.wait_until(ul, clock::now() + timeout, [this]() {
{ return this->q_.size() < this->max_size_;
if (!item_popped_cond_.wait_until(ul, clock::now() + timeout, [this]() { return this->q_.size() < this->max_size_; })) }))
return false; return false;
} }
q_.push(std::forward<TT>(item)); q_.push(std::forward<TT>(item));
if (q_.size() <= 1) if (q_.size() <= 1) {
{ ul.unlock(); //So the notified thread will have better chance to accuire the lock immediatly..
ul.unlock(); //So the notified thread will have better chance to accuire the lock immediatly.. item_pushed_cond_.notify_one();
item_pushed_cond_.notify_one(); }
} return true;
return true; }
}
// Push copy of item into the back of the queue. // Push copy of item into the back of the queue.
// If the queue is full, block the calling thread until there is room. // If the queue is full, block the calling thread until there is room.
template<typename TT> template<typename TT>
void push(TT&& item) void push(TT&& item) {
{ while (!push(std::forward<TT>(item), one_hour));
while (!push(std::forward<TT>(item), one_hour)); }
}
// Pop a copy of the front item in the queue into the given item ref. // Pop a copy of the front item in the queue into the given item ref.
// If the queue is empty, block the calling thread util there is item to pop or timeout have passed. // If the queue is empty, block the calling thread util there is item to pop or timeout have passed.
// Return: false on timeout , true on successful pop/ // Return: false on timeout , true on successful pop/
template<class Duration_Rep, class Duration_Period> template<class Duration_Rep, class Duration_Period>
bool pop(T& item, const std::chrono::duration<Duration_Rep, Duration_Period>& timeout) bool pop(T& item, const std::chrono::duration<Duration_Rep, Duration_Period>& timeout) {
{ std::unique_lock<std::mutex> ul(mutex_);
std::unique_lock<std::mutex> ul(mutex_); if (q_.empty()) {
if (q_.empty()) if (!item_pushed_cond_.wait_until(ul, clock::now() + timeout, [this]() {
{ return !this->q_.empty();
if (!item_pushed_cond_.wait_until(ul, clock::now() + timeout, [this]() { return !this->q_.empty(); })) }))
return false; return false;
} }
item = std::move(q_.front()); item = std::move(q_.front());
q_.pop(); q_.pop();
if (q_.size() >= max_size_ - 1) if (q_.size() >= max_size_ - 1) {
{ ul.unlock(); //So the notified thread will have better chance to accuire the lock immediatly..
ul.unlock(); //So the notified thread will have better chance to accuire the lock immediatly.. item_popped_cond_.notify_one();
item_popped_cond_.notify_one(); }
} return true;
return true; }
}
// Pop a copy of the front item in the queue into the given item ref. // Pop a copy of the front item in the queue into the given item ref.
// If the queue is empty, block the calling thread util there is item to pop. // If the queue is empty, block the calling thread util there is item to pop.
void pop(T& item) void pop(T& item) {
{ while (!pop(item, one_hour));
while (!pop(item, one_hour)); }
}
// Clear the queue // Clear the queue
void clear() void clear() {
{ {
{
std::unique_lock<std::mutex> ul(mutex_); std::unique_lock<std::mutex> ul(mutex_);
queue_t().swap(q_); queue_t().swap(q_);
} }
item_popped_cond_.notify_all(); item_popped_cond_.notify_all();
} }
private: private:
size_type max_size_; size_type max_size_;
std::queue<T> q_; std::queue<T> q_;
std::mutex mutex_; std::mutex mutex_;
std::condition_variable item_pushed_cond_; std::condition_variable item_pushed_cond_;
std::condition_variable item_popped_cond_; std::condition_variable item_popped_cond_;
const std::chrono::hours one_hour{1}; const std::chrono::hours one_hour {
1
};
}; };
} }

View File

@ -53,7 +53,7 @@ public:
fast_oss():std::ostream(&_dev) {} fast_oss():std::ostream(&_dev) {}
~fast_oss() = default; ~fast_oss() = default;
fast_oss(const fast_oss& other):std::basic_ios<char>(), std::ostream(),_dev(other._dev) {} fast_oss(const fast_oss& other):std::basic_ios<char>(), std::ostream(),_dev(other._dev) {}
fast_oss operator=(const fast_oss& other) fast_oss& operator=(const fast_oss& other)
{ {
if(&other != this) if(&other != this)
_dev = other._dev; _dev = other._dev;

View File

@ -13,7 +13,10 @@ namespace details
class line_logger class line_logger
{ {
public: public:
line_logger(logger* callback_logger, level::level_enum msg_level) { line_logger(logger* callback_logger, level::level_enum msg_level):
_callback_logger(callback_logger),
_oss(),
_level(msg_level) {
callback_logger->formatter_->format_header(callback_logger->logger_name_, callback_logger->formatter_->format_header(callback_logger->logger_name_,
msg_level, msg_level,
c11log::formatters::clock::now(), c11log::formatters::clock::now(),
@ -24,7 +27,9 @@ public:
_callback_logger(other._callback_logger), _callback_logger(other._callback_logger),
_oss(other._oss), _oss(other._oss),
_level(other._level) {}; _level(other._level) {};
line_logger& operator=(const line_logger&) = delete; line_logger& operator=(const line_logger&) = delete;
~line_logger() { ~line_logger() {
if (_callback_logger) { if (_callback_logger) {
_oss << '\n'; _oss << '\n';

View File

@ -26,10 +26,13 @@ public:
typedef std::shared_ptr<sinks::base_sink> sink_ptr_t; typedef std::shared_ptr<sinks::base_sink> sink_ptr_t;
typedef std::vector<sink_ptr_t> sinks_vector_t; typedef std::vector<sink_ptr_t> sinks_vector_t;
explicit logger(const std::string& name) : logger_name_(name), explicit logger(const std::string& name) :
formatter_(std::make_unique<formatters::default_formatter>()) { logger_name_(name),
atomic_level_.store(level::INFO); formatter_(std::make_unique<formatters::default_formatter>()),
} sinks_(),
mutex_(),
atomic_level_(level::INFO)
{}
~logger() = default; ~logger() = default;
@ -55,7 +58,6 @@ public:
private: private:
friend details::line_logger; friend details::line_logger;
std::string logger_name_ = ""; std::string logger_name_ = "";
std::unique_ptr<c11log::formatters::formatter> formatter_; std::unique_ptr<c11log::formatters::formatter> formatter_;
sinks_vector_t sinks_; sinks_vector_t sinks_;

View File

@ -31,7 +31,7 @@ protected:
private: private:
c11log::logger::sinks_vector_t sinks_; c11log::logger::sinks_vector_t sinks_;
std::atomic<bool> active_ { true }; std::atomic<bool> active_;
c11log::details::blocking_queue<std::string> q_; c11log::details::blocking_queue<std::string> q_;
std::thread back_thread_; std::thread back_thread_;
//Clear all remaining messages(if any), stop the back_thread_ and join it //Clear all remaining messages(if any), stop the back_thread_ and join it
@ -45,7 +45,9 @@ private:
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline c11log::sinks::async_sink::async_sink(const std::size_t max_queue_size) inline c11log::sinks::async_sink::async_sink(const std::size_t max_queue_size)
:q_(max_queue_size), :sinks_(),
active_(true),
q_(max_queue_size),
back_thread_(&async_sink::thread_loop_, this) back_thread_(&async_sink::thread_loop_, this)
{} {}

View File

@ -6,29 +6,29 @@
#include "base_sink.h" #include "base_sink.h"
namespace c11log { namespace c11log
namespace sinks { {
namespace sinks
{
/* /*
* Trivial file sink with single file as target * Trivial file sink with single file as target
*/ */
class simple_file_sink : public base_sink { class simple_file_sink : public base_sink
{
public: public:
simple_file_sink(const std::string &filename, const std::string& extension = "txt") explicit simple_file_sink(const std::string &filename, const std::string& extension = "txt")
{ : mutex_(),
std::ostringstream oss; _ofstream(filename + "." + extension, std::ofstream::app)
oss << filename << "." << extension; {}
_ofstream.open(oss.str(), std::ofstream::app);
}
protected: protected:
void sink_it_(const std::string& msg) override void sink_it_(const std::string& msg) override {
{ std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock(mutex_); _ofstream << msg;
_ofstream << msg; _ofstream.flush();
_ofstream.flush(); }
}
private: private:
std::mutex mutex_; std::mutex mutex_;
std::ofstream _ofstream; std::ofstream _ofstream;
}; };
@ -36,130 +36,124 @@ private:
/* /*
* Thread safe, size limited file sink * Thread safe, size limited file sink
*/ */
class rotating_file_sink : public base_sink { class rotating_file_sink : public base_sink
{
public: public:
rotating_file_sink(const std::string &base_filename, const std::string &extension, size_t max_size, size_t max_files): rotating_file_sink(const std::string &base_filename, const std::string &extension, size_t max_size, size_t max_files):
_base_filename(base_filename), _base_filename(base_filename),
_extension(extension), _extension(extension),
_max_size(max_size), _max_size(max_size),
_max_files(max_files), _max_files(max_files),
_current_size(0), _current_size(0),
_index(0) _index(0),
{ mutex_(),
_ofstream.open(_calc_filename(_base_filename, 0, _extension)); _ofstream(_calc_filename(_base_filename, 0, _extension))
} {}
protected: protected:
void sink_it_(const std::string& msg) override void sink_it_(const std::string& msg) override {
{ std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock(mutex_); _current_size += msg.length();
_current_size += msg.length(); if (_current_size > _max_size) {
if (_current_size > _max_size) _rotate();
{ _current_size = msg.length();
_rotate(); }
_current_size = msg.length(); _ofstream << msg;
} _ofstream.flush();
_ofstream << msg; }
_ofstream.flush();
}
private: private:
static std::string _calc_filename(const std::string& filename, std::size_t index, const std::string& extension) static std::string _calc_filename(const std::string& filename, std::size_t index, const std::string& extension) {
{ std::ostringstream oss;
std::ostringstream oss; if (index)
if (index) oss << filename << "." << index << "." << extension;
oss << filename << "." << index << "." << extension; else
else oss << filename << "." << extension;
oss << filename << "." << extension; return oss.str();
return oss.str(); }
}
// Rotate old files: // Rotate old files:
// log.n-1.txt -> log.n.txt // log.n-1.txt -> log.n.txt
// log n-2.txt -> log.n-1.txt // log n-2.txt -> log.n-1.txt
// ... // ...
// log.txt -> log.1.txt // log.txt -> log.1.txt
void _rotate() void _rotate() {
{ _ofstream.close();
_ofstream.close(); //Remove oldest file
//Remove oldest file for (auto i = _max_files; i > 0; --i) {
for (auto i = _max_files; i > 0; --i) { auto src = _calc_filename(_base_filename, i - 1, _extension);
auto src = _calc_filename(_base_filename, i - 1, _extension); auto target = _calc_filename(_base_filename, i, _extension);
auto target = _calc_filename(_base_filename, i, _extension); if (i == _max_files)
if (i == _max_files) std::remove(target.c_str());
std::remove(target.c_str()); std::rename(src.c_str(), target.c_str());
std::rename(src.c_str(), target.c_str()); }
} _ofstream.open(_calc_filename(_base_filename, 0, _extension));
_ofstream.open(_calc_filename(_base_filename, 0, _extension)); }
}
std::string _base_filename; std::string _base_filename;
std::string _extension; std::string _extension;
std::size_t _max_size; std::size_t _max_size;
std::size_t _max_files; std::size_t _max_files;
std::size_t _current_size; std::size_t _current_size;
std::size_t _index; std::size_t _index;
std::ofstream _ofstream; std::mutex mutex_;
std::mutex mutex_; std::ofstream _ofstream;
}; };
/* /*
* Thread safe file sink that closes the log file at midnight and opens new one * Thread safe file sink that closes the log file at midnight and opens new one
*/ */
class daily_file_sink:public base_sink { class daily_file_sink:public base_sink
{
public: public:
daily_file_sink(const std::string& base_filename, const std::string& extension = "txt"): explicit daily_file_sink(const std::string& base_filename, const std::string& extension = "txt"):
_base_filename(base_filename), _base_filename(base_filename),
_extension(extension), _extension(extension),
_midnight_tp { _calc_midnight_tp() } _midnight_tp (_calc_midnight_tp() ),
mutex_(),
{ _ofstream(_calc_filename(_base_filename, _extension), std::ofstream::app)
_ofstream.open(_calc_filename(_base_filename, _extension), std::ofstream::app); {}
}
protected: protected:
void sink_it_(const std::string& msg) override void sink_it_(const std::string& msg) override {
{ std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock(mutex_); if (std::chrono::system_clock::now() >= _midnight_tp) {
if (std::chrono::system_clock::now() >= _midnight_tp) _ofstream.close();
{ _ofstream.open(_calc_filename(_base_filename, _extension));
_ofstream.close(); _midnight_tp = _calc_midnight_tp();
_ofstream.open(_calc_filename(_base_filename, _extension)); }
_midnight_tp = _calc_midnight_tp(); _ofstream << msg;
} _ofstream.flush();
_ofstream << msg; }
_ofstream.flush();
}
private: private:
// Return next midnight's time_point // Return next midnight's time_point
static std::chrono::system_clock::time_point _calc_midnight_tp() static std::chrono::system_clock::time_point _calc_midnight_tp() {
{ using namespace std::chrono;
using namespace std::chrono; auto now = system_clock::now();
auto now = system_clock::now(); time_t tnow = std::chrono::system_clock::to_time_t(now);
time_t tnow = std::chrono::system_clock::to_time_t(now); tm date = c11log::details::os::localtime(tnow);
tm date = c11log::details::os::localtime(tnow); date.tm_hour = date.tm_min = date.tm_sec = 0;
date.tm_hour = date.tm_min = date.tm_sec = 0; auto midnight = std::chrono::system_clock::from_time_t(std::mktime(&date));
auto midnight = std::chrono::system_clock::from_time_t(std::mktime(&date)); return system_clock::time_point(midnight + hours(24));
return system_clock::time_point(midnight + hours(24)); }
}
static std::string _calc_filename(const std::string& basename, const std::string& extension) static std::string _calc_filename(const std::string& basename, const std::string& extension) {
{ std::tm tm = c11log::details::os::localtime();
std::tm tm = c11log::details::os::localtime(); char buf[32];
char buf[32]; sprintf(buf, ".%d-%02d-%02d.", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
sprintf(buf, ".%d-%02d-%02d.", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); return basename+buf+extension;
return basename+buf+extension; }
}
std::string _base_filename;
std::string _extension;
std::chrono::system_clock::time_point _midnight_tp;
std::mutex mutex_;
std::ofstream _ofstream;
std::string _base_filename;
std::string _extension;
std::chrono::system_clock::time_point _midnight_tp;
std::ofstream _ofstream;
std::mutex mutex_;
}; };
} }
} }