clang format

This commit is contained in:
gabime 2024-01-13 18:20:08 +02:00
parent eaab457156
commit c539f36551
41 changed files with 152 additions and 249 deletions

View File

@ -6,7 +6,7 @@ Standard: c++17
IndentWidth: 4 IndentWidth: 4
TabWidth: 4 TabWidth: 4
UseTab: Never UseTab: Never
ColumnLimit: 120 ColumnLimit: 130
AlignAfterOpenBracket: Align AlignAfterOpenBracket: Align
BinPackParameters: false BinPackParameters: false
AlignEscapedNewlines: Left AlignEscapedNewlines: Left

View File

@ -287,8 +287,7 @@ if(NOT SPDLOG_USE_STD_FORMAT)
target_link_libraries(spdlog PUBLIC fmt::fmt) target_link_libraries(spdlog PUBLIC fmt::fmt)
endif() endif()
spdlog_enable_warnings(spdlog) spdlog_enable_warnings(spdlog)
set_target_properties(spdlog PROPERTIES VERSION ${SPDLOG_VERSION} SOVERSION set_target_properties(spdlog PROPERTIES VERSION ${SPDLOG_VERSION} SOVERSION ${SPDLOG_VERSION_MAJOR}.${SPDLOG_VERSION_MINOR})
${SPDLOG_VERSION_MAJOR}.${SPDLOG_VERSION_MINOR})
set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX d) set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX d)
# set source groups for visual studio # set source groups for visual studio

View File

@ -96,8 +96,8 @@ int main(int argc, char *argv[]) {
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
auto tp = std::make_shared<details::thread_pool>(queue_size, 1); auto tp = std::make_shared<details::thread_pool>(queue_size, 1);
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true); auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, true);
auto logger = std::make_shared<async_logger>("async_logger", std::move(file_sink), std::move(tp), auto logger =
async_overflow_policy::block); std::make_shared<async_logger>("async_logger", std::move(file_sink), std::move(tp), async_overflow_policy::block);
bench_mt(howmany, std::move(logger), threads); bench_mt(howmany, std::move(logger), threads);
// verify_file(filename, howmany); // verify_file(filename, howmany);
} }

View File

@ -38,8 +38,8 @@ static const int max_threads = 1000;
void bench_threaded_logging(size_t threads, int iters) { void bench_threaded_logging(size_t threads, int iters) {
spdlog::info("**************************************************************"); spdlog::info("**************************************************************");
spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Multi threaded: {:L} threads, {:L} messages", spdlog::info(
threads, iters)); spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "Multi threaded: {:L} threads, {:L} messages", threads, iters));
spdlog::info("**************************************************************"); spdlog::info("**************************************************************");
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);
@ -121,8 +121,8 @@ void bench(int howmany, std::shared_ptr<spdlog::logger> log) {
auto delta = high_resolution_clock::now() - start; auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count(); auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(),
log->name(), delta_d, size_t(howmany / delta_d))); delta_d, size_t(howmany / delta_d)));
spdlog::drop(log->name()); spdlog::drop(log->name());
} }
@ -148,8 +148,8 @@ void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, size_t thread_co
auto delta = high_resolution_clock::now() - start; auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count(); auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", spdlog::info(spdlog::fmt_lib::format(std::locale("en_US.UTF-8"), "{:<30} Elapsed: {:0.2f} secs {:>16L}/sec", log->name(),
log->name(), delta_d, size_t(howmany / delta_d))); delta_d, size_t(howmany / delta_d)));
spdlog::drop(log->name()); spdlog::drop(log->name());
} }

View File

@ -91,8 +91,7 @@ int main(int argc, char *argv[]) {
auto disabled_logger = std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>()); auto disabled_logger = std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
disabled_logger->set_level(spdlog::level::off); disabled_logger->set_level(spdlog::level::off);
benchmark::RegisterBenchmark("disabled-at-compile-time", bench_disabled_macro, disabled_logger); benchmark::RegisterBenchmark("disabled-at-compile-time", bench_disabled_macro, disabled_logger);
benchmark::RegisterBenchmark("disabled-at-compile-time (global logger)", bench_disabled_macro_global_logger, benchmark::RegisterBenchmark("disabled-at-compile-time (global logger)", bench_disabled_macro_global_logger, disabled_logger);
disabled_logger);
benchmark::RegisterBenchmark("disabled-at-runtime", bench_logger, disabled_logger); benchmark::RegisterBenchmark("disabled-at-runtime", bench_logger, disabled_logger);
benchmark::RegisterBenchmark("disabled-at-runtime (global logger)", bench_global_logger, disabled_logger); benchmark::RegisterBenchmark("disabled-at-runtime (global logger)", bench_global_logger, disabled_logger);
@ -112,8 +111,7 @@ int main(int argc, char *argv[]) {
spdlog::drop("basic_st"); spdlog::drop("basic_st");
// rotating st // rotating st
auto rotating_st = auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", file_size, rotating_files);
spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", file_size, rotating_files);
benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))->UseRealTime(); benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))->UseRealTime();
spdlog::drop("rotating_st"); spdlog::drop("rotating_st");
@ -134,11 +132,8 @@ int main(int argc, char *argv[]) {
spdlog::drop("basic_mt"); spdlog::drop("basic_mt");
// rotating mt // rotating mt
auto rotating_mt = auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", file_size, rotating_files);
spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", file_size, rotating_files); benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))->Threads(n_threads)->UseRealTime();
benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))
->Threads(n_threads)
->UseRealTime();
spdlog::drop("rotating_mt"); spdlog::drop("rotating_mt");
// daily mt // daily mt
@ -150,8 +145,8 @@ int main(int argc, char *argv[]) {
// async // async
auto queue_size = 1024 * 1024 * 3; auto queue_size = 1024 * 1024 * 3;
auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1); auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1);
auto async_logger = std::make_shared<spdlog::async_logger>( auto async_logger = std::make_shared<spdlog::async_logger>("async_logger", std::make_shared<null_sink_mt>(), std::move(tp),
"async_logger", std::make_shared<null_sink_mt>(), std::move(tp), spdlog::async_overflow_policy::overrun_oldest); spdlog::async_overflow_policy::overrun_oldest);
benchmark::RegisterBenchmark("async_logger", bench_logger, async_logger)->Threads(n_threads)->UseRealTime(); benchmark::RegisterBenchmark("async_logger", bench_logger, async_logger)->Threads(n_threads)->UseRealTime();
benchmark::Initialize(&argc, argv); benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks(); benchmark::RunSpecifiedBenchmarks();

View File

@ -276,8 +276,7 @@ void user_defined_example() { spdlog::info("user defined type: {}", my_type(14))
// Custom error handler. Will be triggered on log failure. // Custom error handler. Will be triggered on log failure.
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( spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
[](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
} }
// syslog example (linux/osx/freebsd) // syslog example (linux/osx/freebsd)

View File

@ -48,8 +48,7 @@ struct async_factory_impl {
} }
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...); auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
auto new_logger = auto new_logger = std::make_shared<async_logger>(std::move(logger_name), std::move(sink), std::move(tp), OverflowPolicy);
std::make_shared<async_logger>(std::move(logger_name), std::move(sink), std::move(tp), OverflowPolicy);
registry_inst.initialize_logger(new_logger); registry_inst.initialize_logger(new_logger);
return new_logger; return new_logger;
} }

View File

@ -23,9 +23,9 @@ SPDLOG_API std::tm gmtime() noexcept;
// eol definition // eol definition
#ifdef _WIN32 #ifdef _WIN32
constexpr static const char *default_eol = "\r\n"; constexpr static const char *default_eol = "\r\n";
#else #else
constexpr static const char *default_eol = "\n"; constexpr static const char *default_eol = "\n";
#endif #endif
// folder separator // folder separator

View File

@ -75,8 +75,8 @@ public:
} }
int option_value = TX_BUFFER_SIZE; int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) <
sizeof(option_value)) < 0) { 0) {
int last_error = ::WSAGetLastError(); int last_error = ::WSAGetLastError();
cleanup_(); cleanup_();
throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error); throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error);

View File

@ -46,8 +46,8 @@ public:
} }
int option_value = TX_BUFFER_SIZE; int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value), sizeof(option_value)) <
sizeof(option_value)) < 0) { 0) {
cleanup_(); cleanup_();
throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!"); throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
} }

View File

@ -61,8 +61,7 @@ private:
// create a dump_info that wraps the given container // create a dump_info that wraps the given container
template <typename Container> template <typename Container>
inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container, inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container, size_t size_per_line = 32) {
size_t size_per_line = 32) {
static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1"); static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
using Iter = typename Container::const_iterator; using Iter = typename Container::const_iterator;
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line); return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
@ -139,8 +138,7 @@ struct formatter<spdlog::details::dump_info<T>, char> {
// format the given bytes range as hex // format the given bytes range as hex
template <typename FormatContext, typename Container> template <typename FormatContext, typename Container>
auto format(const spdlog::details::dump_info<Container> &the_range, FormatContext &ctx) const auto format(const spdlog::details::dump_info<Container> &the_range, FormatContext &ctx) const -> decltype(ctx.out()) {
-> decltype(ctx.out()) {
constexpr const char *hex_upper = "0123456789ABCDEF"; constexpr const char *hex_upper = "0123456789ABCDEF";
constexpr const char *hex_lower = "0123456789abcdef"; constexpr const char *hex_lower = "0123456789abcdef";
const char *hex_chars = use_uppercase ? hex_upper : hex_lower; const char *hex_chars = use_uppercase ? hex_upper : hex_lower;

View File

@ -19,9 +19,7 @@ namespace sinks {
template <typename Mutex> template <typename Mutex>
class basic_file_sink final : public base_sink<Mutex> { class basic_file_sink final : public base_sink<Mutex> {
public: public:
explicit basic_file_sink(const filename_t &filename, explicit basic_file_sink(const filename_t &filename, bool truncate = false, const file_event_handlers &event_handlers = {});
bool truncate = false,
const file_event_handlers &event_handlers = {});
const filename_t &filename() const; const filename_t &filename() const;
protected: protected:

View File

@ -29,8 +29,8 @@ struct daily_filename_calculator {
static filename_t calc_filename(const filename_t &filename, const tm &now_tm) { static filename_t calc_filename(const filename_t &filename, const tm &now_tm) {
filename_t basename, ext; filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename); std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1,
now_tm.tm_mon + 1, now_tm.tm_mday, ext); now_tm.tm_mday, ext);
} }
}; };
@ -214,8 +214,8 @@ inline std::shared_ptr<logger> daily_logger_format_mt(const std::string &logger_
bool truncate = false, bool truncate = false,
uint16_t max_files = 0, uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate, return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate, max_files,
max_files, event_handlers); event_handlers);
} }
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
@ -238,7 +238,7 @@ inline std::shared_ptr<logger> daily_logger_format_st(const std::string &logger_
bool truncate = false, bool truncate = false,
uint16_t max_files = 0, uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate, return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate, max_files,
max_files, event_handlers); event_handlers);
} }
} // namespace spdlog } // namespace spdlog

View File

@ -40,8 +40,7 @@ template <typename Mutex>
class dup_filter_sink : public dist_sink<Mutex> { class dup_filter_sink : public dist_sink<Mutex> {
public: public:
template <class Rep, class Period> template <class Rep, class Period>
explicit dup_filter_sink(std::chrono::duration<Rep, Period> max_skip_duration, explicit dup_filter_sink(std::chrono::duration<Rep, Period> max_skip_duration, level notification_level = level::info)
level notification_level = level::info)
: max_skip_duration_{max_skip_duration}, : max_skip_duration_{max_skip_duration},
log_level_{notification_level} {} log_level_{notification_level} {}
@ -62,8 +61,7 @@ protected:
// log the "skipped.." message // log the "skipped.." message
if (skip_counter_ > 0) { if (skip_counter_ > 0) {
char buf[64]; char buf[64];
auto msg_size = auto msg_size = ::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", static_cast<unsigned>(skip_counter_));
::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", static_cast<unsigned>(skip_counter_));
if (msg_size > 0 && static_cast<size_t>(msg_size) < sizeof(buf)) { if (msg_size > 0 && static_cast<size_t>(msg_size) < sizeof(buf)) {
details::log_msg skipped_msg{msg.source, msg.logger_name, log_level_, details::log_msg skipped_msg{msg.source, msg.logger_name, log_level_,
string_view_t{buf, static_cast<size_t>(msg_size)}}; string_view_t{buf, static_cast<size_t>(msg_size)}};

View File

@ -173,8 +173,7 @@ inline std::shared_ptr<logger> hourly_logger_mt(const std::string &logger_name,
bool truncate = false, bool truncate = false,
uint16_t max_files = 0, uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files, return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files, event_handlers);
event_handlers);
} }
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
@ -183,7 +182,6 @@ inline std::shared_ptr<logger> hourly_logger_st(const std::string &logger_name,
bool truncate = false, bool truncate = false,
uint16_t max_files = 0, uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files, return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files, event_handlers);
event_handlers);
} }
} // namespace spdlog } // namespace spdlog

View File

@ -71,8 +71,8 @@ public:
protected: protected:
void sink_it_(const details::log_msg &msg) override { void sink_it_(const details::log_msg &msg) override {
producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY, (void *)msg.payload.data(), producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY, (void *)msg.payload.data(), msg.payload.size(), NULL,
msg.payload.size(), NULL, NULL); NULL);
} }
void flush_() override { producer_->flush(config_.flush_timeout_ms); } void flush_() override { producer_->flush(config_.flush_timeout_ms); }
@ -91,26 +91,22 @@ using kafka_sink_st = kafka_sink<spdlog::details::null_mutex>;
} // namespace sinks } // namespace sinks
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> kafka_logger_mt(const std::string &logger_name, inline std::shared_ptr<logger> kafka_logger_mt(const std::string &logger_name, spdlog::sinks::kafka_sink_config config) {
spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_mt>(logger_name, config); return Factory::template create<sinks::kafka_sink_mt>(logger_name, config);
} }
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> kafka_logger_st(const std::string &logger_name, inline std::shared_ptr<logger> kafka_logger_st(const std::string &logger_name, spdlog::sinks::kafka_sink_config config) {
spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_st>(logger_name, config); return Factory::template create<sinks::kafka_sink_st>(logger_name, config);
} }
template <typename Factory = spdlog::async_factory> template <typename Factory = spdlog::async_factory>
inline std::shared_ptr<spdlog::logger> kafka_logger_async_mt(std::string logger_name, inline std::shared_ptr<spdlog::logger> kafka_logger_async_mt(std::string logger_name, spdlog::sinks::kafka_sink_config config) {
spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_mt>(logger_name, config); return Factory::template create<sinks::kafka_sink_mt>(logger_name, config);
} }
template <typename Factory = spdlog::async_factory> template <typename Factory = spdlog::async_factory>
inline std::shared_ptr<spdlog::logger> kafka_logger_async_st(std::string logger_name, inline std::shared_ptr<spdlog::logger> kafka_logger_async_st(std::string logger_name, spdlog::sinks::kafka_sink_config config) {
spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_st>(logger_name, config); return Factory::template create<sinks::kafka_sink_st>(logger_name, config);
} }

View File

@ -58,8 +58,8 @@ protected:
if (client_ != nullptr) { if (client_ != nullptr) {
auto doc = document{} << "timestamp" << bsoncxx::types::b_date(msg.time) << "level" auto doc = document{} << "timestamp" << bsoncxx::types::b_date(msg.time) << "level"
<< level::to_string_view(msg.log_level).data() << "level_num" << msg.log_level << level::to_string_view(msg.log_level).data() << "level_num" << msg.log_level << "message"
<< "message" << std::string(msg.payload.begin(), msg.payload.end()) << "logger_name" << std::string(msg.payload.begin(), msg.payload.end()) << "logger_name"
<< std::string(msg.logger_name.begin(), msg.logger_name.end()) << "thread_id" << std::string(msg.logger_name.begin(), msg.logger_name.end()) << "thread_id"
<< static_cast<int>(msg.thread_id) << finalize; << static_cast<int>(msg.thread_id) << finalize;
client_->database(db_name_).collection(coll_name_).insert_one(doc.view()); client_->database(db_name_).collection(coll_name_).insert_one(doc.view());

View File

@ -43,9 +43,8 @@ protected:
memory_buf_t formatted; memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted); base_sink<Mutex>::formatter_->format(msg, formatted);
const string_view_t str = string_view_t(formatted.data(), formatted.size()); const string_view_t str = string_view_t(formatted.data(), formatted.size());
QMetaObject::invokeMethod( QMetaObject::invokeMethod(qt_object_, meta_method_.c_str(), Qt::AutoConnection,
qt_object_, meta_method_.c_str(), Qt::AutoConnection, Q_ARG(QString, QString::fromUtf8(str.data(), static_cast<int>(str.size())).trimmed()));
Q_ARG(QString, QString::fromUtf8(str.data(), static_cast<int>(str.size())).trimmed()));
} }
void flush_() override {} void flush_() override {}
@ -206,8 +205,7 @@ protected:
// insert the colorized text // insert the colorized text
cursor.setCharFormat(params.level_color); cursor.setCharFormat(params.level_color);
cursor.insertText( cursor.insertText(params.payload.mid(params.color_range_start, params.color_range_end - params.color_range_start));
params.payload.mid(params.color_range_start, params.color_range_end - params.color_range_start));
// insert the text after the color range with default format // insert the text after the color range with default format
cursor.setCharFormat(params.default_color); cursor.setCharFormat(params.default_color);
@ -266,16 +264,12 @@ inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name,
} }
// log to QObject // log to QObject
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, QObject *qt_object, const std::string &meta_method) {
QObject *qt_object,
const std::string &meta_method) {
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method); return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
} }
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, QObject *qt_object, const std::string &meta_method) {
QObject *qt_object,
const std::string &meta_method) {
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method); return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
} }

View File

@ -68,8 +68,8 @@ inline std::shared_ptr<logger> rotating_logger_mt(const std::string &logger_name
size_t max_files, size_t max_files,
bool rotate_on_open = false, bool rotate_on_open = false,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, rotate_on_open,
rotate_on_open, event_handlers); event_handlers);
} }
template <typename Factory = spdlog::synchronous_factory> template <typename Factory = spdlog::synchronous_factory>
@ -79,7 +79,7 @@ inline std::shared_ptr<logger> rotating_logger_st(const std::string &logger_name
size_t max_files, size_t max_files,
bool rotate_on_open = false, bool rotate_on_open = false,
const file_event_handlers &event_handlers = {}) { const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, rotate_on_open,
rotate_on_open, event_handlers); event_handlers);
} }
} // namespace spdlog } // namespace spdlog

View File

@ -75,8 +75,8 @@ struct win32_error : public spdlog_ex {
local_alloc_t format_message_result{}; local_alloc_t format_message_result{};
auto format_message_succeeded = ::FormatMessageA( auto format_message_succeeded = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&format_message_result.hlocal_, 0, nullptr); MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&format_message_result.hlocal_, 0, nullptr);
if (format_message_succeeded && format_message_result.hlocal_) { if (format_message_succeeded && format_message_result.hlocal_) {
system_message = fmt_lib::format(" ({})", (LPSTR)format_message_result.hlocal_); system_message = fmt_lib::format(" ({})", (LPSTR)format_message_result.hlocal_);
@ -140,8 +140,7 @@ public:
// get user token // get user token
std::vector<unsigned char> buffer(static_cast<size_t>(tusize)); std::vector<unsigned char> buffer(static_cast<size_t>(tusize));
if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, (LPVOID)buffer.data(), tusize, if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, (LPVOID)buffer.data(), tusize, &tusize)) {
&tusize)) {
SPDLOG_THROW(win32_error("GetTokenInformation")); SPDLOG_THROW(win32_error("GetTokenInformation"));
} }
@ -210,9 +209,9 @@ protected:
formatted.push_back('\0'); formatted.push_back('\0');
LPCSTR lp_str = formatted.data(); LPCSTR lp_str = formatted.data();
succeeded = static_cast<bool>(::ReportEventA(event_log_handle(), eventlog::get_event_type(msg), succeeded =
eventlog::get_event_category(msg), event_id_, static_cast<bool>(::ReportEventA(event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg),
current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr)); event_id_, current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr));
if (!succeeded) { if (!succeeded) {
SPDLOG_THROW(win32_error("ReportEvent")); SPDLOG_THROW(win32_error("ReportEvent"));

View File

@ -40,9 +40,7 @@ struct source_loc {
static constexpr source_loc current() { return source_loc{}; } static constexpr source_loc current() { return source_loc{}; }
#endif #endif
[[nodiscard]] constexpr bool empty() const noexcept { [[nodiscard]] constexpr bool empty() const noexcept { return line == 0 || filename == nullptr || short_filename == nullptr; }
return line == 0 || filename == nullptr || short_filename == nullptr;
}
const char *filename{nullptr}; const char *filename{nullptr};
const char *short_filename{nullptr}; const char *short_filename{nullptr};

View File

@ -10,8 +10,7 @@ namespace spdlog {
spdlog::level level_from_str(const std::string &name) noexcept { spdlog::level level_from_str(const std::string &name) noexcept {
auto it = std::find(std::begin(level_string_views), std::end(level_string_views), name); auto it = std::find(std::begin(level_string_views), std::end(level_string_views), name);
if (it != std::end(level_string_views)) if (it != std::end(level_string_views)) return static_cast<level>(std::distance(std::begin(level_string_views), it));
return static_cast<level>(std::distance(std::begin(level_string_views), it));
// check also for "warn" and "err" before giving up.. // check also for "warn" and "err" before giving up..
if (name == "warn") { if (name == "warn") {

View File

@ -218,8 +218,7 @@ size_t filesize(FILE *f) {
int fd = ::fileno(f); int fd = ::fileno(f);
#endif #endif
// 64 bits(but not in osx, linux/musl or cygwin, where fstat64 is deprecated) // 64 bits(but not in osx, linux/musl or cygwin, where fstat64 is deprecated)
#if ((defined(__linux__) && defined(__GLIBC__)) || defined(__sun) || defined(_AIX)) && \ #if ((defined(__linux__) && defined(__GLIBC__)) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
(defined(__LP64__) || defined(_LP64))
struct stat64 st; struct stat64 st;
if (::fstat64(fd, &st) == 0) { if (::fstat64(fd, &st) == 0) {
return static_cast<size_t>(st.st_size); return static_cast<size_t>(st.st_size);
@ -400,9 +399,9 @@ bool is_color_terminal() noexcept {
return true; return true;
} }
static constexpr std::array<const char *, 16> terms = {{"ansi", "color", "console", "cygwin", "gnome", static constexpr std::array<const char *, 16> terms = {{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm",
"konsole", "kterm", "linux", "msys", "putty", "rxvt", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm",
"screen", "vt100", "xterm", "alacritty", "vt102"}}; "alacritty", "vt102"}};
const char *env_term_p = std::getenv("TERM"); const char *env_term_p = std::getenv("TERM");
if (env_term_p == nullptr) { if (env_term_p == nullptr) {
@ -473,8 +472,7 @@ void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target) {
if (result_size > 0) { if (result_size > 0) {
target.resize(result_size); target.resize(result_size);
result_size = result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, target.data(), result_size);
::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, target.data(), result_size);
if (result_size > 0) { if (result_size > 0) {
assert(result_size == target.size()); assert(result_size == target.size());
return; return;

View File

@ -50,9 +50,7 @@ thread_pool::~thread_pool() {
SPDLOG_CATCH_STD SPDLOG_CATCH_STD
} }
void thread_pool::post_log(async_logger_ptr &&worker_ptr, void thread_pool::post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy) {
const details::log_msg &msg,
async_overflow_policy overflow_policy) {
async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg); async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg);
post_async_msg_(std::move(async_m), overflow_policy); post_async_msg_(std::move(async_m), overflow_policy);
} }

View File

@ -106,8 +106,7 @@ void logger::err_handler_(const std::string &msg) {
#if defined(USING_R) && defined(R_R_H) // if in R environment #if defined(USING_R) && defined(R_R_H) // if in R environment
REprintf("[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), msg.c_str()); REprintf("[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), msg.c_str());
#else #else
std::fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), std::fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] %s\n", err_counter, date_buf, name().c_str(), msg.c_str());
msg.c_str());
#endif #endif
} }
} }

View File

@ -62,9 +62,7 @@ public:
} }
private: private:
void pad_it(long count) { void pad_it(long count) { fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast<size_t>(count)), dest_); }
fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast<size_t>(count)), dest_);
}
const padding_info &padinfo_; const padding_info &padinfo_;
memory_buf_t &dest_; memory_buf_t &dest_;
@ -146,8 +144,7 @@ public:
}; };
// Full weekday name // Full weekday name
static std::array<const char *, 7> full_days{ static std::array<const char *, 7> full_days{{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}};
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}};
template <typename ScopedPadder> template <typename ScopedPadder>
class A_formatter : public flag_formatter { class A_formatter : public flag_formatter {
@ -180,8 +177,8 @@ public:
}; };
// Full month name // Full month name
static const std::array<const char *, 12> full_months{{"January", "February", "March", "April", "May", "June", "July", static const std::array<const char *, 12> full_months{
"August", "September", "October", "November", "December"}}; {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}};
template <typename ScopedPadder> template <typename ScopedPadder>
class B_formatter final : public flag_formatter { class B_formatter final : public flag_formatter {
@ -614,9 +611,7 @@ public:
explicit color_stop_formatter(padding_info padinfo) explicit color_stop_formatter(padding_info padinfo)
: flag_formatter(padinfo) {} : flag_formatter(padinfo) {}
void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override { void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override { msg.color_range_end = dest.size(); }
msg.color_range_end = dest.size();
}
}; };
// print source location // print source location
@ -635,8 +630,7 @@ public:
size_t text_size; size_t text_size;
if (padinfo_.enabled()) { if (padinfo_.enabled()) {
// calc text size for padding based on "filename:line" // calc text size for padding based on "filename:line"
text_size = text_size = std::char_traits<char>::length(msg.source.filename) + ScopedPadder::count_digits(msg.source.line) + 1;
std::char_traits<char>::length(msg.source.filename) + ScopedPadder::count_digits(msg.source.line) + 1;
} else { } else {
text_size = 0; text_size = 0;
} }
@ -858,8 +852,7 @@ std::unique_ptr<formatter> pattern_formatter::clone() const {
for (auto &it : custom_handlers_) { for (auto &it : custom_handlers_) {
cloned_custom_formatters[it.first] = it.second->clone(); cloned_custom_formatters[it.first] = it.second->clone();
} }
auto cloned = auto cloned = std::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
std::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
cloned->need_localtime(need_localtime_); cloned->need_localtime(need_localtime_);
#if defined(__GNUC__) && __GNUC__ < 5 #if defined(__GNUC__) && __GNUC__ < 5
return std::move(cloned); return std::move(cloned);
@ -1088,18 +1081,15 @@ void pattern_formatter::handle_flag_(char flag, details::padding_info padding) {
break; break;
case ('u'): // elapsed time since last log message in nanos case ('u'): // elapsed time since last log message in nanos
formatters_.push_back( formatters_.push_back(std::make_unique<details::elapsed_formatter<Padder, std::chrono::nanoseconds>>(padding));
std::make_unique<details::elapsed_formatter<Padder, std::chrono::nanoseconds>>(padding));
break; break;
case ('i'): // elapsed time since last log message in micros case ('i'): // elapsed time since last log message in micros
formatters_.push_back( formatters_.push_back(std::make_unique<details::elapsed_formatter<Padder, std::chrono::microseconds>>(padding));
std::make_unique<details::elapsed_formatter<Padder, std::chrono::microseconds>>(padding));
break; break;
case ('o'): // elapsed time since last log message in millis case ('o'): // elapsed time since last log message in millis
formatters_.push_back( formatters_.push_back(std::make_unique<details::elapsed_formatter<Padder, std::chrono::milliseconds>>(padding));
std::make_unique<details::elapsed_formatter<Padder, std::chrono::milliseconds>>(padding));
break; break;
case ('O'): // elapsed time since last log message in seconds case ('O'): // elapsed time since last log message in seconds
@ -1131,8 +1121,7 @@ void pattern_formatter::handle_flag_(char flag, details::padding_info padding) {
// Extract given pad spec (e.g. %8X, %=8X, %-8!X, %8!X, %=8!X, %-8!X, %+8!X) // Extract given pad spec (e.g. %8X, %=8X, %-8!X, %8!X, %=8!X, %-8!X, %+8!X)
// Advance the given it pass the end of the padding spec found (if any) // Advance the given it pass the end of the padding spec found (if any)
// Return padding. // Return padding.
details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end) {
std::string::const_iterator end) {
using details::padding_info; using details::padding_info;
using details::scoped_padder; using details::scoped_padder;
const size_t max_width = 64; const size_t max_width = 64;

View File

@ -9,9 +9,7 @@ namespace spdlog {
namespace sinks { namespace sinks {
template <typename Mutex> template <typename Mutex>
basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, bool truncate, const file_event_handlers &event_handlers)
bool truncate,
const file_event_handlers &event_handlers)
: file_helper_{event_handlers} { : file_helper_{event_handlers} {
file_helper_.open(filename, truncate); file_helper_.open(filename, truncate);
} }

View File

@ -113,9 +113,8 @@ void rotating_file_sink<Mutex>::rotate_() {
file_helper_.reopen(true); // truncate the log file anyway to prevent it file_helper_.reopen(true); // truncate the log file anyway to prevent it
// to grow beyond its limit! // to grow beyond its limit!
current_size_ = 0; current_size_ = 0;
throw_spdlog_ex( throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target),
"rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
errno);
} }
} }
} }

View File

@ -44,14 +44,14 @@ template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt<spdl
template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::synchronous_factory>( template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::synchronous_factory>(
const std::string &logger_name, color_mode mode); const std::string &logger_name, color_mode mode);
template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt<spdlog::async_factory>( template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stdout_color_mt<spdlog::async_factory>(const std::string &logger_name,
const std::string &logger_name, color_mode mode); color_mode mode);
template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stdout_color_st<spdlog::async_factory>( template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stdout_color_st<spdlog::async_factory>(const std::string &logger_name,
const std::string &logger_name, color_mode mode); color_mode mode);
template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt<spdlog::async_factory>( template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_mt<spdlog::async_factory>(const std::string &logger_name,
const std::string &logger_name, color_mode mode); color_mode mode);
template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::async_factory>( template SPDLOG_API std::shared_ptr<spdlog::logger> spdlog::stderr_color_st<spdlog::async_factory>(const std::string &logger_name,
const std::string &logger_name, color_mode mode); color_mode mode);

View File

@ -20,14 +20,12 @@ wincolor_sink<Mutex>::wincolor_sink(void *out_handle, color_mode mode)
: out_handle_(out_handle) { : out_handle_(out_handle) {
set_color_mode_impl(mode); set_color_mode_impl(mode);
// set level colors // set level colors
colors_.at(level_to_number(level::trace)) = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white colors_.at(level_to_number(level::trace)) = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white
colors_.at(level_to_number(level::debug)) = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan colors_.at(level_to_number(level::debug)) = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan
colors_.at(level_to_number(level::info)) = FOREGROUND_GREEN; // green colors_.at(level_to_number(level::info)) = FOREGROUND_GREEN; // green
colors_.at(level_to_number(level::warn)) = colors_.at(level_to_number(level::warn)) = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow colors_.at(level_to_number(level::err)) = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red
colors_.at(level_to_number(level::err)) = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red colors_.at(level_to_number(level::critical)) = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
colors_.at(level_to_number(level::critical)) = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN |
FOREGROUND_BLUE |
FOREGROUND_INTENSITY; // intense white on red background FOREGROUND_INTENSITY; // intense white on red background
colors_.at(level_to_number(level::off)) = 0; colors_.at(level_to_number(level::off)) = 0;
} }
@ -113,8 +111,7 @@ template <typename Mutex>
void wincolor_sink<Mutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end) { void wincolor_sink<Mutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end) {
if (end > start) { if (end > start) {
auto size = static_cast<DWORD>(end - start); auto size = static_cast<DWORD>(end - start);
auto ignored = auto ignored = ::WriteConsoleA(static_cast<HANDLE>(out_handle_), formatted.data() + start, size, nullptr, nullptr);
::WriteConsoleA(static_cast<HANDLE>(out_handle_), formatted.data() + start, size, nullptr, nullptr);
(void)(ignored); (void)(ignored);
} }
} }

View File

@ -12,9 +12,7 @@
namespace spdlog { namespace spdlog {
void initialize_logger(std::shared_ptr<logger> logger) { void initialize_logger(std::shared_ptr<logger> logger) { details::registry::instance().initialize_logger(std::move(logger)); }
details::registry::instance().initialize_logger(std::move(logger));
}
std::shared_ptr<logger> get(const std::string &name) { return details::registry::instance().get(name); } std::shared_ptr<logger> get(const std::string &name) { return details::registry::instance().get(name); }
@ -34,17 +32,11 @@ void set_level(level level) { details::registry::instance().set_level(level); }
void flush_on(level level) { details::registry::instance().flush_on(level); } void flush_on(level level) { details::registry::instance().flush_on(level); }
void set_error_handler(void (*handler)(const std::string &msg)) { void set_error_handler(void (*handler)(const std::string &msg)) { details::registry::instance().set_error_handler(handler); }
details::registry::instance().set_error_handler(handler);
}
void register_logger(std::shared_ptr<logger> logger) { void register_logger(std::shared_ptr<logger> logger) { details::registry::instance().register_logger(std::move(logger)); }
details::registry::instance().register_logger(std::move(logger));
}
void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun) { void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun) { details::registry::instance().apply_all(fun); }
details::registry::instance().apply_all(fun);
}
void drop(const std::string &name) { details::registry::instance().drop(name); } void drop(const std::string &name) { details::registry::instance().drop(name); }

View File

@ -31,8 +31,7 @@ TEST_CASE("discard policy ", "[async]") {
size_t messages = 1024; size_t messages = 1024;
auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1); auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1);
auto logger = auto logger = std::make_shared<spdlog::async_logger>("as", test_sink, tp, spdlog::async_overflow_policy::overrun_oldest);
std::make_shared<spdlog::async_logger>("as", test_sink, tp, spdlog::async_overflow_policy::overrun_oldest);
for (size_t i = 0; i < messages; i++) { for (size_t i = 0; i < messages; i++) {
logger->info("Hello message"); logger->info("Hello message");
} }
@ -47,8 +46,7 @@ TEST_CASE("discard policy discard_new ", "[async]") {
size_t messages = 1024; size_t messages = 1024;
auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1); auto tp = std::make_shared<spdlog::details::thread_pool>(queue_size, 1);
auto logger = auto logger = std::make_shared<spdlog::async_logger>("as", test_sink, tp, spdlog::async_overflow_policy::discard_new);
std::make_shared<spdlog::async_logger>("as", test_sink, tp, spdlog::async_overflow_policy::discard_new);
for (size_t i = 0; i < messages; i++) { for (size_t i = 0; i < messages; i++) {
logger->info("Hello message"); logger->info("Hello message");
} }

View File

@ -21,18 +21,16 @@ TEST_CASE("create_dir", "[create_dir]") {
SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); // test existing SPDLOG_FILENAME_T("test_logs/dir1/dir1"))); // test existing
REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1///dir2//"), SPDLOG_FILENAME_T("test_logs/dir1/dir2"))); REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/dir1///dir2//"), SPDLOG_FILENAME_T("test_logs/dir1/dir2")));
REQUIRE(try_create_dir(SPDLOG_FILENAME_T("./test_logs/dir1/dir3"), SPDLOG_FILENAME_T("test_logs/dir1/dir3"))); REQUIRE(try_create_dir(SPDLOG_FILENAME_T("./test_logs/dir1/dir3"), SPDLOG_FILENAME_T("test_logs/dir1/dir3")));
REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/../test_logs/dir1/dir4"), REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs/../test_logs/dir1/dir4"), SPDLOG_FILENAME_T("test_logs/dir1/dir4")));
SPDLOG_FILENAME_T("test_logs/dir1/dir4")));
#ifdef WIN32 #ifdef WIN32
// test backslash folder separator // test backslash folder separator
REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"))); REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir222"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir222")));
REQUIRE( REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\")));
try_create_dir(SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir223\\")));
REQUIRE(try_create_dir(SPDLOG_FILENAME_T(".\\test_logs\\dir1\\dir2\\dir99\\..\\dir23"), REQUIRE(try_create_dir(SPDLOG_FILENAME_T(".\\test_logs\\dir1\\dir2\\dir99\\..\\dir23"),
SPDLOG_FILENAME_T("test_logs\\dir1\\dir2\\dir23"))); SPDLOG_FILENAME_T("test_logs\\dir1\\dir2\\dir23")));
REQUIRE(try_create_dir(SPDLOG_FILENAME_T("test_logs\\..\\test_logs\\dir1\\dir5"), REQUIRE(
SPDLOG_FILENAME_T("test_logs\\dir1\\dir5"))); try_create_dir(SPDLOG_FILENAME_T("test_logs\\..\\test_logs\\dir1\\dir5"), SPDLOG_FILENAME_T("test_logs\\dir1\\dir5")));
#endif #endif
} }

View File

@ -31,8 +31,8 @@ TEST_CASE("daily_logger with dateonly calculator", "[daily_logger]") {
spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly"); spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly");
std::tm tm = spdlog::details::os::localtime(); std::tm tm = spdlog::details::os::localtime();
filename_memory_buf_t w; filename_memory_buf_t w;
spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}"), basename, spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}"), basename, tm.tm_year + 1900,
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); tm.tm_mon + 1, tm.tm_mday);
auto logger = spdlog::create<sink_type>("logger", basename, 0, 0); auto logger = spdlog::create<sink_type>("logger", basename, 0, 0);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
@ -62,8 +62,8 @@ TEST_CASE("daily_logger with custom calculator", "[daily_logger]") {
spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly"); spdlog::filename_t basename = SPDLOG_FILENAME_T("test_logs/daily_dateonly");
std::tm tm = spdlog::details::os::localtime(); std::tm tm = spdlog::details::os::localtime();
filename_memory_buf_t w; filename_memory_buf_t w;
spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), basename, spdlog::fmt_lib::format_to(std::back_inserter(w), SPDLOG_FILENAME_T("{}{:04d}{:02d}{:02d}"), basename, tm.tm_year + 1900,
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); tm.tm_mon + 1, tm.tm_mday);
auto logger = spdlog::create<sink_type>("logger", basename, 0, 0); auto logger = spdlog::create<sink_type>("logger", basename, 0, 0);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
@ -100,8 +100,8 @@ TEST_CASE("rotating_file_sink::calc_filename3", "[rotating_file_sink]") {
TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") { TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") {
// daily_YYYY-MM-DD_hh-mm.txt // daily_YYYY-MM-DD_hh-mm.txt
auto filename = spdlog::sinks::daily_filename_calculator::calc_filename(SPDLOG_FILENAME_T("daily.txt"), auto filename =
spdlog::details::os::localtime()); spdlog::sinks::daily_filename_calculator::calc_filename(SPDLOG_FILENAME_T("daily.txt"), spdlog::details::os::localtime());
// date regex based on https://www.regular-expressions.info/dates.html // date regex based on https://www.regular-expressions.info/dates.html
std::basic_regex<spdlog::filename_t::value_type> re( std::basic_regex<spdlog::filename_t::value_type> re(
SPDLOG_FILENAME_T(R"(^daily_(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\.txt$)")); SPDLOG_FILENAME_T(R"(^daily_(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\.txt$)"));
@ -113,11 +113,10 @@ TEST_CASE("daily_file_sink::daily_filename_calculator", "[daily_file_sink]") {
TEST_CASE("daily_file_sink::daily_filename_format_calculator", "[daily_file_sink]") { TEST_CASE("daily_file_sink::daily_filename_format_calculator", "[daily_file_sink]") {
std::tm tm = spdlog::details::os::localtime(); std::tm tm = spdlog::details::os::localtime();
// example-YYYY-MM-DD.log // example-YYYY-MM-DD.log
auto filename = auto filename = spdlog::sinks::daily_filename_format_calculator::calc_filename(SPDLOG_FILENAME_T("example-%Y-%m-%d.log"), tm);
spdlog::sinks::daily_filename_format_calculator::calc_filename(SPDLOG_FILENAME_T("example-%Y-%m-%d.log"), tm);
REQUIRE(filename == spdlog::fmt_lib::format(SPDLOG_FILENAME_T("example-{:04d}-{:02d}-{:02d}.log"), REQUIRE(filename == spdlog::fmt_lib::format(SPDLOG_FILENAME_T("example-{:04d}-{:02d}-{:02d}.log"), tm.tm_year + 1900,
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday)); tm.tm_mon + 1, tm.tm_mday));
} }
/* Test removal of old files */ /* Test removal of old files */

View File

@ -12,9 +12,7 @@
class failing_sink : public spdlog::sinks::base_sink<std::mutex> { class failing_sink : public spdlog::sinks::base_sink<std::mutex> {
protected: protected:
void sink_it_(const spdlog::details::log_msg &) final { void sink_it_(const spdlog::details::log_msg &) final { throw std::runtime_error("some error happened during log"); }
throw std::runtime_error("some error happened during log");
}
void flush_() final { throw std::runtime_error("some error happened during flush"); } void flush_() final { throw std::runtime_error("some error happened during flush"); }
}; };

View File

@ -55,10 +55,8 @@ TEST_CASE("eventlog", "[eventlog]") {
test_sink->set_pattern("%v"); test_sink->set_pattern("%v");
test_single_print([&test_logger](std::string const &msg) { test_logger.trace(msg); }, "my trace message", test_single_print([&test_logger](std::string const &msg) { test_logger.trace(msg); }, "my trace message", EVENTLOG_SUCCESS);
EVENTLOG_SUCCESS); test_single_print([&test_logger](std::string const &msg) { test_logger.debug(msg); }, "my debug message", EVENTLOG_SUCCESS);
test_single_print([&test_logger](std::string const &msg) { test_logger.debug(msg); }, "my debug message",
EVENTLOG_SUCCESS);
test_single_print([&test_logger](std::string const &msg) { test_logger.info(msg); }, "my info message", test_single_print([&test_logger](std::string const &msg) { test_logger.info(msg); }, "my info message",
EVENTLOG_INFORMATION_TYPE); EVENTLOG_INFORMATION_TYPE);
test_single_print([&test_logger](std::string const &msg) { test_logger.warn(msg); }, "my warn message", test_single_print([&test_logger](std::string const &msg) { test_logger.warn(msg); }, "my warn message",

View File

@ -80,22 +80,17 @@ TEST_CASE("file_helper_split_by_extension", "[file_helper::split_by_extension()]
test_split_ext(SPDLOG_FILENAME_T(".mylog.txt"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T(".mylog.txt"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T("")); test_split_ext(SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(".mylog"), SPDLOG_FILENAME_T(""));
test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("")); test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T(""));
test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), test_split_ext(SPDLOG_FILENAME_T("/aaa/bb.d/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bb.d/mylog"), SPDLOG_FILENAME_T(".txt"));
SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog"), test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T(""));
SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."), SPDLOG_FILENAME_T("aaa/bbb/ccc/mylog."),
SPDLOG_FILENAME_T(""));
test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog"), test_split_ext(SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog.txt"), SPDLOG_FILENAME_T("aaa/bbb/ccc/.mylog"),
SPDLOG_FILENAME_T(".txt")); SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog"), test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog.txt"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/mylog"),
SPDLOG_FILENAME_T(".txt")); SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), test_split_ext(SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T("/aaa/bbb/ccc/.mylog"), SPDLOG_FILENAME_T(""));
SPDLOG_FILENAME_T(""));
test_split_ext(SPDLOG_FILENAME_T("../mylog.txt"), SPDLOG_FILENAME_T("../mylog"), SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T("../mylog.txt"), SPDLOG_FILENAME_T("../mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt"), SPDLOG_FILENAME_T(".././mylog"), SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt"), SPDLOG_FILENAME_T(".././mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T(".././mylog.txt/xxx"), test_split_ext(SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T(".././mylog.txt/xxx"), SPDLOG_FILENAME_T(""));
SPDLOG_FILENAME_T(""));
test_split_ext(SPDLOG_FILENAME_T("/mylog.txt"), SPDLOG_FILENAME_T("/mylog"), SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T("/mylog.txt"), SPDLOG_FILENAME_T("/mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T("//mylog.txt"), SPDLOG_FILENAME_T("//mylog"), SPDLOG_FILENAME_T(".txt")); test_split_ext(SPDLOG_FILENAME_T("//mylog.txt"), SPDLOG_FILENAME_T("//mylog"), SPDLOG_FILENAME_T(".txt"));
test_split_ext(SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T("")); test_split_ext(SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T(""), SPDLOG_FILENAME_T(""));

View File

@ -22,8 +22,7 @@ TEST_CASE("simple_file_logger", "[simple_logger]") {
logger->flush(); logger->flush();
require_message_count(SIMPLE_LOG, 2); require_message_count(SIMPLE_LOG, 2);
using spdlog::details::os::default_eol; using spdlog::details::os::default_eol;
REQUIRE(file_contents(SIMPLE_LOG) == REQUIRE(file_contents(SIMPLE_LOG) == spdlog::fmt_lib::format("Test message 1{}Test message 2{}", default_eol, default_eol));
spdlog::fmt_lib::format("Test message 1{}Test message 2{}", default_eol, default_eol));
} }
TEST_CASE("flush_on", "[flush_on]") { TEST_CASE("flush_on", "[flush_on]") {
@ -42,9 +41,8 @@ TEST_CASE("flush_on", "[flush_on]") {
require_message_count(SIMPLE_LOG, 3); require_message_count(SIMPLE_LOG, 3);
using spdlog::details::os::default_eol; using spdlog::details::os::default_eol;
REQUIRE(file_contents(SIMPLE_LOG) == REQUIRE(file_contents(SIMPLE_LOG) == spdlog::fmt_lib::format("Should not be flushed{}Test message 1{}Test message 2{}",
spdlog::fmt_lib::format("Should not be flushed{}Test message 1{}Test message 2{}", default_eol, default_eol, default_eol, default_eol, default_eol));
default_eol));
} }
TEST_CASE("rotating_file_logger1", "[rotating_logger]") { TEST_CASE("rotating_file_logger1", "[rotating_logger]") {

View File

@ -37,8 +37,7 @@ TEST_CASE("test_sink_levels", "[log_level]") {
auto get_expected_messages(spdlog::level level) { auto get_expected_messages(spdlog::level level) {
// expected messages for each level // expected messages for each level
static const std::map<spdlog::level, std::vector<std::string>> messages = { static const std::map<spdlog::level, std::vector<std::string>> messages = {
{spdlog::level::trace, {spdlog::level::trace, {"trace hello", "debug hello", "info hello", "warning hello", "error hello", "critical hello"}},
{"trace hello", "debug hello", "info hello", "warning hello", "error hello", "critical hello"}},
{spdlog::level::debug, {"debug hello", "info hello", "warning hello", "error hello", "critical hello"}}, {spdlog::level::debug, {"debug hello", "info hello", "warning hello", "error hello", "critical hello"}},
{spdlog::level::info, {"info hello", "warning hello", "error hello", "critical hello"}}, {spdlog::level::info, {"info hello", "warning hello", "error hello", "critical hello"}},
{spdlog::level::warn, {"warning hello", "error hello", "critical hello"}}, {spdlog::level::warn, {"warning hello", "error hello", "critical hello"}},

View File

@ -42,15 +42,14 @@ TEST_CASE("short level", "[pattern_formatter]") {
} }
TEST_CASE("name", "[pattern_formatter]") { TEST_CASE("name", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%n] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n");
"[pattern_tester] Some message\n");
} }
TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") { TEST_CASE("date MM/DD/YY ", "[pattern_formatter]") {
auto now_tm = spdlog::details::os::localtime(); auto now_tm = spdlog::details::os::localtime();
std::stringstream oss; std::stringstream oss;
oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) << now_tm.tm_mday << "/" oss << std::setfill('0') << std::setw(2) << now_tm.tm_mon + 1 << "/" << std::setw(2) << now_tm.tm_mday << "/" << std::setw(2)
<< std::setw(2) << (now_tm.tm_year + 1900) % 1000 << " Some message\n"; << (now_tm.tm_year + 1900) % 1000 << " Some message\n";
REQUIRE(log_to_str("Some message", "%D %v", spdlog::pattern_time_type::local, "\n") == oss.str()); REQUIRE(log_to_str("Some message", "%D %v", spdlog::pattern_time_type::local, "\n") == oss.str());
} }
@ -126,24 +125,18 @@ TEST_CASE("color range test6", "[pattern_formatter]") {
// //
TEST_CASE("level_left_padded", "[pattern_formatter]") { TEST_CASE("level_left_padded", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%8l] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%8l] %v", spdlog::pattern_time_type::local, "\n") == "[ info] Some message\n");
"[ info] Some message\n"); REQUIRE(log_to_str("Some message", "[%8!l] %v", spdlog::pattern_time_type::local, "\n") == "[ info] Some message\n");
REQUIRE(log_to_str("Some message", "[%8!l] %v", spdlog::pattern_time_type::local, "\n") ==
"[ info] Some message\n");
} }
TEST_CASE("level_right_padded", "[pattern_formatter]") { TEST_CASE("level_right_padded", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%-8l] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%-8l] %v", spdlog::pattern_time_type::local, "\n") == "[info ] Some message\n");
"[info ] Some message\n"); REQUIRE(log_to_str("Some message", "[%-8!l] %v", spdlog::pattern_time_type::local, "\n") == "[info ] Some message\n");
REQUIRE(log_to_str("Some message", "[%-8!l] %v", spdlog::pattern_time_type::local, "\n") ==
"[info ] Some message\n");
} }
TEST_CASE("level_center_padded", "[pattern_formatter]") { TEST_CASE("level_center_padded", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%=8l] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%=8l] %v", spdlog::pattern_time_type::local, "\n") == "[ info ] Some message\n");
"[ info ] Some message\n"); REQUIRE(log_to_str("Some message", "[%=8!l] %v", spdlog::pattern_time_type::local, "\n") == "[ info ] Some message\n");
REQUIRE(log_to_str("Some message", "[%=8!l] %v", spdlog::pattern_time_type::local, "\n") ==
"[ info ] Some message\n");
} }
TEST_CASE("short level_left_padded", "[pattern_formatter]") { TEST_CASE("short level_left_padded", "[pattern_formatter]") {
@ -162,20 +155,17 @@ TEST_CASE("short level_center_padded", "[pattern_formatter]") {
} }
TEST_CASE("left_padded_short", "[pattern_formatter]") { TEST_CASE("left_padded_short", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%3n] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n");
"[pattern_tester] Some message\n");
REQUIRE(log_to_str("Some message", "[%3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); REQUIRE(log_to_str("Some message", "[%3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n");
} }
TEST_CASE("right_padded_short", "[pattern_formatter]") { TEST_CASE("right_padded_short", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%-3n] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%-3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n");
"[pattern_tester] Some message\n");
REQUIRE(log_to_str("Some message", "[%-3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); REQUIRE(log_to_str("Some message", "[%-3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n");
} }
TEST_CASE("center_padded_short", "[pattern_formatter]") { TEST_CASE("center_padded_short", "[pattern_formatter]") {
REQUIRE(log_to_str("Some message", "[%=3n] %v", spdlog::pattern_time_type::local, "\n") == REQUIRE(log_to_str("Some message", "[%=3n] %v", spdlog::pattern_time_type::local, "\n") == "[pattern_tester] Some message\n");
"[pattern_tester] Some message\n");
REQUIRE(log_to_str("Some message", "[%=3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n"); REQUIRE(log_to_str("Some message", "[%=3!n] %v", spdlog::pattern_time_type::local, "\n") == "[pat] Some message\n");
} }
@ -220,13 +210,11 @@ TEST_CASE("padding_truncate_funcname", "[pattern_formatter]") {
auto formatter = std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter(pattern)); auto formatter = std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter(pattern));
test_sink.set_formatter(std::move(formatter)); test_sink.set_formatter(std::move(formatter));
spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, "message"};
"message"};
test_sink.log(msg1); test_sink.log(msg1);
REQUIRE(test_sink.lines()[0] == "message [ func]"); REQUIRE(test_sink.lines()[0] == "message [ func]");
spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "function"}, "test_logger", spdlog::level::info, spdlog::details::log_msg msg2{spdlog::source_loc{"ignored", 1, "function"}, "test_logger", spdlog::level::info, "message"};
"message"};
test_sink.log(msg2); test_sink.log(msg2);
REQUIRE(test_sink.lines()[1] == "message [funct]"); REQUIRE(test_sink.lines()[1] == "message [funct]");
} }
@ -238,8 +226,7 @@ TEST_CASE("padding_funcname", "[pattern_formatter]") {
auto formatter = std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter(pattern)); auto formatter = std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter(pattern));
test_sink.set_formatter(std::move(formatter)); test_sink.set_formatter(std::move(formatter));
spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, spdlog::details::log_msg msg1{spdlog::source_loc{"ignored", 1, "func"}, "test_logger", spdlog::level::info, "message"};
"message"};
test_sink.log(msg1); test_sink.log(msg1);
REQUIRE(test_sink.lines()[0] == "message [ func]"); REQUIRE(test_sink.lines()[0] == "message [ func]");
@ -293,8 +280,7 @@ TEST_CASE("clone-formatter", "[pattern_formatter]") {
TEST_CASE("clone-formatter-2", "[pattern_formatter]") { TEST_CASE("clone-formatter-2", "[pattern_formatter]") {
using spdlog::pattern_time_type; using spdlog::pattern_time_type;
auto formatter_1 = auto formatter_1 = std::make_shared<spdlog::pattern_formatter>("%D %X [%] [%n] %v", pattern_time_type::utc, "xxxxxx\n");
std::make_shared<spdlog::pattern_formatter>("%D %X [%] [%n] %v", pattern_time_type::utc, "xxxxxx\n");
auto formatter_2 = formatter_1->clone(); auto formatter_2 = formatter_1->clone();
std::string logger_name = "test2"; std::string logger_name = "test2";
spdlog::details::log_msg msg(logger_name, spdlog::level::info, "some message"); spdlog::details::log_msg msg(logger_name, spdlog::level::info, "some message");
@ -328,9 +314,7 @@ public:
std::string some_txt; std::string some_txt;
std::unique_ptr<custom_flag_formatter> clone() const override { std::unique_ptr<custom_flag_formatter> clone() const override { return std::make_unique<custom_test_flag>(some_txt); }
return std::make_unique<custom_test_flag>(some_txt);
}
}; };
// test clone with custom flag formatters // test clone with custom flag formatters
TEST_CASE("clone-custom_formatter", "[pattern_formatter]") { TEST_CASE("clone-custom_formatter", "[pattern_formatter]") {
@ -345,8 +329,7 @@ TEST_CASE("clone-custom_formatter", "[pattern_formatter]") {
formatter_1->format(msg, formatted_1); formatter_1->format(msg, formatted_1);
formatter_2->format(msg, formatted_2); formatter_2->format(msg, formatted_2);
auto expected = auto expected = spdlog::fmt_lib::format("[logger-name] [custom_output] some message{}", spdlog::details::os::default_eol);
spdlog::fmt_lib::format("[logger-name] [custom_output] some message{}", spdlog::details::os::default_eol);
REQUIRE(to_string_view(formatted_1) == expected); REQUIRE(to_string_view(formatted_1) == expected);
REQUIRE(to_string_view(formatted_2) == expected); REQUIRE(to_string_view(formatted_2) == expected);
@ -416,8 +399,7 @@ TEST_CASE("custom flags", "[pattern_formatter]") {
spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message");
formatter->format(msg, formatted); formatter->format(msg, formatted);
auto expected = auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [custom2] some message{}", spdlog::details::os::default_eol);
spdlog::fmt_lib::format("[logger-name] [custom1] [custom2] some message{}", spdlog::details::os::default_eol);
REQUIRE(to_string_view(formatted) == expected); REQUIRE(to_string_view(formatted) == expected);
} }
@ -432,8 +414,8 @@ TEST_CASE("custom flags-padding", "[pattern_formatter]") {
spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message"); spdlog::details::log_msg msg(spdlog::source_loc{}, "logger-name", spdlog::level::info, "some message");
formatter->format(msg, formatted); formatter->format(msg, formatted);
auto expected = spdlog::fmt_lib::format("[logger-name] [custom1] [ custom2] some message{}", auto expected =
spdlog::details::os::default_eol); spdlog::fmt_lib::format("[logger-name] [custom1] [ custom2] some message{}", spdlog::details::os::default_eol);
REQUIRE(to_string_view(formatted) == expected); REQUIRE(to_string_view(formatted) == expected);
} }

View File

@ -28,8 +28,7 @@ TEST_CASE("apply_all", "[registry]") {
spdlog::drop_all(); spdlog::drop_all();
auto logger = std::make_shared<spdlog::logger>(tested_logger_name, std::make_shared<spdlog::sinks::null_sink_st>()); auto logger = std::make_shared<spdlog::logger>(tested_logger_name, std::make_shared<spdlog::sinks::null_sink_st>());
spdlog::register_logger(logger); spdlog::register_logger(logger);
auto logger2 = auto logger2 = std::make_shared<spdlog::logger>(tested_logger_name2, std::make_shared<spdlog::sinks::null_sink_st>());
std::make_shared<spdlog::logger>(tested_logger_name2, std::make_shared<spdlog::sinks::null_sink_st>());
spdlog::register_logger(logger2); spdlog::register_logger(logger2);
int counter = 0; int counter = 0;
@ -96,8 +95,7 @@ TEST_CASE("disable automatic registration", "[registry]") {
spdlog::set_level(level); spdlog::set_level(level);
// but disable automatic registration // but disable automatic registration
spdlog::set_automatic_registration(false); spdlog::set_automatic_registration(false);
auto logger1 = auto logger1 = spdlog::create<spdlog::sinks::daily_file_sink_st>(tested_logger_name, SPDLOG_FILENAME_T("filename"), 11, 59);
spdlog::create<spdlog::sinks::daily_file_sink_st>(tested_logger_name, SPDLOG_FILENAME_T("filename"), 11, 59);
auto logger2 = spdlog::create_async<spdlog::sinks::stdout_color_sink_mt>(tested_logger_name2); auto logger2 = spdlog::create_async<spdlog::sinks::stdout_color_sink_mt>(tested_logger_name2);
// loggers should not be part of the registry // loggers should not be part of the registry
REQUIRE_FALSE(spdlog::get(tested_logger_name)); REQUIRE_FALSE(spdlog::get(tested_logger_name));