clang format

This commit is contained in:
gabime 2018-07-21 23:48:07 +03:00
parent a96b4d7529
commit 9e4925eff0
35 changed files with 197 additions and 152 deletions

View File

@ -48,9 +48,11 @@ int main(int argc, char *argv[])
if (argc > 3) if (argc > 3)
queue_size = atoi(argv[3]); queue_size = atoi(argv[3]);
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "Single thread, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true); auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true);
bench(howmany, basic_st); bench(howmany, basic_st);
@ -63,9 +65,11 @@ int main(int argc, char *argv[])
bench(howmany, spdlog::create<null_sink_st>("null_st")); bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n"; cout << "\n****************************************************************"
"***************\n";
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true); auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, basic_mt, threads); bench_mt(howmany, basic_mt, threads);
@ -77,9 +81,11 @@ int main(int argc, char *argv[])
bench_mt(howmany, daily_mt, threads); bench_mt(howmany, daily_mt, threads);
bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads); bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads);
cout << "\n*******************************************************************************\n"; cout << "\n****************************************************************"
"***************\n";
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl; cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl;
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {

View File

@ -41,9 +41,11 @@ int main(int, char *[])
try try
{ {
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
cout << "Single thread\n"; cout << "Single thread\n";
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true); auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true);
bench(howmany, basic_st); bench(howmany, basic_st);
@ -56,9 +58,11 @@ int main(int, char *[])
bench(howmany, spdlog::create<null_sink_st>("null_st")); bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n"; cout << "\n****************************************************************"
"***************\n";
cout << threads << " threads sharing same logger\n"; cout << threads << " threads sharing same logger\n";
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true); auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, basic_mt, threads); bench_mt(howmany, basic_mt, threads);
@ -70,9 +74,11 @@ int main(int, char *[])
bench_mt(howmany, daily_mt, threads); bench_mt(howmany, daily_mt, threads);
bench(howmany, spdlog::create<null_sink_st>("null_mt")); bench(howmany, spdlog::create<null_sink_st>("null_mt"));
cout << "\n*******************************************************************************\n"; cout << "\n****************************************************************"
"***************\n";
cout << "async logging.. " << threads << " threads sharing same logger\n"; cout << "async logging.. " << threads << " threads sharing same logger\n";
cout << "*******************************************************************************\n"; cout << "******************************************************************"
"*************\n";
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {

View File

@ -50,9 +50,7 @@ int main(int, char *[])
spdlog::flush_every(std::chrono::seconds(3)); spdlog::flush_every(std::chrono::seconds(3));
// apply some function on all registered loggers // apply some function on all registered loggers
spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
l->info("End of example.");
});
// Release and close all loggers // Release and close all loggers
spdlog::drop_all(); spdlog::drop_all();
@ -178,9 +176,7 @@ void user_defined_example()
void err_handler_example() void err_handler_example()
{ {
// can be set globally or per logger(logger->set_error_handler(..)) // can be set globally or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** ERROR HANDLER EXAMPLE ***: {}", msg); });
spdlog::get("console")->error("*** ERROR HANDLER EXAMPLE ***: {}", msg);
});
spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
} }

View File

@ -9,10 +9,13 @@
// //
// Async logging using global thread pool // Async logging using global thread pool
// All loggers created here share same global thread pool. // All loggers created here share same global thread pool.
// Each log message is pushed to a queue along withe a shared pointer to the logger. // Each log message is pushed to a queue along withe a shared pointer to the
// If a logger deleted while having pending messages in the queue, it's actual destruction will defer // logger.
// If a logger deleted while having pending messages in the queue, it's actual
// destruction will defer
// until all its messages are processed by the thread pool. // until all its messages are processed by the thread pool.
// This is because each message in the queue holds a shared_ptr to the originating logger. // This is because each message in the queue holds a shared_ptr to the
// originating logger.
#include "spdlog/async_logger.h" #include "spdlog/async_logger.h"
#include "spdlog/details/registry.h" #include "spdlog/details/registry.h"
@ -27,7 +30,8 @@ static const size_t default_async_q_size = 8192;
} }
// async logger factory - creates async loggers backed with thread pool. // async logger factory - creates async loggers backed with thread pool.
// if a global thread pool doesn't already exist, create it with default queue size of 8192 items and single thread. // if a global thread pool doesn't already exist, create it with default queue
// size of 8192 items and single thread.
template<async_overflow_policy OverflowPolicy = async_overflow_policy::block> template<async_overflow_policy OverflowPolicy = async_overflow_policy::block>
struct async_factory_impl struct async_factory_impl
{ {
@ -54,7 +58,6 @@ struct async_factory_impl
using async_factory = async_factory_impl<async_overflow_policy::block>; using async_factory = async_factory_impl<async_overflow_policy::block>;
using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>; using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
template<typename Sink, typename... SinkArgs> template<typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create_async(const std::string &logger_name, SinkArgs &&... sink_args) inline std::shared_ptr<spdlog::logger> create_async(const std::string &logger_name, SinkArgs &&... sink_args)
{ {
@ -67,7 +70,6 @@ inline std::shared_ptr<spdlog::logger> create_async_nb(const std::string &logger
return async_factory_nonblock::create<Sink>(logger_name, std::forward<SinkArgs>(sink_args)...); return async_factory_nonblock::create<Sink>(logger_name, std::forward<SinkArgs>(sink_args)...);
} }
// set global thread pool. // set global thread pool.
inline void init_thread_pool(size_t q_size, size_t thread_count) inline void init_thread_pool(size_t q_size, size_t thread_count)
{ {

View File

@ -5,15 +5,19 @@
#pragma once #pragma once
// Very fast asynchronous logger (millions of logs per second on an average desktop) // Very fast asynchronous logger (millions of logs per second on an average
// Uses pre allocated lockfree queue for maximum throughput even under large number of threads. // desktop)
// Uses pre allocated lockfree queue for maximum throughput even under large
// number of threads.
// Creates a single back thread to pop messages from the queue and log them. // Creates a single back thread to pop messages from the queue and log them.
// //
// Upon each log write the logger: // Upon each log write the logger:
// 1. Checks if its log level is enough to log the message // 1. Checks if its log level is enough to log the message
// 2. Push a new copy of the message to a queue (or block the caller until space is available in the queue) // 2. Push a new copy of the message to a queue (or block the caller until
// space is available in the queue)
// 3. will throw spdlog_ex upon log exceptions // 3. will throw spdlog_ex upon log exceptions
// Upon destruction, logs all remaining messages in the queue before destructing.. // Upon destruction, logs all remaining messages in the queue before
// destructing..
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/logger.h" #include "spdlog/logger.h"
@ -28,7 +32,8 @@ namespace spdlog {
enum class async_overflow_policy enum class async_overflow_policy
{ {
block, // Block until message can be enqueued block, // Block until message can be enqueued
overrun_oldest // Discard oldest message in the queue if full when trying to add new item. overrun_oldest // Discard oldest message in the queue if full when trying to
// add new item.
}; };
namespace details { namespace details {

View File

@ -70,7 +70,6 @@ using level_t = details::null_atomic_int;
using level_t = std::atomic<int>; using level_t = std::atomic<int>;
#endif #endif
// Log level enum // Log level enum
namespace level { namespace level {
enum level_enum enum level_enum
@ -121,8 +120,6 @@ inline spdlog::level::level_enum from_str(const std::string &name)
using level_hasher = std::hash<int>; using level_hasher = std::hash<int>;
} // namespace level } // namespace level
// //
// Pattern time - specific time getting to use for pattern_formatter. // Pattern time - specific time getting to use for pattern_formatter.
// local time by default // local time by default

View File

@ -15,16 +15,16 @@
#include <string> #include <string>
template<typename It> template<typename It>
inline spdlog::async_logger::async_logger(std::string logger_name, const It &begin, const It &end, inline spdlog::async_logger::async_logger(
std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, const It &begin, const It &end, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: logger(std::move(logger_name), begin, end) : logger(std::move(logger_name), begin, end)
, thread_pool_(tp) , thread_pool_(tp)
, overflow_policy_(overflow_policy) , overflow_policy_(overflow_policy)
{ {
} }
inline spdlog::async_logger::async_logger(std::string logger_name, sinks_init_list sinks_list, inline spdlog::async_logger::async_logger(
std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), tp, overflow_policy) : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), tp, overflow_policy)
{ {
} }

View File

@ -8,7 +8,6 @@
#include "stdio.h" #include "stdio.h"
#include <mutex> #include <mutex>
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct console_stdout struct console_stdout

View File

@ -6,7 +6,8 @@
#pragma once #pragma once
// Helper class for file sink // Helper class for file sink
// When failing to open a file, retry several times(5) with small delay between the tries(10 ms) // When failing to open a file, retry several times(5) with small delay between
// the tries(10 ms)
// Throw spdlog_ex exception on errors // Throw spdlog_ex exception on errors
#include "../details/log_msg.h" #include "../details/log_msg.h"
@ -126,7 +127,8 @@ public:
{ {
auto ext_index = fname.rfind('.'); auto ext_index = fname.rfind('.');
// no valid extension found - return whole path and empty string as extension // no valid extension found - return whole path and empty string as
// extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
{ {
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());

View File

@ -17,7 +17,8 @@ inline spdlog::logger::logger(std::string logger_name, const It &begin, const It
, level_(level::info) , level_(level::info)
, flush_level_(level::off) , flush_level_(level::off)
, last_err_time_(0) , last_err_time_(0)
, msg_counter_(1) // message counter will start from 1. 0-message id will be reserved for controll messages , 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); };
} }
@ -286,7 +287,8 @@ 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 // 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)
{ {

View File

@ -7,8 +7,10 @@
// multi producer-multi consumer blocking queue. // multi producer-multi consumer blocking queue.
// enqueue(..) - will block until room found to put the new message. // enqueue(..) - will block until room found to put the new message.
// enqueue_nowait(..) - will return immediately with false if no room left in the queue. // enqueue_nowait(..) - will return immediately with false if no room left in
// dequeue_for(..) - will block until the queue is not empty or timeout have passed. // the queue.
// dequeue_for(..) - will block until the queue is not empty or timeout have
// passed.
#include "spdlog/details/circular_q.h" #include "spdlog/details/circular_q.h"

View File

@ -321,7 +321,8 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
} }
// Return current thread id as size_t // Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially under VS 2013) // It exists because the std::this_thread::get_id() is much slower(especially
// under VS 2013)
inline size_t _thread_id() inline size_t _thread_id()
{ {
#ifdef _WIN32 #ifdef _WIN32

View File

@ -120,7 +120,8 @@ class c_formatter SPDLOG_FINAL : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
// fmt::format_to(dest, "{} {} {} ", days[tm_time.tm_wday], months[tm_time.tm_mon], tm_time.tm_mday); // fmt::format_to(dest, "{} {} {} ", days[tm_time.tm_wday],
// months[tm_time.tm_mon], tm_time.tm_mday);
// date // date
fmt_helper::append_str(days[tm_time.tm_wday], dest); fmt_helper::append_str(days[tm_time.tm_wday], dest);
dest.push_back(' '); dest.push_back(' ');
@ -308,7 +309,8 @@ class T_formatter SPDLOG_FINAL : public flag_formatter
{ {
void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override void format(const details::log_msg &, const std::tm &tm_time, fmt::memory_buffer &dest) override
{ {
// fmt::format_to(dest, "{:02}:{:02}:{:02}", tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec); // fmt::format_to(dest, "{:02}:{:02}:{:02}", tm_time.tm_hour,
// tm_time.tm_min, tm_time.tm_sec);
fmt_helper::pad2(tm_time.tm_hour, dest); fmt_helper::pad2(tm_time.tm_hour, dest);
dest.push_back(':'); dest.push_back(':');
fmt_helper::pad2(tm_time.tm_min, dest); fmt_helper::pad2(tm_time.tm_min, dest);
@ -539,8 +541,8 @@ private:
class pattern_formatter SPDLOG_FINAL : public formatter class pattern_formatter SPDLOG_FINAL : public formatter
{ {
public: public:
explicit pattern_formatter(std::string pattern, pattern_time_type time_type = pattern_time_type::local, explicit pattern_formatter(
std::string eol = spdlog::details::os::default_eol) std::string pattern, pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol)
: eol_(std::move(eol)) : eol_(std::move(eol))
, pattern_time_type_(time_type) , pattern_time_type_(time_type)
, last_log_secs_(0) , last_log_secs_(0)

View File

@ -12,14 +12,13 @@
// creates the thread on construction. // creates the thread on construction.
// stops and joins the thread on destruction. // stops and joins the thread on destruction.
#include <mutex>
#include <atomic> #include <atomic>
#include <condition_variable>
#include <chrono> #include <chrono>
#include <condition_variable>
#include <functional> #include <functional>
#include <mutex>
namespace spdlog namespace spdlog {
{
namespace details { namespace details {
class periodic_worker class periodic_worker
@ -34,16 +33,14 @@ public:
return; return;
} }
active_ = true; active_ = true;
flusher_thread_ = std::thread([callback_fun, interval, this]() flusher_thread_ = std::thread([callback_fun, interval, this]() {
{
using std::chrono::steady_clock; using std::chrono::steady_clock;
auto last_flush_tp = steady_clock::now(); auto last_flush_tp = steady_clock::now();
for (;;) for (;;)
{ {
std::unique_lock<std::mutex> lock(this->mutex_); std::unique_lock<std::mutex> lock(this->mutex_);
this->cv_.wait_for(lock, interval, [callback_fun, interval, last_flush_tp, this] this->cv_.wait_for(lock, interval, [callback_fun, interval, last_flush_tp, this] {
{
return !this->active_ || (steady_clock::now() - last_flush_tp) >= interval; return !this->active_ || (steady_clock::now() - last_flush_tp) >= interval;
}); });
if (!this->active_) if (!this->active_)
@ -76,5 +73,5 @@ private:
std::mutex mutex_; std::mutex mutex_;
std::condition_variable cv_; std::condition_variable cv_;
}; };
} } // namespace details
} } // namespace spdlog

View File

@ -11,8 +11,8 @@
// This class is thread safe // This class is thread safe
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/logger.h"
#include "spdlog/details/periodic_worker.h" #include "spdlog/details/periodic_worker.h"
#include "spdlog/logger.h"
#include <chrono> #include <chrono>
#include <functional> #include <functional>

View File

@ -114,10 +114,12 @@ public:
thread_pool(size_t q_max_items, size_t threads_n) thread_pool(size_t q_max_items, size_t threads_n)
: q_(q_max_items) : q_(q_max_items)
{ {
// std::cout << "thread_pool() q_size_bytes: " << q_size_bytes << "\tthreads_n: " << threads_n << std::endl; // std::cout << "thread_pool() q_size_bytes: " << q_size_bytes <<
// "\tthreads_n: " << threads_n << std::endl;
if (threads_n == 0 || threads_n > 1000) if (threads_n == 0 || threads_n > 1000)
{ {
throw spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid range is 1-1000)"); throw spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
"range is 1-1000)");
} }
for (size_t i = 0; i < threads_n; i++) for (size_t i = 0; i < threads_n; i++)
{ {
@ -175,13 +177,12 @@ private:
void worker_loop_() void worker_loop_()
{ {
while (process_next_msg_()) while (process_next_msg_()) {};
{
};
} }
// process next message in the queue // process next message in the queue
// return true if this thread should still be active (while no terminate msg was received) // return true if this thread should still be active (while no terminate msg
// was received)
bool process_next_msg_() bool process_next_msg_()
{ {
async_msg incoming_async_msg; async_msg incoming_async_msg;

View File

@ -1233,7 +1233,8 @@ const long long format_arg_store<Context, Args...>::TYPES = get_types();
/** /**
\rst \rst
Constructs an `~fmt::format_arg_store` object that contains references to Constructs an `~fmt::format_arg_store` object that contains references to
arguments and can be implicitly converted to `~fmt::format_args`. `Context` can arguments and can be implicitly converted to `~fmt::format_args`. `Context`
can
be omitted in which case it defaults to `~fmt::context`. be omitted in which case it defaults to `~fmt::context`.
\endrst \endrst
*/ */
@ -1536,7 +1537,8 @@ inline void print(std::FILE *f, string_view format_str, const Args &... args)
vprint(f, format_str, as); vprint(f, format_str, as);
} }
/** /**
Prints formatted data to the file *f* which should be in wide-oriented mode set Prints formatted data to the file *f* which should be in wide-oriented mode
set
via ``fwide(f, 1)`` or ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. via ``fwide(f, 1)`` or ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows.
*/ */
template<typename... Args> template<typename... Args>

View File

@ -320,7 +320,8 @@ FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent)
int index = static_cast<int>(std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10)); int index = static_cast<int>(std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10));
// Decimal exponent of the first (smallest) cached power of 10. // Decimal exponent of the first (smallest) cached power of 10.
const int first_dec_exp = -348; const int first_dec_exp = -348;
// Difference between two consecutive decimal exponents in cached powers of 10. // Difference between two consecutive decimal exponents in cached powers of
// 10.
const int dec_exp_step = 8; const int dec_exp_step = 8;
index = (index - first_dec_exp - 1) / dec_exp_step + 1; index = (index - first_dec_exp - 1) / dec_exp_step + 1;
pow10_exponent = first_dec_exp + index * dec_exp_step; pow10_exponent = first_dec_exp + index * dec_exp_step;

View File

@ -388,7 +388,8 @@ inline fp operator-(fp x, fp y)
} }
// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest // Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest
// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be normalized. // with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be
// normalized.
fp operator*(fp x, fp y); fp operator*(fp x, fp y);
// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its // Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
@ -4305,7 +4306,8 @@ inline format_to_n_result<OutputIt> vformat_to_n(OutputIt out, std::size_t n, st
/** /**
\rst \rst
Formats arguments, writes up to ``n`` characters of the result to the output Formats arguments, writes up to ``n`` characters of the result to the output
iterator ``out`` and returns the total output size and the iterator past the end iterator ``out`` and returns the total output size and the iterator past the
end
of the output range. of the output range.
\endrst \endrst
*/ */
@ -4561,7 +4563,8 @@ inline void print(rgb fd, string_view format_str, const Args &... args)
Formats a string and prints it to stdout using ANSI escape sequences to Formats a string and prints it to stdout using ANSI escape sequences to
specify foreground color 'fd' and background color 'bg'. specify foreground color 'fd' and background color 'bg'.
Example: Example:
fmt::print(fmt::color::red, fmt::color::black, "Elapsed time: {0:.2f} seconds", 1.23); fmt::print(fmt::color::red, fmt::color::black, "Elapsed time: {0:.2f}
seconds", 1.23);
*/ */
template<typename... Args> template<typename... Args>
inline void print(rgb fd, rgb bg, string_view format_str, const Args &... args) inline void print(rgb fd, rgb bg, string_view format_str, const Args &... args)

View File

@ -60,7 +60,8 @@ private:
void operator<<(null); void operator<<(null);
}; };
// Checks if T has a user-defined operator<< (e.g. not a member of std::ostream). // Checks if T has a user-defined operator<< (e.g. not a member of
// std::ostream).
template<typename T, typename Char> template<typename T, typename Char>
class is_streamable class is_streamable
{ {
@ -74,7 +75,8 @@ private:
typedef decltype(test<T>(0)) result; typedef decltype(test<T>(0)) result;
public: public:
// std::string operator<< is not considered user-defined because we handle strings // std::string operator<< is not considered user-defined because we handle
// strings
// specially. // specially.
static const bool value = result::value && !std::is_same<T, std::string>::value; static const bool value = result::value && !std::is_same<T, std::string>::value;
}; };

View File

@ -35,8 +35,8 @@ struct formatting_base
template<typename Char, typename Enable = void> template<typename Char, typename Enable = void>
struct formatting_range : formatting_base<Char> struct formatting_range : formatting_base<Char>
{ {
static FMT_CONSTEXPR_DECL const std::size_t range_length_limit = static FMT_CONSTEXPR_DECL const std::size_t range_length_limit = FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the
FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the range. // range.
Char prefix; Char prefix;
Char delimiter; Char delimiter;
Char postfix; Char postfix;

View File

@ -5,14 +5,17 @@
#pragma once #pragma once
// Thread safe logger (except for set_pattern(..), set_formatter(..) and set_error_handler()) // Thread safe logger (except for set_pattern(..), set_formatter(..) and
// set_error_handler())
// Has name, log level, vector of std::shared sink pointers and formatter // Has name, log level, vector of std::shared sink pointers and formatter
// Upon each log write the logger: // Upon each log write the logger:
// 1. Checks if its log level is enough to log the message and if yes: // 1. Checks if its log level is enough to log the message and if yes:
// 2. Call the underlying sinks to do the job. // 2. Call the underlying sinks to do the job.
// 3. Each sink use its own private copy of a formatter to format the message and send to its destination. // 3. Each sink use its own private copy of a formatter to format the message
// and send to its destination.
// //
// The use of private formatter per sink provides the opportunity to cache some formatted data, // The use of private formatter per sink provides the opportunity to cache some
// formatted data,
// and support customize format per each sink. // and support customize format per each sink.
#include "spdlog/common.h" #include "spdlog/common.h"
@ -138,10 +141,12 @@ protected:
bool should_flush_(const details::log_msg &msg); bool should_flush_(const details::log_msg &msg);
// default error handler: print the error to stderr with the max rate of 1 message/minute // default error handler: print the error to stderr with the max rate of 1
// message/minute
void default_err_handler_(const std::string &msg); void default_err_handler_(const std::string &msg);
// increment the message count (only if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)) // increment the message count (only if
// defined(SPDLOG_ENABLE_MESSAGE_COUNTER))
void incr_msg_counter_(details::log_msg &msg); void incr_msg_counter_(details::log_msg &msg);
const std::string name_; const std::string name_;

View File

@ -5,10 +5,10 @@
#pragma once #pragma once
#include "spdlog/details/fmt_helper.h"
#include "spdlog/details/null_mutex.h"
#include "spdlog/details/os.h" #include "spdlog/details/os.h"
#include "spdlog/sinks/base_sink.h" #include "spdlog/sinks/base_sink.h"
#include "spdlog/details/null_mutex.h"
#include "spdlog/details/fmt_helper.h"
#include <android/log.h> #include <android/log.h>
#include <chrono> #include <chrono>
@ -68,9 +68,7 @@ protected:
} }
} }
void flush_() override void flush_() override {}
{
}
private: private:
static android_LogPriority convert_to_android_(spdlog::level::level_enum level) static android_LogPriority convert_to_android_(spdlog::level::level_enum level)
@ -117,5 +115,3 @@ inline std::shared_ptr<logger> android_logger_st(const std::string &logger_name,
} }
} // namespace spdlog } // namespace spdlog

View File

@ -18,7 +18,8 @@ namespace spdlog {
namespace sinks { namespace sinks {
/** /**
* This sink prefixes the output with an ANSI escape sequence color code depending on the severity * This sink prefixes the output with an ANSI escape sequence color code
* depending on the severity
* of the message. * of the message.
* If no color terminal detected, omit the escape codes. * If no color terminal detected, omit the escape codes.
*/ */

View File

@ -7,7 +7,8 @@
// //
// base sink templated over a mutex (either dummy or real) // base sink templated over a mutex (either dummy or real)
// concrete implementation should override the sink_it_() and flush_() methods. // concrete implementation should override the sink_it_() and flush_() methods.
// locking is taken care of in this class - no locking needed by the implementers.. // locking is taken care of in this class - no locking needed by the
// implementers..
// //
#include "spdlog/common.h" #include "spdlog/common.h"

View File

@ -14,7 +14,8 @@
#include <mutex> #include <mutex>
#include <vector> #include <vector>
// Distribution sink (mux). Stores a vector of sinks which get called when log is called // Distribution sink (mux). Stores a vector of sinks which get called when log
// is called
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {

View File

@ -98,7 +98,8 @@ private:
if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0) if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0)
{ {
// if failed try again after small delay. // if failed try again after small delay.
// this is a workaround to a windows issue, where very high rotation rates sometimes fail (because of antivirus?). // this is a workaround to a windows issue, where very high rotation
// rates sometimes fail (because of antivirus?).
details::os::sleep_for_millis(20); details::os::sleep_for_millis(20);
details::os::remove(target); details::os::remove(target);
if (details::os::rename(src, target) != 0) if (details::os::rename(src, target) != 0)

View File

@ -57,7 +57,8 @@ protected:
private: private:
std::array<int, 7> priorities_; std::array<int, 7> priorities_;
// must store the ident because the man says openlog might use the pointer as is and not a string copy // must store the ident because the man says openlog might use the pointer as
// is and not a string copy
const std::string ident_; const std::string ident_;
// //

View File

@ -19,7 +19,8 @@
namespace spdlog { namespace spdlog {
namespace sinks { namespace sinks {
/* /*
* Windows color console sink. Uses WriteConsoleA to write to the console with colors * Windows color console sink. Uses WriteConsoleA to write to the console with
* colors
*/ */
template<typename OutHandle, typename ConsoleMutex> template<typename OutHandle, typename ConsoleMutex>
class wincolor_sink : public sink class wincolor_sink : public sink
@ -73,7 +74,8 @@ public:
// in color range // in color range
auto orig_attribs = set_console_attribs(colors_[msg.level]); auto orig_attribs = set_console_attribs(colors_[msg.level]);
print_range_(formatted, msg.color_range_start, msg.color_range_end); print_range_(formatted, msg.color_range_start, msg.color_range_end);
::SetConsoleTextAttribute(out_handle_, orig_attribs); // reset to orig colors ::SetConsoleTextAttribute(out_handle_,
orig_attribs); // reset to orig colors
// after color range // after color range
print_range_(formatted, msg.color_range_end, formatted.size()); print_range_(formatted, msg.color_range_end, formatted.size());
} }

View File

@ -35,17 +35,19 @@ struct synchronous_factory
using default_factory = synchronous_factory; using default_factory = synchronous_factory;
// Create and register a logger with a templated sink type // Create and register a logger with a templated sink type
// The logger's level, formatter and flush level will be set according the global settings. // The logger's level, formatter and flush level will be set according the
// global settings.
// Example: // Example:
// spdlog::create<daily_file_sink_st>("logger_name", "dailylog_filename", 11, 59); // spdlog::create<daily_file_sink_st>("logger_name", "dailylog_filename", 11,
// 59);
template<typename Sink, typename... SinkArgs> template<typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&... sink_args) inline std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&... sink_args)
{ {
return default_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...); return default_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
} }
// Return an existing logger or nullptr if a logger with such name doesn't
// Return an existing logger or nullptr if a logger with such name doesn't exist. // exist.
// example: spdlog::get("my_logger")->info("hello {}", "world"); // example: spdlog::get("my_logger")->info("hello {}", "world");
inline std::shared_ptr<logger> get(const std::string &name) inline std::shared_ptr<logger> get(const std::string &name)
{ {
@ -78,7 +80,6 @@ inline void flush_every(std::chrono::seconds interval)
details::registry::instance().flush_every(interval); details::registry::instance().flush_every(interval);
} }
// Set global error handler // Set global error handler
inline void set_error_handler(log_err_handler handler) inline void set_error_handler(log_err_handler handler)
{ {
@ -113,7 +114,8 @@ inline void drop_all()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// //
// Trace & Debug can be switched on/off at compile time for zero cost debug statements. // Trace & Debug can be switched on/off at compile time for zero cost debug
// statements.
// Uncomment SPDLOG_DEBUG_ON/SPDLOG_TRACE_ON in tweakme.h to enable. // Uncomment SPDLOG_DEBUG_ON/SPDLOG_TRACE_ON in tweakme.h to enable.
// SPDLOG_TRACE(..) will also print current file and line. // SPDLOG_TRACE(..) will also print current file and line.
// //
@ -130,7 +132,9 @@ inline void drop_all()
#ifdef _MSC_VER #ifdef _MSC_VER
#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__) #define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ "(" SPDLOG_STR_HELPER(__LINE__) ") ] " __VA_ARGS__)
#else #else
#define SPDLOG_TRACE(logger, ...) logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ] " __VA_ARGS__) #define SPDLOG_TRACE(logger, ...) \
logger->trace("[ " __FILE__ ":" SPDLOG_STR_HELPER(__LINE__) " ]" \
" " __VA_ARGS__)
#endif #endif
#else #else
#define SPDLOG_TRACE(logger, ...) (void)0 #define SPDLOG_TRACE(logger, ...) (void)0

View File

@ -7,24 +7,29 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// //
// Edit this file to squeeze more performance, and to customize supported features // Edit this file to squeeze more performance, and to customize supported
// features
// //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Under Linux, the much faster CLOCK_REALTIME_COARSE clock can be used. // Under Linux, the much faster CLOCK_REALTIME_COARSE clock can be used.
// This clock is less accurate - can be off by dozens of millis - depending on the kernel HZ. // This clock is less accurate - can be off by dozens of millis - depending on
// the kernel HZ.
// Uncomment to use it instead of the regular clock. // Uncomment to use it instead of the regular clock.
// //
// #define SPDLOG_CLOCK_COARSE // #define SPDLOG_CLOCK_COARSE
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment if date/time logging is not needed and never appear in the log pattern. // Uncomment if date/time logging is not needed and never appear in the log
// pattern.
// This will prevent spdlog from querying the clock on each log call. // This will prevent spdlog from querying the clock on each log call.
// //
// WARNING: If the log pattern contains any date/time while this flag is on, the result is undefined. // WARNING: If the log pattern contains any date/time while this flag is on, the
// You must set new pattern(spdlog::set_pattern(..") without any date/time in it // result is undefined.
// You must set new pattern(spdlog::set_pattern(..") without any
// date/time in it
// //
// #define SPDLOG_NO_DATETIME // #define SPDLOG_NO_DATETIME
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -33,7 +38,8 @@
// Uncomment if thread id logging is not needed (i.e. no %t in the log pattern). // Uncomment if thread id logging is not needed (i.e. no %t in the log pattern).
// This will prevent spdlog from querying the thread id on each log call. // This will prevent spdlog from querying the thread id on each log call.
// //
// WARNING: If the log pattern contains thread id (i.e, %t) while this flag is on, the result is undefined. // WARNING: If the log pattern contains thread id (i.e, %t) while this flag is
// on, the result is undefined.
// //
// #define SPDLOG_NO_THREAD_ID // #define SPDLOG_NO_THREAD_ID
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -42,7 +48,8 @@
// Uncomment to prevent spdlog from caching thread ids in thread local storage. // Uncomment to prevent spdlog from caching thread ids in thread local storage.
// By default spdlog saves thread ids in tls to gain a few micros for each call. // By default spdlog saves thread ids in tls to gain a few micros for each call.
// //
// WARNING: if your program forks, UNCOMMENT this flag to prevent undefined thread ids in the children logs. // WARNING: if your program forks, UNCOMMENT this flag to prevent undefined
// thread ids in the children logs.
// //
// #define SPDLOG_DISABLE_TID_CACHING // #define SPDLOG_DISABLE_TID_CACHING
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -62,7 +69,8 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to avoid locking in the registry operations (spdlog::get(), spdlog::drop() spdlog::register()). // Uncomment to avoid locking in the registry operations (spdlog::get(),
// spdlog::drop() spdlog::register()).
// Use only if your code never modifies concurrently the registry. // Use only if your code never modifies concurrently the registry.
// Note that upon creating a logger the registry is modified by spdlog.. // Note that upon creating a logger the registry is modified by spdlog..
// //
@ -71,7 +79,8 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to avoid spdlog's usage of atomic log levels // Uncomment to avoid spdlog's usage of atomic log levels
// Use only if your code never modifies a logger's log levels concurrently by different threads. // Use only if your code never modifies a logger's log levels concurrently by
// different threads.
// //
// #define SPDLOG_NO_ATOMIC_LEVELS // #define SPDLOG_NO_ATOMIC_LEVELS
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -90,7 +99,8 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to use your own copy of the fmt library instead of spdlog's copy. // Uncomment to use your own copy of the fmt library instead of spdlog's copy.
// In this case spdlog will try to include <fmt/format.h> so set your -I flag accordingly. // In this case spdlog will try to include <fmt/format.h> so set your -I flag
// accordingly.
// //
// #define SPDLOG_FMT_EXTERNAL // #define SPDLOG_FMT_EXTERNAL
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -126,5 +136,6 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Uncomment to customize level names (e.g. "MT TRACE") // Uncomment to customize level names (e.g. "MT TRACE")
// //
// #define SPDLOG_LEVEL_NAMES { "MY TRACE", "MY DEBUG", "MY INFO", "MY WARNING", "MY ERROR", "MY CRITICAL", "OFF" } // #define SPDLOG_LEVEL_NAMES { "MY TRACE", "MY DEBUG", "MY INFO", "MY WARNING",
// "MY ERROR", "MY CRITICAL", "OFF" }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@ -36,7 +36,6 @@ TEST_CASE("discard policy ", "[async]")
logger->info("Hello message"); logger->info("Hello message");
} }
REQUIRE(test_sink->msg_counter() < messages); REQUIRE(test_sink->msg_counter() < messages);
} }
TEST_CASE("discard policy using factory ", "[async]") TEST_CASE("discard policy using factory ", "[async]")
@ -54,7 +53,6 @@ TEST_CASE("discard policy using factory ", "[async]")
auto sink = std::static_pointer_cast<sinks::test_sink_mt>(logger->sinks()[0]); auto sink = std::static_pointer_cast<sinks::test_sink_mt>(logger->sinks()[0]);
REQUIRE(sink->msg_counter() < messages); REQUIRE(sink->msg_counter() < messages);
spdlog::drop_all(); spdlog::drop_all();
} }
TEST_CASE("flush", "[async]") TEST_CASE("flush", "[async]")
@ -78,7 +76,6 @@ TEST_CASE("flush", "[async]")
REQUIRE(test_sink->flush_counter() == 1); REQUIRE(test_sink->flush_counter() == 1);
} }
TEST_CASE("async periodic flush", "[async]") TEST_CASE("async periodic flush", "[async]")
{ {
using namespace spdlog; using namespace spdlog;

View File

@ -77,7 +77,6 @@ TEST_CASE("to_level_enum", "[convert_to_level_enum]")
REQUIRE(spdlog::level::from_str("null") == spdlog::level::off); REQUIRE(spdlog::level::from_str("null") == spdlog::level::off);
} }
TEST_CASE("periodic flush", "[periodic_flush]") TEST_CASE("periodic flush", "[periodic_flush]")
{ {
using namespace spdlog; using namespace spdlog;