clang-format

This commit is contained in:
gabime
2018-03-09 15:26:33 +02:00
parent 461b5ef28a
commit a2653d409f
66 changed files with 2330 additions and 2587 deletions

View File

@@ -13,11 +13,11 @@
#pragma once
#include "../common.h"
#include "../sinks/sink.h"
#include "../details/mpmc_bounded_q.h"
#include "../details/log_msg.h"
#include "../details/mpmc_bounded_q.h"
#include "../details/os.h"
#include "../formatter.h"
#include "../sinks/sink.h"
#include <chrono>
#include <exception>
@@ -28,10 +28,7 @@
#include <utility>
#include <vector>
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
class async_log_helper
{
@@ -57,24 +54,25 @@ class async_log_helper
async_msg() = default;
~async_msg() = default;
explicit async_msg(async_msg_type m_type) :
level(level::info),
thread_id(0),
msg_type(m_type),
msg_id(0)
{}
explicit async_msg(async_msg_type m_type)
: level(level::info)
, thread_id(0)
, msg_type(m_type)
, msg_id(0)
{
}
async_msg(async_msg&& other) SPDLOG_NOEXCEPT :
logger_name(std::move(other.logger_name)),
level(std::move(other.level)),
time(std::move(other.time)),
thread_id(other.thread_id),
txt(std::move(other.txt)),
msg_type(std::move(other.msg_type)),
msg_id(other.msg_id)
{}
async_msg(async_msg &&other) SPDLOG_NOEXCEPT : logger_name(std::move(other.logger_name)),
level(std::move(other.level)),
time(std::move(other.time)),
thread_id(other.thread_id),
txt(std::move(other.txt)),
msg_type(std::move(other.msg_type)),
msg_id(other.msg_id)
{
}
async_msg& operator=(async_msg&& other) SPDLOG_NOEXCEPT
async_msg &operator=(async_msg &&other) SPDLOG_NOEXCEPT
{
logger_name = std::move(other.logger_name);
level = other.level;
@@ -87,17 +85,17 @@ async_msg(async_msg&& other) SPDLOG_NOEXCEPT :
}
// never copy or assign. should only be moved..
async_msg(const async_msg&) = delete;
async_msg& operator=(const async_msg& other) = delete;
async_msg(const async_msg &) = delete;
async_msg &operator=(const async_msg &other) = delete;
// construct from log_msg
explicit async_msg(const details::log_msg& m):
level(m.level),
time(m.time),
thread_id(m.thread_id),
txt(m.raw.data(), m.raw.size()),
msg_type(async_msg_type::log),
msg_id(m.msg_id)
explicit async_msg(const details::log_msg &m)
: level(m.level)
, time(m.time)
, thread_id(m.thread_id)
, txt(m.raw.data(), m.raw.size())
, msg_type(async_msg_type::log)
, msg_id(m.msg_id)
{
#ifndef SPDLOG_NO_NAME
logger_name = *m.logger_name;
@@ -122,22 +120,18 @@ public:
using clock = std::chrono::steady_clock;
async_log_helper(formatter_ptr formatter,
std::vector<sink_ptr> sinks,
size_t queue_size,
const log_err_handler err_handler,
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
std::function<void()> worker_warmup_cb = nullptr,
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
std::function<void()> worker_teardown_cb = nullptr);
async_log_helper(formatter_ptr formatter, std::vector<sink_ptr> sinks, size_t queue_size, const log_err_handler err_handler,
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry, std::function<void()> worker_warmup_cb = nullptr,
const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(),
std::function<void()> worker_teardown_cb = nullptr);
void log(const details::log_msg& msg);
void log(const details::log_msg &msg);
// stop logging and join the back thread
~async_log_helper();
async_log_helper(const async_log_helper&) = delete;
async_log_helper& operator=(const async_log_helper&) = delete;
async_log_helper(const async_log_helper &) = delete;
async_log_helper &operator=(const async_log_helper &) = delete;
void set_formatter(formatter_ptr msg_formatter);
@@ -173,49 +167,41 @@ private:
// worker thread
std::thread _worker_thread;
void push_msg(async_msg&& new_msg);
void push_msg(async_msg &&new_msg);
// worker thread main loop
void worker_loop();
// pop next message from the queue and process it. will set the last_pop to the pop time
// return false if termination of the queue is required
bool process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush);
bool process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush);
void handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush);
void handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush);
// sleep,yield or return immediately using the time passed since last message as a hint
static void sleep_or_yield(const spdlog::log_clock::time_point& now, const log_clock::time_point& last_op_time);
static void sleep_or_yield(const spdlog::log_clock::time_point &now, const log_clock::time_point &last_op_time);
// wait until the queue is empty
void wait_empty_q();
};
}
}
}} // namespace spdlog::details
///////////////////////////////////////////////////////////////////////////////
// async_sink class implementation
///////////////////////////////////////////////////////////////////////////////
inline spdlog::details::async_log_helper::async_log_helper(
formatter_ptr formatter,
std::vector<sink_ptr> sinks,
size_t queue_size,
log_err_handler err_handler,
const async_overflow_policy overflow_policy,
std::function<void()> worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
std::function<void()> worker_teardown_cb):
_formatter(std::move(formatter)),
_sinks(std::move(sinks)),
_q(queue_size),
_err_handler(std::move(err_handler)),
_flush_requested(false),
_terminate_requested(false),
_overflow_policy(overflow_policy),
_worker_warmup_cb(std::move(worker_warmup_cb)),
_flush_interval_ms(flush_interval_ms),
_worker_teardown_cb(std::move(worker_teardown_cb))
inline spdlog::details::async_log_helper::async_log_helper(formatter_ptr formatter, std::vector<sink_ptr> sinks, size_t queue_size,
log_err_handler err_handler, const async_overflow_policy overflow_policy, std::function<void()> worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, std::function<void()> worker_teardown_cb)
: _formatter(std::move(formatter))
, _sinks(std::move(sinks))
, _q(queue_size)
, _err_handler(std::move(err_handler))
, _flush_requested(false)
, _terminate_requested(false)
, _overflow_policy(overflow_policy)
, _worker_warmup_cb(std::move(worker_warmup_cb))
, _flush_interval_ms(flush_interval_ms)
, _worker_teardown_cb(std::move(worker_teardown_cb))
{
_worker_thread = std::thread(&async_log_helper::worker_loop, this);
}
@@ -234,14 +220,13 @@ inline spdlog::details::async_log_helper::~async_log_helper()
}
}
//Try to push and block until succeeded (if the policy is not to discard when the queue is full)
inline void spdlog::details::async_log_helper::log(const details::log_msg& msg)
// Try to push and block until succeeded (if the policy is not to discard when the queue is full)
inline void spdlog::details::async_log_helper::log(const details::log_msg &msg)
{
push_msg(async_msg(msg));
}
inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg)
inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg &&new_msg)
{
if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg)
{
@@ -251,8 +236,7 @@ inline void spdlog::details::async_log_helper::push_msg(details::async_log_helpe
{
now = details::os::now();
sleep_or_yield(now, last_op_time);
}
while (!_q.enqueue(std::move(new_msg)));
} while (!_q.enqueue(std::move(new_msg)));
}
}
@@ -261,12 +245,13 @@ inline void spdlog::details::async_log_helper::flush(bool wait_for_q)
{
push_msg(async_msg(async_msg_type::flush));
if (wait_for_q)
wait_empty_q(); //return when queue is empty
wait_empty_q(); // return when queue is empty
}
inline void spdlog::details::async_log_helper::worker_loop()
{
if (_worker_warmup_cb) _worker_warmup_cb();
if (_worker_warmup_cb)
_worker_warmup_cb();
auto last_pop = details::os::now();
auto last_flush = last_pop;
auto active = true;
@@ -280,19 +265,18 @@ inline void spdlog::details::async_log_helper::worker_loop()
{
_err_handler(ex.what());
}
catch(...)
catch (...)
{
_err_handler("Unknown exeption in async logger worker loop.");
}
}
if (_worker_teardown_cb) _worker_teardown_cb();
if (_worker_teardown_cb)
_worker_teardown_cb();
}
// process next message in the queue
// return true if this thread should still be active (while no terminate msg was received)
inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point& last_pop, log_clock::time_point& last_flush)
inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_point &last_pop, log_clock::time_point &last_flush)
{
async_msg incoming_async_msg;
@@ -334,9 +318,10 @@ inline bool spdlog::details::async_log_helper::process_next_msg(log_clock::time_
}
// flush all sinks if _flush_interval_ms has expired
inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point& now, log_clock::time_point& last_flush)
inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::time_point &now, log_clock::time_point &last_flush)
{
auto should_flush = _flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms);
auto should_flush =
_flush_requested || (_flush_interval_ms != std::chrono::milliseconds::zero() && now - last_flush >= _flush_interval_ms);
if (should_flush)
{
for (auto &s : _sinks)
@@ -352,10 +337,11 @@ inline void spdlog::details::async_log_helper::set_formatter(formatter_ptr msg_f
}
// spin, yield or sleep. use the time passed since last message as a hint
inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_clock::time_point& now, const spdlog::log_clock::time_point& last_op_time)
inline void spdlog::details::async_log_helper::sleep_or_yield(
const spdlog::log_clock::time_point &now, const spdlog::log_clock::time_point &last_op_time)
{
using std::chrono::milliseconds;
using std::chrono::microseconds;
using std::chrono::milliseconds;
auto time_since_op = now - last_op_time;

View File

@@ -8,49 +8,39 @@
// Async Logger implementation
// Use an async_sink (queue per logger) to perform the logging in a worker thread
#include "../details/async_log_helper.h"
#include "../async_logger.h"
#include "../details/async_log_helper.h"
#include <string>
#include <functional>
#include <chrono>
#include <functional>
#include <memory>
#include <string>
template<class It>
inline spdlog::async_logger::async_logger(const std::string& logger_name,
const It& begin,
const It& end,
size_t queue_size,
const async_overflow_policy overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
logger(logger_name, begin, end),
_async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
template <class It>
inline spdlog::async_logger::async_logger(const std::string &logger_name, const It &begin, const It &end, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
: logger(logger_name, begin, end)
, _async_log_helper(new details::async_log_helper(
_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
{
}
inline spdlog::async_logger::async_logger(const std::string& logger_name,
sinks_init_list sinks_list,
size_t queue_size,
const async_overflow_policy overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
inline spdlog::async_logger::async_logger(const std::string& logger_name,
sink_ptr single_sink,
size_t queue_size,
const async_overflow_policy overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
async_logger(logger_name,
inline spdlog::async_logger::async_logger(const std::string &logger_name, sinks_init_list sinks_list, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
: async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms,
worker_teardown_cb)
{
std::move(single_sink)
}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
}
inline spdlog::async_logger::async_logger(const std::string &logger_name, sink_ptr single_sink, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
: async_logger(
logger_name, {std::move(single_sink)}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)
{
}
inline void spdlog::async_logger::flush()
{
@@ -62,28 +52,25 @@ inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_
{
_err_handler = err_handler;
_async_log_helper->set_error_handler(err_handler);
}
inline spdlog::log_err_handler spdlog::async_logger::error_handler()
{
return _err_handler;
}
inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter)
{
_formatter = msg_formatter;
_async_log_helper->set_formatter(_formatter);
}
inline void spdlog::async_logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time)
inline void spdlog::async_logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time)
{
_formatter = std::make_shared<pattern_formatter>(pattern, pattern_time);
_async_log_helper->set_formatter(_formatter);
}
inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
inline void spdlog::async_logger::_sink_it(details::log_msg &msg)
{
try
{
@@ -98,10 +85,9 @@ inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
{
_err_handler(ex.what());
}
catch(...)
catch (...)
{
_err_handler("Unknown exception in logger " + _name);
throw;
}
}

View File

@@ -9,20 +9,17 @@
// When failing to open a file, retry several times(5) with small delay between the tries(10 ms)
// Throw spdlog_ex exception on errors
#include "../details/os.h"
#include "../details/log_msg.h"
#include "../details/os.h"
#include <cerrno>
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <tuple>
#include <cerrno>
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
class file_helper
{
@@ -33,16 +30,15 @@ public:
explicit file_helper() = default;
file_helper(const file_helper&) = delete;
file_helper& operator=(const file_helper&) = delete;
file_helper(const file_helper &) = delete;
file_helper &operator=(const file_helper &) = delete;
~file_helper()
{
close();
}
void open(const filename_t& fname, bool truncate = false)
void open(const filename_t &fname, bool truncate = false)
{
close();
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
@@ -63,7 +59,6 @@ public:
if (_filename.empty())
throw spdlog_ex("Failed re opening file - was not opened before");
open(_filename, truncate);
}
void flush()
@@ -80,7 +75,7 @@ public:
}
}
void write(const log_msg& msg)
void write(const log_msg &msg)
{
size_t msg_size = msg.formatted.size();
auto data = msg.formatted.data();
@@ -97,12 +92,12 @@ public:
return os::filesize(_fd);
}
const filename_t& filename() const
const filename_t &filename() const
{
return _filename;
}
static bool file_exists(const filename_t& fname)
static bool file_exists(const filename_t &fname)
{
return os::file_exists(fname);
}
@@ -120,7 +115,7 @@ public:
// ".mylog" => (".mylog". "")
// "my_folder/.mylog" => ("my_folder/.mylog", "")
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
static std::tuple<filename_t, filename_t> split_by_extenstion(const spdlog::filename_t& fname)
static std::tuple<filename_t, filename_t> split_by_extenstion(const spdlog::filename_t &fname)
{
auto ext_index = fname.rfind('.');
@@ -138,8 +133,7 @@ public:
}
private:
FILE* _fd{ nullptr };
FILE *_fd{nullptr};
filename_t _filename;
};
}
}
}} // namespace spdlog::details

View File

@@ -11,16 +11,13 @@
#include <string>
#include <utility>
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
struct log_msg
{
log_msg() = default;
log_msg(const std::string *loggers_name, level::level_enum lvl) :
logger_name(loggers_name),
level(lvl)
log_msg(const std::string *loggers_name, level::level_enum lvl)
: logger_name(loggers_name)
, level(lvl)
{
#ifndef SPDLOG_NO_DATETIME
time = os::now();
@@ -31,18 +28,16 @@ struct log_msg
#endif
}
log_msg(const log_msg& other) = delete;
log_msg& operator=(log_msg&& other) = delete;
log_msg(log_msg&& other) = delete;
log_msg(const log_msg &other) = delete;
log_msg &operator=(log_msg &&other) = delete;
log_msg(log_msg &&other) = delete;
const std::string *logger_name{ nullptr };
const std::string *logger_name{nullptr};
level::level_enum level;
log_clock::time_point time;
size_t thread_id;
fmt::MemoryWriter raw;
fmt::MemoryWriter formatted;
size_t msg_id{ 0 };
size_t msg_id{0};
};
}
}
}} // namespace spdlog::details

View File

@@ -13,54 +13,47 @@
// create logger with given name, sinks and the default pattern formatter
// all other ctors will call this one
template<class It>
inline spdlog::logger::logger(std::string logger_name, const It& begin, const It& end):
_name(std::move(logger_name)),
_sinks(begin, end),
_formatter(std::make_shared<pattern_formatter>("%+")),
_level(level::info),
_flush_level(level::off),
_last_err_time(0),
_msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages
template <class It>
inline spdlog::logger::logger(std::string logger_name, const It &begin, const It &end)
: _name(std::move(logger_name))
, _sinks(begin, end)
, _formatter(std::make_shared<pattern_formatter>("%+"))
, _level(level::info)
, _flush_level(level::off)
, _last_err_time(0)
, _msg_counter(1) // message counter will start from 1. 0-message id will be reserved for controll messages
{
_err_handler = [this](const std::string &msg)
{
this->_default_err_handler(msg);
};
_err_handler = [this](const std::string &msg) { this->_default_err_handler(msg); };
}
// ctor with sinks as init list
inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list):
logger(logger_name, sinks_list.begin(), sinks_list.end())
{}
inline spdlog::logger::logger(const std::string &logger_name, sinks_init_list sinks_list)
: logger(logger_name, sinks_list.begin(), sinks_list.end())
{
}
// ctor with single sink
inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink):
logger(logger_name,
inline spdlog::logger::logger(const std::string &logger_name, spdlog::sink_ptr single_sink)
: logger(logger_name, {std::move(single_sink)})
{
std::move(single_sink)
})
{}
}
inline spdlog::logger::~logger() = default;
inline void spdlog::logger::set_formatter(spdlog::formatter_ptr msg_formatter)
{
_set_formatter(std::move(msg_formatter));
}
inline void spdlog::logger::set_pattern(const std::string& pattern, pattern_time_type pattern_time)
inline void spdlog::logger::set_pattern(const std::string &pattern, pattern_time_type pattern_time)
{
_set_pattern(pattern, pattern_time);
}
template <typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args)
{
if (!should_log(lvl)) return;
if (!should_log(lvl))
return;
try
{
@@ -77,17 +70,17 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Ar
{
_err_handler(ex.what());
}
catch(...)
catch (...)
{
_err_handler("Unknown exception in logger " + _name);
throw;
}
}
template <typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const char* msg)
template <typename... Args> inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
{
if (!should_log(lvl)) return;
if (!should_log(lvl))
return;
try
{
details::log_msg log_msg(&_name, lvl);
@@ -105,10 +98,10 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* msg)
}
}
template<typename T>
inline void spdlog::logger::log(level::level_enum lvl, const T& msg)
template <typename T> inline void spdlog::logger::log(level::level_enum lvl, const T &msg)
{
if (!should_log(lvl)) return;
if (!should_log(lvl))
return;
try
{
details::log_msg log_msg(&_name, lvl);
@@ -126,98 +119,78 @@ inline void spdlog::logger::log(level::level_enum lvl, const T& msg)
}
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::trace(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::trace(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::trace, fmt, arg1, args...);
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::debug(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::debug(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::debug, fmt, arg1, args...);
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::info(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::info(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::info, fmt, arg1, args...);
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::warn(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::warn(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::warn, fmt, arg1, args...);
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::error(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::error(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::err, fmt, arg1, args...);
}
template <typename Arg1, typename... Args>
inline void spdlog::logger::critical(const char* fmt, const Arg1 &arg1, const Args&... args)
template <typename Arg1, typename... Args> inline void spdlog::logger::critical(const char *fmt, const Arg1 &arg1, const Args &... args)
{
log(level::critical, fmt, arg1, args...);
}
template<typename T>
inline void spdlog::logger::trace(const T& msg)
template <typename T> inline void spdlog::logger::trace(const T &msg)
{
log(level::trace, msg);
}
template<typename T>
inline void spdlog::logger::debug(const T& msg)
template <typename T> inline void spdlog::logger::debug(const T &msg)
{
log(level::debug, msg);
}
template<typename T>
inline void spdlog::logger::info(const T& msg)
template <typename T> inline void spdlog::logger::info(const T &msg)
{
log(level::info, msg);
}
template<typename T>
inline void spdlog::logger::warn(const T& msg)
template <typename T> inline void spdlog::logger::warn(const T &msg)
{
log(level::warn, msg);
}
template<typename T>
inline void spdlog::logger::error(const T& msg)
template <typename T> inline void spdlog::logger::error(const T &msg)
{
log(level::err, msg);
}
template<typename T>
inline void spdlog::logger::critical(const T& msg)
template <typename T> inline void spdlog::logger::critical(const T &msg)
{
log(level::critical, msg);
}
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
#include <codecvt>
#include <locale>
template <typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* msg)
template <typename... Args> inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *msg)
{
std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
log(lvl, conv.to_bytes(msg));
}
template <typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::log(level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
fmt::WMemoryWriter wWriter;
@@ -225,51 +198,42 @@ inline void spdlog::logger::log(level::level_enum lvl, const wchar_t* fmt, const
log(lvl, wWriter.c_str());
}
template <typename... Args>
inline void spdlog::logger::trace(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::trace(const wchar_t *fmt, const Args &... args)
{
log(level::trace, fmt, args...);
}
template <typename... Args>
inline void spdlog::logger::debug(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::debug(const wchar_t *fmt, const Args &... args)
{
log(level::debug, fmt, args...);
}
template <typename... Args>
inline void spdlog::logger::info(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::info(const wchar_t *fmt, const Args &... args)
{
log(level::info, fmt, args...);
}
template <typename... Args>
inline void spdlog::logger::warn(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::warn(const wchar_t *fmt, const Args &... args)
{
log(level::warn, fmt, args...);
}
template <typename... Args>
inline void spdlog::logger::error(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::error(const wchar_t *fmt, const Args &... args)
{
log(level::err, fmt, args...);
}
template <typename... Args>
inline void spdlog::logger::critical(const wchar_t* fmt, const Args&... args)
template <typename... Args> inline void spdlog::logger::critical(const wchar_t *fmt, const Args &... args)
{
log(level::critical, fmt, args...);
}
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
//
// name and level
//
inline const std::string& spdlog::logger::name() const
inline const std::string &spdlog::logger::name() const
{
return _name;
}
@@ -307,7 +271,7 @@ inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) cons
//
// protected virtual called at end of each user log call (if enabled) by the line_logger
//
inline void spdlog::logger::_sink_it(details::log_msg& msg)
inline void spdlog::logger::_sink_it(details::log_msg &msg)
{
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
_incr_msg_counter(msg);
@@ -315,17 +279,17 @@ inline void spdlog::logger::_sink_it(details::log_msg& msg)
_formatter->format(msg);
for (auto &sink : _sinks)
{
if( sink->should_log( msg.level))
if (sink->should_log(msg.level))
{
sink->log(msg);
}
}
if(_should_flush_on(msg))
if (_should_flush_on(msg))
flush();
}
inline void spdlog::logger::_set_pattern(const std::string& pattern, pattern_time_type pattern_time)
inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time)
{
_formatter = std::make_shared<pattern_formatter>(pattern, pattern_time);
}
@@ -337,7 +301,7 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter)
inline void spdlog::logger::flush()
{
for (auto& sink : _sinks)
for (auto &sink : _sinks)
sink->flush();
}
@@ -366,8 +330,7 @@ inline void spdlog::logger::_incr_msg_counter(details::log_msg &msg)
msg.msg_id = _msg_counter.fetch_add(1, std::memory_order_relaxed);
}
inline const std::vector<spdlog::sink_ptr>& spdlog::logger::sinks() const
inline const std::vector<spdlog::sink_ptr> &spdlog::logger::sinks() const
{
return _sinks;
}

View File

@@ -48,23 +48,19 @@ Distributed under the MIT License (http://opensource.org/licenses/MIT)
#include <atomic>
#include <utility>
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
template <typename T>
class mpmc_bounded_queue
template <typename T> class mpmc_bounded_queue
{
public:
using item_type = T;
explicit mpmc_bounded_queue(size_t buffer_size)
:max_size_(buffer_size),
buffer_(new cell_t[buffer_size]),
buffer_mask_(buffer_size - 1)
: max_size_(buffer_size)
, buffer_(new cell_t[buffer_size])
, buffer_mask_(buffer_size - 1)
{
//queue size must be power of two
// queue size must be power of two
if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)))
throw spdlog_ex("async logger queue size must be power of two");
@@ -79,12 +75,12 @@ public:
delete[] buffer_;
}
mpmc_bounded_queue(mpmc_bounded_queue const&) = delete;
void operator=(mpmc_bounded_queue const&) = delete;
mpmc_bounded_queue(mpmc_bounded_queue const &) = delete;
void operator=(mpmc_bounded_queue const &) = delete;
bool enqueue(T&& data)
bool enqueue(T &&data)
{
cell_t* cell;
cell_t *cell;
size_t pos = enqueue_pos_.load(std::memory_order_relaxed);
for (;;)
{
@@ -110,15 +106,14 @@ public:
return true;
}
bool dequeue(T& data)
bool dequeue(T &data)
{
cell_t* cell;
cell_t *cell;
size_t pos = dequeue_pos_.load(std::memory_order_relaxed);
for (;;)
{
cell = &buffer_[pos & buffer_mask_];
size_t seq =
cell->sequence_.load(std::memory_order_acquire);
size_t seq = cell->sequence_.load(std::memory_order_acquire);
intptr_t dif = static_cast<intptr_t>(seq) - static_cast<intptr_t>(pos + 1);
if (dif == 0)
{
@@ -144,32 +139,30 @@ public:
front = enqueue_pos_.load(std::memory_order_acquire);
back = dequeue_pos_.load(std::memory_order_acquire);
front1 = enqueue_pos_.load(std::memory_order_relaxed);
}
while (front != front1);
} while (front != front1);
return back == front;
}
private:
struct cell_t
{
std::atomic<size_t> sequence_;
T data_;
std::atomic<size_t> sequence_;
T data_;
};
size_t const max_size_;
static size_t const cacheline_size = 64;
static size_t const cacheline_size = 64;
using cacheline_pad_t = char[cacheline_size];
cacheline_pad_t pad0_;
cell_t* const buffer_;
size_t const buffer_mask_;
cacheline_pad_t pad1_;
std::atomic<size_t> enqueue_pos_;
cacheline_pad_t pad2_;
std::atomic<size_t> dequeue_pos_;
cacheline_pad_t pad3_;
cacheline_pad_t pad0_;
cell_t *const buffer_;
size_t const buffer_mask_;
cacheline_pad_t pad1_;
std::atomic<size_t> enqueue_pos_;
cacheline_pad_t pad2_;
std::atomic<size_t> dequeue_pos_;
cacheline_pad_t pad3_;
};
} // ns details
} // ns spdlog
}} // namespace spdlog::details

View File

@@ -8,10 +8,7 @@
#include <atomic>
// null, no cost dummy "mutex" and dummy "atomic" int
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
struct null_mutex
{
void lock() {}
@@ -27,8 +24,10 @@ struct null_atomic_int
int value;
null_atomic_int() = default;
explicit null_atomic_int(int val) : value(val)
{}
explicit null_atomic_int(int val)
: value(val)
{
}
int load(std::memory_order) const
{
@@ -41,5 +40,4 @@ struct null_atomic_int
}
};
}
}
}} // namespace spdlog::details

View File

@@ -6,30 +6,30 @@
#include "../common.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <functional>
#include <string>
#include <chrono>
#include <thread>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <thread>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX //prevent windows redefining min/max
#define NOMINMAX // prevent windows redefining min/max
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <io.h> // _get_osfhandle and _isatty support
#include <process.h> // _get_pid support
#include <io.h> // _get_osfhandle and _isatty support
#include <windows.h>
#ifdef __MINGW32__
#include <share.h>
@@ -37,8 +37,8 @@
#else // unix
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#ifdef __linux__
#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
@@ -47,19 +47,13 @@
#include <sys/thr.h> //Use thr_self() syscall under FreeBSD to get thread id
#endif
#endif //unix
#endif // unix
#ifndef __has_feature // Clang - feature checking macros.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#ifndef __has_feature // Clang - feature checking macros.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
namespace spdlog
{
namespace details
{
namespace os
{
namespace spdlog { namespace details { namespace os {
inline spdlog::log_clock::time_point now()
{
@@ -68,14 +62,11 @@ inline spdlog::log_clock::time_point now()
timespec ts;
::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
return std::chrono::time_point<log_clock, typename log_clock::duration>(
std::chrono::duration_cast<typename log_clock::duration>(
std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
#else
return log_clock::now();
#endif
}
inline std::tm localtime(const std::time_t &time_tt)
{
@@ -114,24 +105,19 @@ inline std::tm gmtime()
std::time_t now_t = time(nullptr);
return gmtime(now_t);
}
inline bool operator==(const std::tm& tm1, const std::tm& tm2)
inline bool operator==(const std::tm &tm1, const std::tm &tm2)
{
return (tm1.tm_sec == tm2.tm_sec &&
tm1.tm_min == tm2.tm_min &&
tm1.tm_hour == tm2.tm_hour &&
tm1.tm_mday == tm2.tm_mday &&
tm1.tm_mon == tm2.tm_mon &&
tm1.tm_year == tm2.tm_year &&
tm1.tm_isdst == tm2.tm_isdst);
return (tm1.tm_sec == tm2.tm_sec && tm1.tm_min == tm2.tm_min && tm1.tm_hour == tm2.tm_hour && tm1.tm_mday == tm2.tm_mday &&
tm1.tm_mon == tm2.tm_mon && tm1.tm_year == tm2.tm_year && tm1.tm_isdst == tm2.tm_isdst);
}
inline bool operator!=(const std::tm& tm1, const std::tm& tm2)
inline bool operator!=(const std::tm &tm1, const std::tm &tm2)
{
return !(tm1 == tm2);
}
// eol definition
#if !defined (SPDLOG_EOL)
#if !defined(SPDLOG_EOL)
#ifdef _WIN32
#define SPDLOG_EOL "\r\n"
#else
@@ -139,9 +125,7 @@ inline bool operator!=(const std::tm& tm1, const std::tm& tm2)
#endif
#endif
SPDLOG_CONSTEXPR static const char* default_eol = SPDLOG_EOL;
SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
// folder separator
#ifdef _WIN32
@@ -150,7 +134,6 @@ SPDLOG_CONSTEXPR static const char folder_sep = '\\';
SPDLOG_CONSTEXPR static const char folder_sep = '/';
#endif
inline void prevent_child_fd(FILE *f)
{
@@ -167,9 +150,8 @@ inline void prevent_child_fd(FILE *f)
#endif
}
//fopen_s on non windows for writing
inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mode)
// fopen_s on non windows for writing
inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
@@ -177,7 +159,7 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod
#else
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR);
#endif
#else //unix
#else // unix
*fp = fopen((filename.c_str()), mode.c_str());
#endif
@@ -188,7 +170,6 @@ inline bool fopen_s(FILE** fp, const filename_t& filename, const filename_t& mod
return *fp == nullptr;
}
inline int remove(const filename_t &filename)
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
@@ -198,7 +179,7 @@ inline int remove(const filename_t &filename)
#endif
}
inline int rename(const filename_t& filename1, const filename_t& filename2)
inline int rename(const filename_t &filename1, const filename_t &filename2)
{
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wrename(filename1.c_str(), filename2.c_str());
@@ -207,9 +188,8 @@ inline int rename(const filename_t& filename1, const filename_t& filename2)
#endif
}
//Return if file exists
inline bool file_exists(const filename_t& filename)
// Return if file exists
inline bool file_exists(const filename_t &filename)
{
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
@@ -218,28 +198,25 @@ inline bool file_exists(const filename_t& filename)
auto attribs = GetFileAttributesA(filename.c_str());
#endif
return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
#else //common linux/unix all have the stat system call
#else // common linux/unix all have the stat system call
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
#endif
}
//Return file size according to open FILE* object
// Return file size according to open FILE* object
inline size_t filesize(FILE *f)
{
if (f == nullptr)
throw spdlog_ex("Failed getting file size. fd is null");
#if defined ( _WIN32) && !defined(__CYGWIN__)
#if defined(_WIN32) && !defined(__CYGWIN__)
int fd = _fileno(f);
#if _WIN64 //64 bits
#if _WIN64 // 64 bits
struct _stat64 st;
if (_fstat64(fd, &st) == 0)
return st.st_size;
#else //windows 32 bits
#else // windows 32 bits
long ret = _filelength(fd);
if (ret >= 0)
return static_cast<size_t>(ret);
@@ -247,9 +224,9 @@ inline size_t filesize(FILE *f)
#else // unix
int fd = fileno(f);
//64 bits(but not in osx or cygwin, where fstat64 is deprecated)
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st ;
struct stat64 st;
if (fstat64(fd, &st) == 0)
return static_cast<size_t>(st.st_size);
#else // unix 32 bits or cygwin
@@ -261,11 +238,8 @@ inline size_t filesize(FILE *f)
throw spdlog_ex("Failed getting file size from fd", errno);
}
//Return utc offset in minutes or throw spdlog_ex on failure
inline int utc_minutes_offset(const std::tm& tm = details::os::localtime())
// Return utc offset in minutes or throw spdlog_ex on failure
inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
{
#ifdef _WIN32
@@ -291,23 +265,22 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime())
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper
{
static long int calculate_gmt_offset(const std::tm & localtm = details::os::localtime(), const std::tm & gmtm = details::os::gmtime())
static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
{
int local_year = localtm.tm_year + (1900 - 1);
int gmt_year = gmtm.tm_year + (1900 - 1);
long int days = (
// difference in day of year
localtm.tm_yday - gmtm.tm_yday
// difference in day of year
localtm.tm_yday -
gmtm.tm_yday
// + intervening leap days
+ ((local_year >> 2) - (gmt_year >> 2))
- (local_year / 100 - gmt_year / 100)
+ ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
// + intervening leap days
+ ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
// + difference in years * 365 */
+ (long int)(local_year - gmt_year) * 365
);
// + difference in years * 365 */
+ (long int)(local_year - gmt_year) * 365);
long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
@@ -326,16 +299,16 @@ inline int utc_minutes_offset(const std::tm& tm = details::os::localtime())
#endif
}
//Return current thread id as size_t
//It exists because the std::this_thread::get_id() is much slower(especially under VS 2013)
// Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially under VS 2013)
inline size_t _thread_id()
{
#ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId());
#elif __linux__
# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
# define SYS_gettid __NR_gettid
# endif
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
#define SYS_gettid __NR_gettid
#endif
return static_cast<size_t>(syscall(SYS_gettid));
#elif __FreeBSD__
long tid;
@@ -345,25 +318,23 @@ inline size_t _thread_id()
uint64_t tid;
pthread_threadid_np(nullptr, &tid);
return static_cast<size_t>(tid);
#else //Default to standard C++11 (other Unix)
#else // Default to standard C++11 (other Unix)
return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
#endif
}
//Return current thread id as size_t (from thread local storage)
// Return current thread id as size_t (from thread local storage)
inline size_t thread_id()
{
#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt ) || (defined(__clang__) && !__has_feature(cxx_thread_local))
#if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \
(defined(__clang__) && !__has_feature(cxx_thread_local))
return _thread_id();
#else // cache thread id in tls
static thread_local const size_t tid = _thread_id();
return tid;
#endif
}
// This is avoid msvc issue in sleep_for that happens if the clock changes.
// See https://github.com/gabime/spdlog/issues/609
inline void sleep_for_millis(int milliseconds)
@@ -377,21 +348,21 @@ inline void sleep_for_millis(int milliseconds)
// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
#define SPDLOG_FILENAME_T(s) L ## s
inline std::string filename_to_str(const filename_t& filename)
#define SPDLOG_FILENAME_T(s) L##s
inline std::string filename_to_str(const filename_t &filename)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
return c.to_bytes(filename);
}
#else
#define SPDLOG_FILENAME_T(s) s
inline std::string filename_to_str(const filename_t& filename)
inline std::string filename_to_str(const filename_t &filename)
{
return filename;
}
#endif
inline std::string errno_to_string(char[256], char* res)
inline std::string errno_to_string(char[256], char *res)
{
return std::string(res);
}
@@ -417,17 +388,17 @@ inline std::string errno_str(int err_num)
else
return "Unknown error";
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \
((_POSIX_C_SOURCE >= 200112L) && ! defined(_GNU_SOURCE)) // posix version
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \
((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version
if (strerror_r(err_num, buf, buf_size) == 0)
return std::string(buf);
else
return "Unknown error";
#else // gnu version (might not use the given buf, so its retval pointer must be used)
#else // gnu version (might not use the given buf, so its retval pointer must be used)
auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type
return errno_to_string(buf, err); // use overloading to select correct stringify function
return errno_to_string(buf, err); // use overloading to select correct stringify function
#endif
}
@@ -439,10 +410,8 @@ inline int pid()
#else
return static_cast<int>(::getpid());
#endif
}
// Determine if the terminal supports colors
// Source: https://github.com/agauniyal/rang/
inline bool is_color_terminal()
@@ -450,11 +419,8 @@ inline bool is_color_terminal()
#ifdef _WIN32
return true;
#else
static constexpr const char* Terms[] =
{
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm",
"linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"
};
static constexpr const char *Terms[] = {
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
const char *env_p = std::getenv("TERM");
if (env_p == nullptr)
@@ -462,19 +428,15 @@ inline bool is_color_terminal()
return false;
}
static const bool result = std::any_of(
std::begin(Terms), std::end(Terms), [&](const char* term)
{
return std::strstr(env_p, term) != nullptr;
});
static const bool result =
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
return result;
#endif
}
// Detrmine if the terminal attached
// Source: https://github.com/agauniyal/rang/
inline bool in_terminal(FILE* file)
inline bool in_terminal(FILE *file)
{
#ifdef _WIN32
@@ -483,6 +445,4 @@ inline bool in_terminal(FILE* file)
return isatty(fileno(file)) != 0;
#endif
}
} //os
} //details
} //spdlog
}}} // namespace spdlog::details::os

View File

@@ -5,11 +5,12 @@
#pragma once
#include "../formatter.h"
#include "../details/log_msg.h"
#include "../details/os.h"
#include "../fmt/fmt.h"
#include "../formatter.h"
#include <array>
#include <chrono>
#include <ctime>
#include <memory>
@@ -18,17 +19,13 @@
#include <thread>
#include <utility>
#include <vector>
#include <array>
namespace spdlog
{
namespace details
{
namespace spdlog { namespace details {
class flag_formatter
{
public:
virtual ~flag_formatter() = default;
virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0;
virtual void format(details::log_msg &msg, const std::tm &tm_time) = 0;
};
///////////////////////////////////////////////////////////////////////
@@ -36,7 +33,7 @@ public:
///////////////////////////////////////////////////////////////////////
class name_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << *msg.logger_name;
}
@@ -45,7 +42,7 @@ class name_formatter : public flag_formatter
// log level appender
class level_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << level::to_str(msg.level);
}
@@ -54,7 +51,7 @@ class level_formatter : public flag_formatter
// short log level appender
class short_level_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << level::to_short_str(msg.level);
}
@@ -64,74 +61,75 @@ class short_level_formatter : public flag_formatter
// Date time pattern appenders
///////////////////////////////////////////////////////////////////////
static const char* ampm(const tm& t)
static const char *ampm(const tm &t)
{
return t.tm_hour >= 12 ? "PM" : "AM";
}
static int to12h(const tm& t)
static int to12h(const tm &t)
{
return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
}
//Abbreviated weekday name
static const std::string days[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
// Abbreviated weekday name
static const std::string days[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
class a_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << days[tm_time.tm_wday];
}
};
//Full weekday name
static const std::string full_days[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
// Full weekday name
static const std::string full_days[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
class A_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << full_days[tm_time.tm_wday];
}
};
//Abbreviated month
static const std::string months[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
// Abbreviated month
static const std::string months[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"};
class b_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << months[tm_time.tm_mon];
}
};
//Full month name
static const std::string full_months[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
// Full month name
static const std::string full_months[]{
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
class B_formatter : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << full_months[tm_time.tm_mon];
}
};
//write 2 ints separated by sep with padding of 2
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep)
// write 2 ints separated by sep with padding of 2
static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, char sep)
{
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0');
return w;
}
//write 3 ints separated by sep with padding of 2
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep)
// write 3 ints separated by sep with padding of 2
static fmt::MemoryWriter &pad_n_join(fmt::MemoryWriter &w, int v1, int v2, int v3, char sep)
{
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0');
return w;
}
//Date and time representation (Thu Aug 23 15:35:46 2014)
// Date and time representation (Thu Aug 23 15:35:46 2014)
class c_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' ';
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900;
@@ -141,7 +139,7 @@ class c_formatter SPDLOG_FINAL : public flag_formatter
// year - 2 digit
class C_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0');
}
@@ -150,7 +148,7 @@ class C_formatter SPDLOG_FINAL : public flag_formatter
// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
class D_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/');
}
@@ -159,7 +157,7 @@ class D_formatter SPDLOG_FINAL : public flag_formatter
// year - 4 digit
class Y_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << tm_time.tm_year + 1900;
}
@@ -168,7 +166,7 @@ class Y_formatter SPDLOG_FINAL : public flag_formatter
// month 1-12
class m_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0');
}
@@ -177,7 +175,7 @@ class m_formatter SPDLOG_FINAL : public flag_formatter
// day of month 1-31
class d_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0');
}
@@ -186,7 +184,7 @@ class d_formatter SPDLOG_FINAL : public flag_formatter
// hours in 24 format 0-23
class H_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0');
}
@@ -195,7 +193,7 @@ class H_formatter SPDLOG_FINAL : public flag_formatter
// hours in 12 format 1-12
class I_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(to12h(tm_time), 2, '0');
}
@@ -204,7 +202,7 @@ class I_formatter SPDLOG_FINAL : public flag_formatter
// minutes 0-59
class M_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_min, 2, '0');
}
@@ -213,7 +211,7 @@ class M_formatter SPDLOG_FINAL : public flag_formatter
// seconds 0-59
class S_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0');
}
@@ -222,7 +220,7 @@ class S_formatter SPDLOG_FINAL : public flag_formatter
// milliseconds
class e_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
auto duration = msg.time.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;
@@ -233,7 +231,7 @@ class e_formatter SPDLOG_FINAL : public flag_formatter
// microseconds
class f_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
auto duration = msg.time.time_since_epoch();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000000;
@@ -244,7 +242,7 @@ class f_formatter SPDLOG_FINAL : public flag_formatter
// nanoseconds
class F_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
auto duration = msg.time.time_since_epoch();
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % 1000000000;
@@ -254,7 +252,7 @@ class F_formatter SPDLOG_FINAL : public flag_formatter
class E_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
auto duration = msg.time.time_since_epoch();
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
@@ -265,7 +263,7 @@ class E_formatter SPDLOG_FINAL : public flag_formatter
// AM/PM
class p_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
msg.formatted << ampm(tm_time);
}
@@ -274,7 +272,7 @@ class p_formatter SPDLOG_FINAL : public flag_formatter
// 12 hour clock 02:55:02 pm
class r_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time);
}
@@ -283,7 +281,7 @@ class r_formatter SPDLOG_FINAL : public flag_formatter
// 24-hour HH:MM time, equivalent to %H:%M
class R_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':');
}
@@ -292,7 +290,7 @@ class R_formatter SPDLOG_FINAL : public flag_formatter
// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
class T_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':');
}
@@ -305,10 +303,10 @@ public:
const std::chrono::seconds cache_refresh = std::chrono::seconds(5);
z_formatter() = default;
z_formatter(const z_formatter&) = delete;
z_formatter& operator=(const z_formatter&) = delete;
z_formatter(const z_formatter &) = delete;
z_formatter &operator=(const z_formatter &) = delete;
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
#ifdef _WIN32
int total_minutes = get_cached_offset(msg, tm_time);
@@ -334,12 +332,13 @@ public:
msg.formatted << sign;
pad_n_join(msg.formatted, h, m, ':');
}
private:
log_clock::time_point _last_update{ std::chrono::seconds(0) };
int _offset_minutes{ 0 };
log_clock::time_point _last_update{std::chrono::seconds(0)};
int _offset_minutes{0};
std::mutex _mutex;
int get_cached_offset(const log_msg& msg, const std::tm& tm_time)
int get_cached_offset(const log_msg &msg, const std::tm &tm_time)
{
std::lock_guard<std::mutex> l(_mutex);
if (msg.time - _last_update >= cache_refresh)
@@ -354,7 +353,7 @@ private:
// Thread id
class t_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << msg.thread_id;
}
@@ -363,7 +362,7 @@ class t_formatter SPDLOG_FINAL : public flag_formatter
// Current pid
class pid_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << details::os::pid();
}
@@ -372,7 +371,7 @@ class pid_formatter SPDLOG_FINAL : public flag_formatter
// message counter formatter
class i_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << fmt::pad(msg.msg_id, 6, '0');
}
@@ -380,7 +379,7 @@ class i_formatter SPDLOG_FINAL : public flag_formatter
class v_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
}
@@ -389,18 +388,20 @@ class v_formatter SPDLOG_FINAL : public flag_formatter
class ch_formatter SPDLOG_FINAL : public flag_formatter
{
public:
explicit ch_formatter(char ch): _ch(ch)
{}
void format(details::log_msg& msg, const std::tm&) override
explicit ch_formatter(char ch)
: _ch(ch)
{
}
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << _ch;
}
private:
char _ch;
};
//aggregate user chars to display as is
// aggregate user chars to display as is
class aggregate_formatter SPDLOG_FINAL : public flag_formatter
{
public:
@@ -410,10 +411,11 @@ public:
{
_str += ch;
}
void format(details::log_msg& msg, const std::tm&) override
void format(details::log_msg &msg, const std::tm &) override
{
msg.formatted << _str;
}
private:
std::string _str;
};
@@ -422,7 +424,7 @@ private:
// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
class full_formatter SPDLOG_FINAL : public flag_formatter
{
void format(details::log_msg& msg, const std::tm& tm_time) override
void format(details::log_msg &msg, const std::tm &tm_time) override
{
#ifndef SPDLOG_NO_DATETIME
auto duration = msg.time.time_since_epoch();
@@ -441,7 +443,6 @@ class full_formatter SPDLOG_FINAL : public flag_formatter
level::to_str(msg.level),
msg.raw.str());*/
// Faster (albeit uglier) way to format the line (5.6 million lines/sec under 10 threads)
msg.formatted << '[' << static_cast<unsigned int>(tm_time.tm_year + 1900) << '-'
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_mon + 1), 2, '0') << '-'
@@ -451,7 +452,7 @@ class full_formatter SPDLOG_FINAL : public flag_formatter
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_sec), 2, '0') << '.'
<< fmt::pad(static_cast<unsigned int>(millis), 3, '0') << "] ";
//no datetime needed
// no datetime needed
#else
(void)tm_time;
#endif
@@ -465,21 +466,18 @@ class full_formatter SPDLOG_FINAL : public flag_formatter
}
};
}
}
}} // namespace spdlog::details
///////////////////////////////////////////////////////////////////////////////
// pattern_formatter inline impl
///////////////////////////////////////////////////////////////////////////////
inline spdlog::pattern_formatter::pattern_formatter(const std::string& pattern, pattern_time_type pattern_time, std::string eol) :
_eol(std::move(eol)),
_pattern_time(pattern_time)
inline spdlog::pattern_formatter::pattern_formatter(const std::string &pattern, pattern_time_type pattern_time, std::string eol)
: _eol(std::move(eol))
, _pattern_time(pattern_time)
{
compile_pattern(pattern);
}
inline void spdlog::pattern_formatter::compile_pattern(const std::string& pattern)
inline void spdlog::pattern_formatter::compile_pattern(const std::string &pattern)
{
auto end = pattern.end();
std::unique_ptr<details::aggregate_formatter> user_chars;
@@ -487,7 +485,7 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter
{
if (*it == '%')
{
if (user_chars) //append user chars found so far
if (user_chars) // append user chars found so far
_formatters.push_back(std::move(user_chars));
if (++it != end)
handle_flag(*it);
@@ -501,11 +499,10 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter
user_chars->add_ch(*it);
}
}
if (user_chars) //append raw chars found so far
if (user_chars) // append raw chars found so far
{
_formatters.push_back(std::move(user_chars));
}
}
inline void spdlog::pattern_formatter::handle_flag(char flag)
{
@@ -524,105 +521,105 @@ inline void spdlog::pattern_formatter::handle_flag(char flag)
_formatters.emplace_back(new details::short_level_formatter());
break;
case('t'):
case ('t'):
_formatters.emplace_back(new details::t_formatter());
break;
case('v'):
case ('v'):
_formatters.emplace_back(new details::v_formatter());
break;
case('a'):
case ('a'):
_formatters.emplace_back(new details::a_formatter());
break;
case('A'):
case ('A'):
_formatters.emplace_back(new details::A_formatter());
break;
case('b'):
case('h'):
case ('b'):
case ('h'):
_formatters.emplace_back(new details::b_formatter());
break;
case('B'):
case ('B'):
_formatters.emplace_back(new details::B_formatter());
break;
case('c'):
case ('c'):
_formatters.emplace_back(new details::c_formatter());
break;
case('C'):
case ('C'):
_formatters.emplace_back(new details::C_formatter());
break;
case('Y'):
case ('Y'):
_formatters.emplace_back(new details::Y_formatter());
break;
case('D'):
case('x'):
case ('D'):
case ('x'):
_formatters.emplace_back(new details::D_formatter());
break;
case('m'):
case ('m'):
_formatters.emplace_back(new details::m_formatter());
break;
case('d'):
case ('d'):
_formatters.emplace_back(new details::d_formatter());
break;
case('H'):
case ('H'):
_formatters.emplace_back(new details::H_formatter());
break;
case('I'):
case ('I'):
_formatters.emplace_back(new details::I_formatter());
break;
case('M'):
case ('M'):
_formatters.emplace_back(new details::M_formatter());
break;
case('S'):
case ('S'):
_formatters.emplace_back(new details::S_formatter());
break;
case('e'):
case ('e'):
_formatters.emplace_back(new details::e_formatter());
break;
case('f'):
case ('f'):
_formatters.emplace_back(new details::f_formatter());
break;
case('F'):
case ('F'):
_formatters.emplace_back(new details::F_formatter());
break;
case('E'):
case ('E'):
_formatters.emplace_back(new details::E_formatter());
break;
case('p'):
case ('p'):
_formatters.emplace_back(new details::p_formatter());
break;
case('r'):
case ('r'):
_formatters.emplace_back(new details::r_formatter());
break;
case('R'):
case ('R'):
_formatters.emplace_back(new details::R_formatter());
break;
case('T'):
case('X'):
case ('T'):
case ('X'):
_formatters.emplace_back(new details::T_formatter());
break;
case('z'):
case ('z'):
_formatters.emplace_back(new details::z_formatter());
break;
@@ -634,19 +631,18 @@ inline void spdlog::pattern_formatter::handle_flag(char flag)
_formatters.emplace_back(new details::pid_formatter());
break;
case ('i'):
_formatters.emplace_back(new details::i_formatter());
break;
default: //Unknown flag appears as is
default: // Unknown flag appears as is
_formatters.emplace_back(new details::ch_formatter('%'));
_formatters.emplace_back(new details::ch_formatter(flag));
break;
}
}
inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg)
inline std::tm spdlog::pattern_formatter::get_time(details::log_msg &msg)
{
if (_pattern_time == pattern_time_type::local)
{
@@ -655,7 +651,7 @@ inline std::tm spdlog::pattern_formatter::get_time(details::log_msg& msg)
return details::os::gmtime(log_clock::to_time_t(msg.time));
}
inline void spdlog::pattern_formatter::format(details::log_msg& msg)
inline void spdlog::pattern_formatter::format(details::log_msg &msg)
{
#ifndef SPDLOG_NO_DATETIME
@@ -667,6 +663,6 @@ inline void spdlog::pattern_formatter::format(details::log_msg& msg)
{
f->format(msg, tm_time);
}
//write eol
// write eol
msg.formatted.write(_eol.data(), _eol.size());
}

View File

@@ -10,10 +10,10 @@
// If user requests a non existing logger, nullptr will be returned
// This class is thread safe
#include "../details/null_mutex.h"
#include "../logger.h"
#include "../async_logger.h"
#include "../common.h"
#include "../details/null_mutex.h"
#include "../logger.h"
#include <chrono>
#include <functional>
@@ -22,16 +22,12 @@
#include <string>
#include <unordered_map>
namespace spdlog
{
namespace details
{
template <class Mutex>
class registry_t
namespace spdlog { namespace details {
template <class Mutex> class registry_t
{
public:
registry_t<Mutex>(const registry_t<Mutex>&) = delete;
registry_t<Mutex>& operator=(const registry_t<Mutex>&) = delete;
registry_t<Mutex>(const registry_t<Mutex> &) = delete;
registry_t<Mutex> &operator=(const registry_t<Mutex> &) = delete;
void register_logger(std::shared_ptr<logger> logger)
{
@@ -41,21 +37,21 @@ public:
_loggers[logger_name] = logger;
}
std::shared_ptr<logger> get(const std::string& logger_name)
std::shared_ptr<logger> get(const std::string &logger_name)
{
std::lock_guard<Mutex> lock(_mutex);
auto found = _loggers.find(logger_name);
return found == _loggers.end() ? nullptr : found->second;
}
template<class It>
std::shared_ptr<logger> create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end)
template <class It> std::shared_ptr<logger> create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end)
{
std::lock_guard<Mutex> lock(_mutex);
throw_if_exists(logger_name);
std::shared_ptr<logger> new_logger;
if (_async_mode)
new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb);
new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy,
_worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb);
else
new_logger = std::make_shared<logger>(logger_name, sinks_begin, sinks_end);
@@ -68,18 +64,21 @@ public:
new_logger->set_level(_level);
new_logger->flush_on(_flush_level);
//Add to registry
// Add to registry
_loggers[logger_name] = new_logger;
return new_logger;
}
template<class It>
std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, const It& sinks_begin, const It& sinks_end)
template <class It>
std::shared_ptr<async_logger> create_async(const std::string &logger_name, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb, const It &sinks_begin,
const It &sinks_end)
{
std::lock_guard<Mutex> lock(_mutex);
throw_if_exists(logger_name);
auto new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb);
auto new_logger = std::make_shared<async_logger>(
logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb);
if (_formatter)
new_logger->set_formatter(_formatter);
@@ -90,7 +89,7 @@ public:
new_logger->set_level(_level);
new_logger->flush_on(_flush_level);
//Add to registry
// Add to registry
_loggers[logger_name] = new_logger;
return new_logger;
}
@@ -102,7 +101,7 @@ public:
fun(l.second);
}
void drop(const std::string& logger_name)
void drop(const std::string &logger_name)
{
std::lock_guard<Mutex> lock(_mutex);
_loggers.erase(logger_name);
@@ -114,46 +113,51 @@ public:
_loggers.clear();
}
std::shared_ptr<logger> create(const std::string& logger_name, sinks_init_list sinks)
std::shared_ptr<logger> create(const std::string &logger_name, sinks_init_list sinks)
{
return create(logger_name, sinks.begin(), sinks.end());
}
std::shared_ptr<logger> create(const std::string& logger_name, sink_ptr sink)
std::shared_ptr<logger> create(const std::string &logger_name, sink_ptr sink)
{
return create(logger_name, { sink });
return create(logger_name, {sink});
}
std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, sinks_init_list sinks)
std::shared_ptr<async_logger> create_async(const std::string &logger_name, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb, sinks_init_list sinks)
{
return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end());
return create_async(
logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks.begin(), sinks.end());
}
std::shared_ptr<async_logger> create_async(const std::string& logger_name, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb, sink_ptr sink)
std::shared_ptr<async_logger> create_async(const std::string &logger_name, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb, sink_ptr sink)
{
return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, { sink });
return create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, {sink});
}
void formatter(formatter_ptr f)
{
std::lock_guard<Mutex> lock(_mutex);
_formatter = f;
for (auto& l : _loggers)
for (auto &l : _loggers)
l.second->set_formatter(_formatter);
}
void set_pattern(const std::string& pattern)
void set_pattern(const std::string &pattern)
{
std::lock_guard<Mutex> lock(_mutex);
_formatter = std::make_shared<pattern_formatter>(pattern);
for (auto& l : _loggers)
for (auto &l : _loggers)
l.second->set_formatter(_formatter);
}
void set_level(level::level_enum log_level)
{
std::lock_guard<Mutex> lock(_mutex);
for (auto& l : _loggers)
for (auto &l : _loggers)
l.second->set_level(log_level);
_level = log_level;
}
@@ -161,19 +165,20 @@ public:
void flush_on(level::level_enum log_level)
{
std::lock_guard<Mutex> lock(_mutex);
for (auto& l : _loggers)
for (auto &l : _loggers)
l.second->flush_on(log_level);
_flush_level = log_level;
}
void set_error_handler(log_err_handler handler)
{
for (auto& l : _loggers)
for (auto &l : _loggers)
l.second->set_error_handler(handler);
_err_handler = handler;
}
void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
{
std::lock_guard<Mutex> lock(_mutex);
_async_mode = true;
@@ -190,7 +195,7 @@ public:
_async_mode = false;
}
static registry_t<Mutex>& instance()
static registry_t<Mutex> &instance()
{
static registry_t<Mutex> s_instance;
return s_instance;
@@ -206,7 +211,7 @@ private:
}
Mutex _mutex;
std::unordered_map <std::string, std::shared_ptr<logger>> _loggers;
std::unordered_map<std::string, std::shared_ptr<logger>> _loggers;
formatter_ptr _formatter;
level::level_enum _level = level::info;
level::level_enum _flush_level = level::off;
@@ -225,5 +230,4 @@ using registry = registry_t<spdlog::details::null_mutex>;
using registry = registry_t<std::mutex>;
#endif
}
}
}} // namespace spdlog::details

View File

@@ -8,10 +8,10 @@
//
// Global registry functions
//
#include "../spdlog.h"
#include "../details/registry.h"
#include "../sinks/file_sinks.h"
#include "../sinks/stdout_sinks.h"
#include "../spdlog.h"
#ifdef SPDLOG_ENABLE_SYSLOG
#include "../sinks/syslog_sink.h"
#endif
@@ -22,7 +22,6 @@
#include "../sinks/ansicolor_sink.h"
#endif
#ifdef __ANDROID__
#include "../sinks/android_sink.h"
#endif
@@ -37,7 +36,7 @@ inline void spdlog::register_logger(std::shared_ptr<logger> logger)
return details::registry::instance().register_logger(std::move(logger));
}
inline std::shared_ptr<spdlog::logger> spdlog::get(const std::string& name)
inline std::shared_ptr<spdlog::logger> spdlog::get(const std::string &name)
{
return details::registry::instance().get(name);
}
@@ -48,58 +47,61 @@ inline void spdlog::drop(const std::string &name)
}
// Create multi/single threaded simple file logger
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_mt(const std::string& logger_name, const filename_t& filename, bool truncate)
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate)
{
return create<spdlog::sinks::simple_file_sink_mt>(logger_name, filename, truncate);
}
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_st(const std::string& logger_name, const filename_t& filename, bool truncate)
inline std::shared_ptr<spdlog::logger> spdlog::basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate)
{
return create<spdlog::sinks::simple_file_sink_st>(logger_name, filename, truncate);
}
// Create multi/single threaded rotating file logger
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_mt(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files)
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_mt(
const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files)
{
return create<spdlog::sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files);
}
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_st(const std::string& logger_name, const filename_t& filename, size_t max_file_size, size_t max_files)
inline std::shared_ptr<spdlog::logger> spdlog::rotating_logger_st(
const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files)
{
return create<spdlog::sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files);
}
// Create file logger which creates new file at midnight):
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_mt(const std::string& logger_name, const filename_t& filename, int hour, int minute)
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_mt(
const std::string &logger_name, const filename_t &filename, int hour, int minute)
{
return create<spdlog::sinks::daily_file_sink_mt>(logger_name, filename, hour, minute);
}
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(const std::string& logger_name, const filename_t& filename, int hour, int minute)
inline std::shared_ptr<spdlog::logger> spdlog::daily_logger_st(
const std::string &logger_name, const filename_t &filename, int hour, int minute)
{
return create<spdlog::sinks::daily_file_sink_st>(logger_name, filename, hour, minute);
}
//
// stdout/stderr loggers
//
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_mt(const std::string &logger_name)
{
return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_mt::instance());
}
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_logger_st(const std::string &logger_name)
{
return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stdout_sink_st::instance());
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_mt(const std::string &logger_name)
{
return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_mt::instance());
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::string &logger_name)
{
return spdlog::details::registry::instance().create(logger_name, spdlog::sinks::stderr_sink_st::instance());
}
@@ -109,52 +111,51 @@ inline std::shared_ptr<spdlog::logger> spdlog::stderr_logger_st(const std::strin
//
#if defined _WIN32 && !defined(__cplusplus_winrt)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_st>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::wincolor_stderr_sink_mt>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::wincolor_stderr_sink_st>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
#else //ansi terminal colors
#else // ansi terminal colors
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stdout_color_st(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_st>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::ansicolor_stderr_sink_mt>();
return spdlog::details::registry::instance().create(logger_name, sink);
}
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string& logger_name)
inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string &logger_name)
{
auto sink = std::make_shared<spdlog::sinks::ansicolor_stderr_sink_st>();
return spdlog::details::registry::instance().create(logger_name, sink);
@@ -163,60 +164,70 @@ inline std::shared_ptr<spdlog::logger> spdlog::stderr_color_st(const std::string
#ifdef SPDLOG_ENABLE_SYSLOG
// Create syslog logger
inline std::shared_ptr<spdlog::logger> spdlog::syslog_logger(const std::string& logger_name, const std::string& syslog_ident, int syslog_option, int syslog_facility)
inline std::shared_ptr<spdlog::logger> spdlog::syslog_logger(
const std::string &logger_name, const std::string &syslog_ident, int syslog_option, int syslog_facility)
{
return create<spdlog::sinks::syslog_sink>(logger_name, syslog_ident, syslog_option, syslog_facility);
}
#endif
#ifdef __ANDROID__
inline std::shared_ptr<spdlog::logger> spdlog::android_logger(const std::string& logger_name, const std::string& tag)
inline std::shared_ptr<spdlog::logger> spdlog::android_logger(const std::string &logger_name, const std::string &tag)
{
return create<spdlog::sinks::android_sink>(logger_name, tag);
}
#endif
// Create and register a logger a single sink
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const spdlog::sink_ptr& sink)
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string &logger_name, const spdlog::sink_ptr &sink)
{
return details::registry::instance().create(logger_name, sink);
}
//Create logger with multiple sinks
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, spdlog::sinks_init_list sinks)
// Create logger with multiple sinks
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string &logger_name, spdlog::sinks_init_list sinks)
{
return details::registry::instance().create(logger_name, sinks);
}
template <typename Sink, typename... Args>
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, Args... args)
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string &logger_name, Args... args)
{
sink_ptr sink = std::make_shared<Sink>(args...);
return details::registry::instance().create(logger_name, { sink });
return details::registry::instance().create(logger_name, {sink});
}
template<class It>
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string& logger_name, const It& sinks_begin, const It& sinks_end)
template <class It>
inline std::shared_ptr<spdlog::logger> spdlog::create(const std::string &logger_name, const It &sinks_begin, const It &sinks_end)
{
return details::registry::instance().create(logger_name, sinks_begin, sinks_end);
}
// Create and register an async logger with a single sink
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string& logger_name, const sink_ptr& sink, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string &logger_name, const sink_ptr &sink, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
{
return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink);
return details::registry::instance().create_async(
logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sink);
}
// Create and register an async logger with multiple sinks
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string& logger_name, sinks_init_list sinks, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb )
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string &logger_name, sinks_init_list sinks, size_t queue_size,
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
{
return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks);
return details::registry::instance().create_async(
logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks);
}
template<class It>
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string& logger_name, const It& sinks_begin, const It& sinks_end, size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
template <class It>
inline std::shared_ptr<spdlog::logger> spdlog::create_async(const std::string &logger_name, const It &sinks_begin, const It &sinks_end,
size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms, const std::function<void()> &worker_teardown_cb)
{
return details::registry::instance().create_async(logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end);
return details::registry::instance().create_async(
logger_name, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb, sinks_begin, sinks_end);
}
inline void spdlog::set_formatter(spdlog::formatter_ptr f)
@@ -224,7 +235,7 @@ inline void spdlog::set_formatter(spdlog::formatter_ptr f)
details::registry::instance().formatter(std::move(f));
}
inline void spdlog::set_pattern(const std::string& format_string)
inline void spdlog::set_pattern(const std::string &format_string)
{
return details::registry::instance().set_pattern(format_string);
}
@@ -244,7 +255,9 @@ inline void spdlog::set_error_handler(log_err_handler handler)
return details::registry::instance().set_error_handler(std::move(handler));
}
inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy,
const std::function<void()> &worker_warmup_cb, const std::chrono::milliseconds &flush_interval_ms,
const std::function<void()> &worker_teardown_cb)
{
details::registry::instance().set_async_mode(queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb);
}