Updated clang-format

Merged with origin
This commit is contained in:
gabime
2023-09-25 16:05:07 +03:00
parent 218e859867
commit dcd5904bdc
94 changed files with 1505 additions and 1445 deletions

View File

@@ -48,8 +48,8 @@ struct async_factory_impl {
}
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
auto new_logger =
std::make_shared<async_logger>(std::move(logger_name), std::move(sink), std::move(tp), OverflowPolicy);
auto new_logger = std::make_shared<async_logger>(std::move(logger_name), std::move(sink),
std::move(tp), OverflowPolicy);
registry_inst.initialize_logger(new_logger);
return new_logger;
}
@@ -59,13 +59,17 @@ using async_factory = async_factory_impl<async_overflow_policy::block>;
using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
template <typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name, SinkArgs &&...sink_args) {
return async_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name,
SinkArgs &&...sink_args) {
return async_factory::create<Sink>(std::move(logger_name),
std::forward<SinkArgs>(sink_args)...);
}
template <typename Sink, typename... SinkArgs>
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name, SinkArgs &&...sink_args) {
return async_factory_nonblock::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name,
SinkArgs &&...sink_args) {
return async_factory_nonblock::create<Sink>(std::move(logger_name),
std::forward<SinkArgs>(sink_args)...);
}
// set global thread pool.
@@ -73,11 +77,13 @@ inline void init_thread_pool(size_t q_size,
size_t thread_count,
std::function<void()> on_thread_start,
std::function<void()> on_thread_stop) {
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start, on_thread_stop);
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start,
on_thread_stop);
details::registry::instance().set_tp(std::move(tp));
}
inline void init_thread_pool(size_t q_size, size_t thread_count, std::function<void()> on_thread_start) {
inline void
init_thread_pool(size_t q_size, size_t thread_count, std::function<void()> on_thread_start) {
init_thread_pool(q_size, thread_count, on_thread_start, [] {});
}
@@ -87,5 +93,7 @@ inline void init_thread_pool(size_t q_size, size_t thread_count) {
}
// get the global thread pool.
inline std::shared_ptr<spdlog::details::thread_pool> thread_pool() { return details::registry::instance().get_tp(); }
inline std::shared_ptr<spdlog::details::thread_pool> thread_pool() {
return details::registry::instance().get_tp();
}
} // namespace spdlog

View File

@@ -30,7 +30,8 @@ namespace details {
class thread_pool;
}
class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>, public logger {
class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>,
public logger {
friend class details::thread_pool;
public:
@@ -40,9 +41,9 @@ public:
It end,
std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block)
: logger(std::move(logger_name), begin, end),
thread_pool_(std::move(tp)),
overflow_policy_(overflow_policy) {}
: logger(std::move(logger_name), begin, end)
, thread_pool_(std::move(tp))
, overflow_policy_(overflow_policy) {}
async_logger(std::string logger_name,
sinks_init_list sinks_list,

View File

@@ -32,7 +32,9 @@ inline void load_argv_levels(int argc, const char **argv) {
}
}
inline void load_argv_levels(int argc, char **argv) { load_argv_levels(argc, const_cast<const char **>(argv)); }
inline void load_argv_levels(int argc, char **argv) {
load_argv_levels(argc, const_cast<const char **>(argv));
}
} // namespace cfg
} // namespace spdlog

View File

@@ -53,7 +53,8 @@
#include <spdlog/fmt/fmt.h>
#if !defined(SPDLOG_USE_STD_FORMAT) && FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8
#if !defined(SPDLOG_USE_STD_FORMAT) && \
FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8
#define SPDLOG_FMT_RUNTIME(format_string) fmt::runtime(format_string)
#if defined(SPDLOG_WCHAR_FILENAMES)
#include <spdlog/fmt/xchar.h>
@@ -176,7 +177,9 @@ using atomic_level_t = std::atomic<level>;
{ "T", "D", "I", "W", "E", "C", "O" }
#endif
[[nodiscard]] constexpr size_t level_to_number(level lvl) noexcept { return static_cast<size_t>(lvl); }
[[nodiscard]] constexpr size_t level_to_number(level lvl) noexcept {
return static_cast<size_t>(lvl);
}
constexpr auto levels_count = level_to_number(level::n_levels);
constexpr std::array<string_view_t, levels_count> level_string_views SPDLOG_LEVEL_NAMES;
constexpr std::array<const char *, levels_count> short_level_names SPDLOG_SHORT_LEVEL_NAMES;
@@ -223,19 +226,24 @@ private:
struct source_loc {
constexpr source_loc() = default;
constexpr source_loc(const char *filename_in, std::uint_least32_t line_in, const char *funcname_in)
: filename{filename_in},
line{line_in},
funcname{funcname_in} {}
constexpr source_loc(const char *filename_in,
std::uint_least32_t line_in,
const char *funcname_in)
: filename{filename_in}
, line{line_in}
, funcname{funcname_in} {}
#ifdef SPDLOG_HAVE_STD_SOURCE_LOCATION
static constexpr source_loc current(const std::source_location source_location = std::source_location::current()) {
return source_loc{source_location.file_name(), source_location.line(), source_location.function_name()};
static constexpr source_loc
current(const std::source_location source_location = std::source_location::current()) {
return source_loc{source_location.file_name(), source_location.line(),
source_location.function_name()};
}
#elif defined(SPDLOG_HAVE_EXPERIMENTAL_SOURCE_LOCATION)
static constexpr source_loc
current(const std::experimental::source_location source_location = std::experimental::source_location::current()) {
return source_loc{source_location.file_name(), source_location.line(), source_location.function_name()};
static constexpr source_loc current(const std::experimental::source_location source_location =
std::experimental::source_location::current()) {
return source_loc{source_location.file_name(), source_location.line(),
source_location.function_name()};
}
#else // no source location support
static constexpr source_loc current() { return source_loc{}; }
@@ -254,22 +262,23 @@ struct loc_with_fmt {
string_view_t fmt_string;
template <typename S, typename = is_convertible_to_sv<S>>
constexpr loc_with_fmt(S fmt_str, source_loc loc = source_loc::current()) noexcept
: loc(loc),
fmt_string(fmt_str) {}
: loc(loc)
, fmt_string(fmt_str) {}
#ifndef SPDLOG_USE_STD_FORMAT
constexpr loc_with_fmt(fmt::runtime_format_string<char> fmt_str, source_loc loc = source_loc::current()) noexcept
: loc(loc),
fmt_string(fmt_str.str) {}
constexpr loc_with_fmt(fmt::runtime_format_string<char> fmt_str,
source_loc loc = source_loc::current()) noexcept
: loc(loc)
, fmt_string(fmt_str.str) {}
#endif
};
struct file_event_handlers {
file_event_handlers()
: before_open(nullptr),
after_open(nullptr),
before_close(nullptr),
after_close(nullptr) {}
: before_open(nullptr)
, after_open(nullptr)
, before_close(nullptr)
, after_close(nullptr) {}
std::function<void(const filename_t &filename)> before_open;
std::function<void(const filename_t &filename, std::FILE *file_stream)> after_open;
@@ -285,32 +294,39 @@ namespace details {
return spdlog::string_view_t{buf.data(), buf.size()};
}
[[nodiscard]] constexpr spdlog::string_view_t to_string_view(spdlog::string_view_t str) noexcept { return str; }
[[nodiscard]] constexpr spdlog::string_view_t to_string_view(spdlog::string_view_t str) noexcept {
return str;
}
#if defined(SPDLOG_WCHAR_FILENAMES)
[[nodiscard]] constexpr spdlog::wstring_view_t to_string_view(const wmemory_buf_t &buf) noexcept {
return spdlog::wstring_view_t{buf.data(), buf.size()};
}
[[nodiscard]] constexpr spdlog::wstring_view_t to_string_view(spdlog::wstring_view_t str) noexcept { return str; }
[[nodiscard]] constexpr spdlog::wstring_view_t to_string_view(spdlog::wstring_view_t str) noexcept {
return str;
}
#endif
// convert format_string<...> to string_view depending on format lib versions
#if defined(SPDLOG_USE_STD_FORMAT)
#if __cpp_lib_format >= 202207L // std::format and __cpp_lib_format >= 202207L
template <typename T, typename... Args>
[[nodiscard]] constexpr std::basic_string_view<T> to_string_view(std::basic_format_string<T, Args...> fmt) noexcept {
[[nodiscard]] constexpr std::basic_string_view<T>
to_string_view(std::basic_format_string<T, Args...> fmt) noexcept {
return fmt.get();
}
#else // std::format and __cpp_lib_format < 202207L
template <typename T, typename... Args>
[[nodiscard]] constexpr std::basic_string_view<T> to_string_view(std::basic_format_string<T, Args...> fmt) noexcept {
[[nodiscard]] constexpr std::basic_string_view<T>
to_string_view(std::basic_format_string<T, Args...> fmt) noexcept {
return fmt;
}
#endif
#else // {fmt} version
template <typename T, typename... Args>
[[nodiscard]] constexpr fmt::basic_string_view<T> to_string_view(fmt::basic_format_string<T, Args...> fmt) noexcept {
[[nodiscard]] constexpr fmt::basic_string_view<T>
to_string_view(fmt::basic_format_string<T, Args...> fmt) noexcept {
return fmt;
}
#endif

View File

@@ -25,8 +25,7 @@ public:
explicit circular_q(size_t max_items)
: max_items_(max_items + 1) // one item is reserved as marker for full q
,
v_(max_items_) {}
, v_(max_items_) {}
circular_q(const circular_q &) = default;
circular_q &operator=(const circular_q &) = default;

View File

@@ -68,7 +68,8 @@ constexpr unsigned int count_digits_fallback(T n) {
template <typename T>
inline unsigned int count_digits(T n) {
using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
using count_type =
typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
#ifdef SPDLOG_USE_STD_FORMAT
return count_digits_fallback(static_cast<count_type>(n));
#else

View File

@@ -10,7 +10,11 @@ namespace spdlog {
namespace details {
struct SPDLOG_API log_msg {
log_msg() = default;
log_msg(log_clock::time_point log_time, source_loc loc, string_view_t logger_name, level lvl, string_view_t msg);
log_msg(log_clock::time_point log_time,
source_loc loc,
string_view_t logger_name,
level lvl,
string_view_t msg);
log_msg(source_loc loc, string_view_t logger_name, level lvl, string_view_t msg);
log_msg(string_view_t logger_name, level lvl, string_view_t msg);
log_msg(const log_msg &other) = default;

View File

@@ -41,7 +41,8 @@ constexpr static const char *default_eol = SPDLOG_EOL;
#endif
constexpr static const char folder_seps[] = SPDLOG_FOLDER_SEPS;
constexpr static const filename_t::value_type folder_seps_filename[] = SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS);
constexpr static const filename_t::value_type folder_seps_filename[] =
SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS);
// fopen_s on non windows for writing
SPDLOG_API bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);

View File

@@ -7,7 +7,8 @@
//
// RAII over the owned thread:
// creates the thread on construction.
// stops and joins the thread on destruction (if the thread is executing a callback, wait for it to finish first).
// stops and joins the thread on destruction (if the thread is executing a callback, wait for it
// to finish first).
#include <chrono>
#include <condition_variable>
@@ -23,7 +24,8 @@ namespace details {
class SPDLOG_API periodic_worker {
public:
template <typename Rep, typename Period>
periodic_worker(const std::function<void()> &callback_fun, std::chrono::duration<Rep, Period> interval) {
periodic_worker(const std::function<void()> &callback_fun,
std::chrono::duration<Rep, Period> interval) {
active_ = (interval > std::chrono::duration<Rep, Period>::zero());
if (!active_) {
return;

View File

@@ -38,7 +38,8 @@ public:
// Return raw ptr to the default logger.
// To be used directly by the spdlog default api (e.g. spdlog::info)
// This make the default API faster, but cannot be used concurrently with set_default_logger().
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
// e.g do not call set_default_logger() from one thread while calling spdlog::info() from
// another.
logger *get_default_raw();
// set default logger.

View File

@@ -34,8 +34,9 @@ class tcp_client {
static void throw_winsock_error_(const std::string &msg, int last_error) {
char buf[512];
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf,
(sizeof(buf) / sizeof(char)), NULL);
throw_spdlog_ex(fmt_lib::format("tcp_sink - {}: {}", msg, buf));
}
@@ -104,7 +105,8 @@ public:
// set TCP_NODELAY
int enable_flag = 1;
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag), sizeof(enable_flag));
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag),
sizeof(enable_flag));
}
// Send exactly n_bytes of the given data.
@@ -113,7 +115,8 @@ public:
size_t bytes_sent = 0;
while (bytes_sent < n_bytes) {
const int send_flags = 0;
auto write_result = ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
auto write_result =
::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
if (write_result == SOCKET_ERROR) {
int last_error = ::WSAGetLastError();
close();

View File

@@ -84,11 +84,13 @@ public:
// set TCP_NODELAY
int enable_flag = 1;
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag), sizeof(enable_flag));
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag),
sizeof(enable_flag));
// prevent sigpipe on systems where MSG_NOSIGNAL is not available
#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast<char *>(&enable_flag), sizeof(enable_flag));
::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast<char *>(&enable_flag),
sizeof(enable_flag));
#endif
#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
@@ -106,7 +108,8 @@ public:
#else
const int send_flags = 0;
#endif
auto write_result = ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags);
auto write_result =
::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags);
if (write_result < 0) {
close();
throw_spdlog_ex("write(2) failed", errno);

View File

@@ -38,9 +38,9 @@ struct async_msg : log_msg_buffer {
// support for vs2013 move
#if defined(_MSC_VER) && _MSC_VER <= 1800
async_msg(async_msg &&other)
: log_msg_buffer(std::move(other)),
msg_type(other.msg_type),
worker_ptr(std::move(other.worker_ptr)) {}
: log_msg_buffer(std::move(other))
, msg_type(other.msg_type)
, worker_ptr(std::move(other.worker_ptr)) {}
async_msg &operator=(async_msg &&other) {
*static_cast<log_msg_buffer *>(this) = std::move(other);
@@ -55,14 +55,14 @@ struct async_msg : log_msg_buffer {
// construct from log_msg with given type
async_msg(async_logger_ptr &&worker, async_msg_type the_type, const details::log_msg &m)
: log_msg_buffer{m},
msg_type{the_type},
worker_ptr{std::move(worker)} {}
: log_msg_buffer{m}
, msg_type{the_type}
, worker_ptr{std::move(worker)} {}
async_msg(async_logger_ptr &&worker, async_msg_type the_type)
: log_msg_buffer{},
msg_type{the_type},
worker_ptr{std::move(worker)} {}
: log_msg_buffer{}
, msg_type{the_type}
, worker_ptr{std::move(worker)} {}
explicit async_msg(async_msg_type the_type)
: async_msg{nullptr, the_type} {}
@@ -86,7 +86,9 @@ public:
thread_pool(const thread_pool &) = delete;
thread_pool &operator=(thread_pool &&) = delete;
void post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy);
void post_log(async_logger_ptr &&worker_ptr,
const details::log_msg &msg,
async_overflow_policy overflow_policy);
void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy);
size_t overrun_counter();
void reset_overrun_counter();

View File

@@ -38,8 +38,9 @@ class udp_client {
static void throw_winsock_error_(const std::string &msg, int last_error) {
char buf[512];
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf,
(sizeof(buf) / sizeof(char)), NULL);
throw_spdlog_ex(fmt_lib::format("udp_sink - {}: {}", msg, buf));
}
@@ -73,8 +74,8 @@ public:
}
int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value),
sizeof(option_value)) < 0) {
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0) {
int last_error = ::WSAGetLastError();
cleanup_();
throw_winsock_error_("error: setsockopt(SO_SNDBUF) Failed!", last_error);
@@ -87,7 +88,8 @@ public:
void send(const char *data, size_t n_bytes) {
socklen_t tolen = sizeof(struct sockaddr);
if (::sendto(socket_, data, static_cast<int>(n_bytes), 0, (struct sockaddr *)&addr_, tolen) == -1) {
if (::sendto(socket_, data, static_cast<int>(n_bytes), 0, (struct sockaddr *)&addr_,
tolen) == -1) {
throw_spdlog_ex("sendto(2) failed", errno);
}
}

View File

@@ -45,8 +45,8 @@ public:
}
int option_value = TX_BUFFER_SIZE;
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&option_value),
sizeof(option_value)) < 0) {
if (::setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char *>(&option_value), sizeof(option_value)) < 0) {
cleanup_();
throw_spdlog_ex("error: setsockopt(SO_SNDBUF) Failed!");
}
@@ -71,7 +71,8 @@ public:
void send(const char *data, size_t n_bytes) {
ssize_t toslen = 0;
socklen_t tolen = sizeof(struct sockaddr);
if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) == -1) {
if ((toslen = ::sendto(socket_, data, n_bytes, 0, (struct sockaddr *)&sockAddr_, tolen)) ==
-1) {
throw_spdlog_ex("sendto(2) failed", errno);
}
}

View File

@@ -43,9 +43,9 @@ template <typename It>
class dump_info {
public:
dump_info(It range_begin, It range_end, size_t size_per_line)
: begin_(range_begin),
end_(range_end),
size_per_line_(size_per_line) {}
: begin_(range_begin)
, end_(range_end)
, size_per_line_(size_per_line) {}
// do not use begin() and end() to avoid collision with fmt/ranges
It get_begin() const { return begin_; }
@@ -62,7 +62,8 @@ private:
template <typename Container>
inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container,
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;
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
}
@@ -70,10 +71,11 @@ inline details::dump_info<typename Container::const_iterator> to_hex(const Conta
#if __cpp_lib_span >= 202002L
template <typename Value, size_t Extent>
inline details::dump_info<typename std::span<Value, Extent>::iterator> to_hex(const std::span<Value, Extent> &container,
size_t size_per_line = 32) {
inline details::dump_info<typename std::span<Value, Extent>::iterator>
to_hex(const std::span<Value, Extent> &container, size_t size_per_line = 32) {
using Container = std::span<Value, Extent>;
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::iterator;
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
}
@@ -82,7 +84,8 @@ inline details::dump_info<typename std::span<Value, Extent>::iterator> to_hex(co
// create dump_info from ranges
template <typename It>
inline details::dump_info<It> to_hex(const It range_begin, const It range_end, size_t size_per_line = 32) {
inline details::dump_info<It>
to_hex(const It range_begin, const It range_end, size_t size_per_line = 32) {
return details::dump_info<It>(range_begin, range_end, size_per_line);
}
@@ -155,7 +158,8 @@ struct formatter<spdlog::details::dump_info<T>, char> {
for (auto i = the_range.get_begin(); i != the_range.get_end(); i++) {
auto ch = static_cast<unsigned char>(*i);
if (put_newlines && (i == the_range.get_begin() || i - start_of_line >= size_per_line)) {
if (put_newlines &&
(i == the_range.get_begin() || i - start_of_line >= size_per_line)) {
if (show_ascii && i != the_range.get_begin()) {
*inserter++ = delimiter;
*inserter++ = delimiter;

View File

@@ -5,8 +5,8 @@
#pragma once
//
// include bundled or external copy of fmtlib's std support (for formatting e.g. std::filesystem::path, std::thread::id,
// std::monostate, std::variant, ...)
// include bundled or external copy of fmtlib's std support (for formatting e.g.
// std::filesystem::path, std::thread::id, std::monostate, std::variant, ...)
//
#if !defined(SPDLOG_USE_STD_FORMAT)

View File

@@ -22,17 +22,18 @@
#include <vector>
#ifndef SPDLOG_NO_EXCEPTIONS
#define SPDLOG_LOGGER_CATCH(location) \
catch (const std::exception &ex) { \
if (!location.empty()) { \
err_handler_(fmt_lib::format("{} [{}({})]", ex.what(), location.filename, location.line)); \
} else { \
err_handler_(ex.what()); \
} \
} \
catch (...) { \
err_handler_("Rethrowing unknown exception in logger"); \
throw; \
#define SPDLOG_LOGGER_CATCH(location) \
catch (const std::exception &ex) { \
if (!location.empty()) { \
err_handler_( \
fmt_lib::format("{} [{}({})]", ex.what(), location.filename, location.line)); \
} else { \
err_handler_(ex.what()); \
} \
} \
catch (...) { \
err_handler_("Rethrowing unknown exception in logger"); \
throw; \
}
#else
#define SPDLOG_LOGGER_CATCH(location)
@@ -49,8 +50,8 @@ public:
// Logger with range on sinks
template <typename It>
logger(std::string name, It begin, It end)
: name_(std::move(name)),
sinks_(begin, end) {}
: name_(std::move(name))
, sinks_(begin, end) {}
// Logger with single sink
logger(std::string name, sink_ptr single_sink)
@@ -76,7 +77,8 @@ public:
template <typename... Args>
void log(level lvl, format_string_t<Args...> fmt, Args &&...args) {
if (should_log(lvl)) {
log_with_format_(source_loc{}, lvl, details::to_string_view(fmt), std::forward<Args>(args)...);
log_with_format_(source_loc{}, lvl, details::to_string_view(fmt),
std::forward<Args>(args)...);
}
}
@@ -140,17 +142,29 @@ public:
// log functions with no format string, just string
void trace(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::trace, msg); }
void trace(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::trace, msg);
}
void debug(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::debug, msg); }
void debug(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::debug, msg);
}
void info(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::info, msg); }
void info(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::info, msg);
}
void warn(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::warn, msg); }
void warn(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::warn, msg);
}
void error(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::err, msg); }
void error(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::err, msg);
}
void critical(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::critical, msg); }
void critical(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::critical, msg);
}
#else
template <typename... Args>
void trace(format_string_t<Args...> fmt, Args &&...args) {
@@ -197,7 +211,9 @@ public:
#endif
// return true if logging is enabled for the given level.
[[nodiscard]] bool should_log(level msg_level) const { return msg_level >= level_.load(std::memory_order_relaxed); }
[[nodiscard]] bool should_log(level msg_level) const {
return msg_level >= level_.load(std::memory_order_relaxed);
}
// set the level of logging
void set_level(level level);
@@ -241,7 +257,8 @@ protected:
spdlog::atomic_level_t flush_level_{level::off};
err_handler custom_err_handler_{nullptr};
// common implementation for after templated public api has been resolved to format string and args
// common implementation for after templated public api has been resolved to format string and
// args
template <typename... Args>
void log_with_format_(source_loc loc, level lvl, string_view_t fmt, Args &&...args) {
assert(should_log(lvl));

View File

@@ -25,10 +25,10 @@ struct padding_info {
padding_info() = default;
padding_info(size_t width, padding_info::pad_side side, bool truncate)
: width_(width),
side_(side),
truncate_(truncate),
enabled_(true) {}
: width_(width)
, side_(side)
, truncate_(truncate)
, enabled_(true) {}
bool enabled() const { return enabled_; }
size_t width_ = 0;
@@ -43,7 +43,8 @@ public:
: padinfo_(padinfo) {}
flag_formatter() = default;
virtual ~flag_formatter() = default;
virtual void format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) = 0;
virtual void
format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) = 0;
protected:
padding_info padinfo_;
@@ -55,7 +56,9 @@ class SPDLOG_API custom_flag_formatter : public details::flag_formatter {
public:
virtual std::unique_ptr<custom_flag_formatter> clone() const = 0;
void set_padding_info(const details::padding_info &padding) { flag_formatter::padinfo_ = padding; }
void set_padding_info(const details::padding_info &padding) {
flag_formatter::padinfo_ = padding;
}
};
class SPDLOG_API pattern_formatter final : public formatter {
@@ -102,7 +105,8 @@ private:
// Extract given pad spec (e.g. %8X)
// Advance the given it pass the end of the padding spec found (if any)
// Return padding.
static details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end);
static details::padding_info handle_padspec_(std::string::const_iterator &it,
std::string::const_iterator end);
void compile_pattern_(const std::string &pattern);
};

View File

@@ -27,14 +27,15 @@ namespace sinks {
/*
* Android sink
* (logging using __android_log_write or __android_log_buf_write depending on the specified BufferID)
* (logging using __android_log_write or __android_log_buf_write depending on the specified
* BufferID)
*/
template <typename Mutex, int BufferID = log_id::LOG_ID_MAIN>
class android_sink final : public base_sink<Mutex> {
public:
explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)
: tag_(std::move(tag)),
use_raw_msg_(use_raw_msg) {}
: tag_(std::move(tag))
, use_raw_msg_(use_raw_msg) {}
protected:
void sink_it_(const details::log_msg &msg) override {
@@ -68,10 +69,10 @@ protected:
void flush_() override {}
private:
// There might be liblog versions used, that do not support __android_log_buf_write. So we only compile and link
// against
// __android_log_buf_write, if user explicitly provides a non-default log buffer. Otherwise, when using the default
// log buffer, always log via __android_log_write.
// There might be liblog versions used, that do not support __android_log_buf_write. So we only
// compile and link against
// __android_log_buf_write, if user explicitly provides a non-default log buffer. Otherwise,
// when using the default log buffer, always log via __android_log_write.
template <int ID = BufferID>
typename std::enable_if<ID == static_cast<int>(log_id::LOG_ID_MAIN), int>::type
android_log(int prio, const char *tag, const char *text) {
@@ -120,12 +121,14 @@ using android_sink_buf_st = android_sink<details::null_mutex, BufferId>;
// Create and register android syslog logger
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> android_logger_mt(const std::string &logger_name, const std::string &tag = "spdlog") {
inline std::shared_ptr<logger> android_logger_mt(const std::string &logger_name,
const std::string &tag = "spdlog") {
return Factory::template create<sinks::android_sink_mt>(logger_name, tag);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> android_logger_st(const std::string &logger_name, const std::string &tag = "spdlog") {
inline std::shared_ptr<logger> android_logger_st(const std::string &logger_name,
const std::string &tag = "spdlog") {
return Factory::template create<sinks::android_sink_st>(logger_name, tag);
}

View File

@@ -45,7 +45,8 @@ inline std::shared_ptr<logger> basic_logger_mt(const std::string &logger_name,
const filename_t &filename,
bool truncate = false,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate, event_handlers);
return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate,
event_handlers);
}
template <typename Factory = spdlog::synchronous_factory>
@@ -53,7 +54,8 @@ inline std::shared_ptr<logger> basic_logger_st(const std::string &logger_name,
const filename_t &filename,
bool truncate = false,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate, event_handlers);
return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate,
event_handlers);
}
} // namespace spdlog

View File

@@ -42,12 +42,14 @@ using callback_sink_st = callback_sink<details::null_mutex>;
// factory functions
//
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> callback_logger_mt(const std::string &logger_name, const custom_log_callback &callback) {
inline std::shared_ptr<logger> callback_logger_mt(const std::string &logger_name,
const custom_log_callback &callback) {
return Factory::template create<sinks::callback_sink_mt>(logger_name, callback);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> callback_logger_st(const std::string &logger_name, const custom_log_callback &callback) {
inline std::shared_ptr<logger> callback_logger_st(const std::string &logger_name,
const custom_log_callback &callback) {
return Factory::template create<sinks::callback_sink_st>(logger_name, callback);
}

View File

@@ -31,16 +31,18 @@ struct daily_filename_calculator {
static filename_t calc_filename(const filename_t &filename, const tm &now_tm) {
filename_t basename, ext;
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,
now_tm.tm_mon + 1, now_tm.tm_mday, ext);
return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename,
now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext);
}
};
/*
* Generator of daily log file names with strftime format.
* Usages:
* auto sink = std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("myapp-%Y-%m-%d:%H:%M:%S.log", hour,
* minute);" auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", hour, minute)"
* auto sink =
* std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("myapp-%Y-%m-%d:%H:%M:%S.log", hour,
* minute);" auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log",
* hour, minute)"
*
*/
struct daily_filename_format_calculator {
@@ -70,14 +72,15 @@ public:
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {})
: base_filename_(std::move(base_filename)),
rotation_h_(rotation_hour),
rotation_m_(rotation_minute),
file_helper_{event_handlers},
truncate_(truncate),
max_files_(max_files),
filenames_q_() {
if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) {
: base_filename_(std::move(base_filename))
, rotation_h_(rotation_hour)
, rotation_m_(rotation_minute)
, file_helper_{event_handlers}
, truncate_(truncate)
, max_files_(max_files)
, filenames_q_() {
if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 ||
rotation_minute > 59) {
throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
}
@@ -168,7 +171,8 @@ private:
bool ok = remove_if_exists(old_filename) == 0;
if (!ok) {
filenames_q_.push_back(std::move(current_file));
throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno);
throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename),
errno);
}
}
filenames_q_.push_back(std::move(current_file));
@@ -187,7 +191,8 @@ private:
using daily_file_sink_mt = daily_file_sink<std::mutex>;
using daily_file_sink_st = daily_file_sink<details::null_mutex>;
using daily_file_format_sink_mt = daily_file_sink<std::mutex, daily_filename_format_calculator>;
using daily_file_format_sink_st = daily_file_sink<details::null_mutex, daily_filename_format_calculator>;
using daily_file_format_sink_st =
daily_file_sink<details::null_mutex, daily_filename_format_calculator>;
} // namespace sinks
@@ -202,20 +207,21 @@ inline std::shared_ptr<logger> daily_logger_mt(const std::string &logger_name,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files,
event_handlers);
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute,
truncate, max_files, event_handlers);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_format_mt(const std::string &logger_name,
const filename_t &filename,
int hour = 0,
int minute = 0,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate,
max_files, event_handlers);
inline std::shared_ptr<logger>
daily_logger_format_mt(const std::string &logger_name,
const filename_t &filename,
int hour = 0,
int minute = 0,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_mt>(
logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
template <typename Factory = spdlog::synchronous_factory>
@@ -226,19 +232,20 @@ inline std::shared_ptr<logger> daily_logger_st(const std::string &logger_name,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files,
event_handlers);
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute,
truncate, max_files, event_handlers);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_logger_format_st(const std::string &logger_name,
const filename_t &filename,
int hour = 0,
int minute = 0,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate,
max_files, event_handlers);
inline std::shared_ptr<logger>
daily_logger_format_st(const std::string &logger_name,
const filename_t &filename,
int hour = 0,
int minute = 0,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::daily_file_format_sink_st>(
logger_name, filename, hour, minute, truncate, max_files, event_handlers);
}
} // namespace spdlog

View File

@@ -20,8 +20,8 @@
// #include <spdlog/sinks/dup_filter_sink.h>
//
// int main() {
// auto dup_filter = std::make_shared<dup_filter_sink_st>(std::chrono::seconds(5), level::info);
// dup_filter->add_sink(std::make_shared<stdout_color_sink_mt>());
// auto dup_filter = std::make_shared<dup_filter_sink_st>(std::chrono::seconds(5),
// level::info); dup_filter->add_sink(std::make_shared<stdout_color_sink_mt>());
// spdlog::logger l("logger", dup_filter);
// l.info("Hello");
// l.info("Hello");
@@ -42,8 +42,8 @@ public:
template <class Rep, class Period>
explicit dup_filter_sink(std::chrono::duration<Rep, Period> max_skip_duration,
level notification_level = level::info)
: max_skip_duration_{max_skip_duration},
log_level_{notification_level} {}
: max_skip_duration_{max_skip_duration}
, log_level_{notification_level} {}
protected:
std::chrono::microseconds max_skip_duration_;
@@ -62,8 +62,8 @@ protected:
// log the "skipped.." message
if (skip_counter_ > 0) {
char buf[64];
auto msg_size =
::snprintf(buf, sizeof(buf), "Skipped %u duplicate messages..", static_cast<unsigned>(skip_counter_));
auto msg_size = ::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)) {
details::log_msg skipped_msg{msg.source, msg.logger_name, log_level_,
string_view_t{buf, static_cast<size_t>(msg_size)}};

View File

@@ -29,8 +29,9 @@ struct hourly_filename_calculator {
static filename_t calc_filename(const filename_t &filename, const tm &now_tm) {
filename_t basename, ext;
std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename, now_tm.tm_year + 1900,
now_tm.tm_mon + 1, now_tm.tm_mday, now_tm.tm_hour, ext);
return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename,
now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday,
now_tm.tm_hour, ext);
}
};
@@ -47,11 +48,11 @@ public:
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {})
: base_filename_(std::move(base_filename)),
file_helper_{event_handlers},
truncate_(truncate),
max_files_(max_files),
filenames_q_() {
: base_filename_(std::move(base_filename))
, file_helper_{event_handlers}
, truncate_(truncate)
, max_files_(max_files)
, filenames_q_() {
auto now = log_clock::now();
auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
file_helper_.open(filename, truncate_);
@@ -144,7 +145,8 @@ private:
bool ok = remove_if_exists(old_filename) == 0;
if (!ok) {
filenames_q_.push_back(std::move(current_file));
SPDLOG_THROW(spdlog_ex("Failed removing hourly file " + filename_to_str(old_filename), errno));
SPDLOG_THROW(spdlog_ex(
"Failed removing hourly file " + filename_to_str(old_filename), errno));
}
}
filenames_q_.push_back(std::move(current_file));
@@ -173,8 +175,8 @@ inline std::shared_ptr<logger> hourly_logger_mt(const std::string &logger_name,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files,
event_handlers);
return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate,
max_files, event_handlers);
}
template <typename Factory = spdlog::synchronous_factory>
@@ -183,7 +185,7 @@ inline std::shared_ptr<logger> hourly_logger_st(const std::string &logger_name,
bool truncate = false,
uint16_t max_files = 0,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files,
event_handlers);
return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate,
max_files, event_handlers);
}
} // namespace spdlog

View File

@@ -30,9 +30,9 @@ struct kafka_sink_config {
int32_t flush_timeout_ms = 1000;
kafka_sink_config(std::string addr, std::string topic, int flush_timeout_ms = 1000)
: server_addr{std::move(addr)},
produce_topic{std::move(topic)},
flush_timeout_ms(flush_timeout_ms) {}
: server_addr{std::move(addr)}
, produce_topic{std::move(topic)}
, flush_timeout_ms(flush_timeout_ms) {}
};
template <typename Mutex>
@@ -43,9 +43,11 @@ public:
try {
std::string errstr;
conf_.reset(RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL));
RdKafka::Conf::ConfResult confRes = conf_->set("bootstrap.servers", config_.server_addr, errstr);
RdKafka::Conf::ConfResult confRes =
conf_->set("bootstrap.servers", config_.server_addr, errstr);
if (confRes != RdKafka::Conf::CONF_OK) {
throw_spdlog_ex(fmt_lib::format("conf set bootstrap.servers failed err:{}", errstr));
throw_spdlog_ex(
fmt_lib::format("conf set bootstrap.servers failed err:{}", errstr));
}
tconf_.reset(RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC));
@@ -57,7 +59,8 @@ public:
if (producer_ == nullptr) {
throw_spdlog_ex(fmt_lib::format("create producer failed err:{}", errstr));
}
topic_.reset(RdKafka::Topic::create(producer_.get(), config_.produce_topic, tconf_.get(), errstr));
topic_.reset(RdKafka::Topic::create(producer_.get(), config_.produce_topic,
tconf_.get(), errstr));
if (topic_ == nullptr) {
throw_spdlog_ex(fmt_lib::format("create topic failed err:{}", errstr));
}
@@ -70,8 +73,8 @@ public:
protected:
void sink_it_(const details::log_msg &msg) override {
producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY, (void *)msg.payload.data(),
msg.payload.size(), NULL, NULL);
producer_->produce(topic_.get(), 0, RdKafka::Producer::RK_MSG_COPY,
(void *)msg.payload.data(), msg.payload.size(), NULL, NULL);
}
void flush_() override { producer_->flush(config_.flush_timeout_ms); }
@@ -102,14 +105,14 @@ inline std::shared_ptr<logger> kafka_logger_st(const std::string &logger_name,
}
template <typename Factory = spdlog::async_factory>
inline std::shared_ptr<spdlog::logger> kafka_logger_async_mt(std::string logger_name,
spdlog::sinks::kafka_sink_config config) {
inline std::shared_ptr<spdlog::logger>
kafka_logger_async_mt(std::string logger_name, spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_mt>(logger_name, config);
}
template <typename Factory = spdlog::async_factory>
inline std::shared_ptr<spdlog::logger> kafka_logger_async_st(std::string logger_name,
spdlog::sinks::kafka_sink_config config) {
inline std::shared_ptr<spdlog::logger>
kafka_logger_async_st(std::string logger_name, spdlog::sinks::kafka_sink_config config) {
return Factory::template create<sinks::kafka_sink_st>(logger_name, config);
}

View File

@@ -40,9 +40,9 @@ public:
const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017")
: instance_(std::move(instance)),
db_name_(db_name),
coll_name_(collection_name) {
: instance_(std::move(instance))
, db_name_(db_name)
, coll_name_(collection_name) {
try {
client_ = spdlog::std::make_unique<mongocxx::client>(mongocxx::uri{uri});
} catch (const std::exception &e) {
@@ -59,10 +59,12 @@ protected:
if (client_ != nullptr) {
auto doc = document{} << "timestamp" << bsoncxx::types::b_date(msg.time) << "level"
<< level::to_string_view(msg.log_level).data() << "level_num" << msg.log_level
<< "message" << std::string(msg.payload.begin(), msg.payload.end()) << "logger_name"
<< std::string(msg.logger_name.begin(), msg.logger_name.end()) << "thread_id"
<< static_cast<int>(msg.thread_id) << finalize;
<< level::to_string_view(msg.log_level).data() << "level_num"
<< msg.log_level << "message"
<< std::string(msg.payload.begin(), msg.payload.end())
<< "logger_name"
<< std::string(msg.logger_name.begin(), msg.logger_name.end())
<< "thread_id" << static_cast<int>(msg.thread_id) << finalize;
client_->database(db_name_).collection(coll_name_).insert_one(doc.view());
}
}
@@ -84,19 +86,23 @@ using mongo_sink_st = mongo_sink<spdlog::details::null_mutex>;
} // namespace sinks
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> mongo_logger_mt(const std::string &logger_name,
const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_mt>(logger_name, db_name, collection_name, uri);
inline std::shared_ptr<logger>
mongo_logger_mt(const std::string &logger_name,
const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_mt>(logger_name, db_name, collection_name,
uri);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> mongo_logger_st(const std::string &logger_name,
const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_st>(logger_name, db_name, collection_name, uri);
inline std::shared_ptr<logger>
mongo_logger_st(const std::string &logger_name,
const std::string &db_name,
const std::string &collection_name,
const std::string &uri = "mongodb://localhost:27017") {
return Factory::template create<sinks::mongo_sink_st>(logger_name, db_name, collection_name,
uri);
}
} // namespace spdlog

View File

@@ -15,8 +15,8 @@ template <typename Mutex>
class ostream_sink final : public base_sink<Mutex> {
public:
explicit ostream_sink(std::ostream &os, bool force_flush = false)
: ostream_(os),
force_flush_(force_flush) {}
: ostream_(os)
, force_flush_(force_flush) {}
ostream_sink(const ostream_sink &) = delete;
ostream_sink &operator=(const ostream_sink &) = delete;

View File

@@ -8,8 +8,8 @@
// etc) Building and using requires Qt library.
//
// Warning: the qt_sink won't be notified if the target widget is destroyed.
// If the widget's lifetime can be shorter than the logger's one, you should provide some permanent QObject,
// and then use a standard signal/slot.
// If the widget's lifetime can be shorter than the logger's one, you should provide some permanent
// QObject, and then use a standard signal/slot.
//
#include "spdlog/common.h"
@@ -30,8 +30,8 @@ template <typename Mutex>
class qt_sink : public base_sink<Mutex> {
public:
qt_sink(QObject *qt_object, std::string meta_method)
: qt_object_(qt_object),
meta_method_(std::move(meta_method)) {
: qt_object_(qt_object)
, meta_method_(std::move(meta_method)) {
if (!qt_object_) {
throw_spdlog_ex("qt_sink: qt_object is null");
}
@@ -59,15 +59,19 @@ private:
// QT color sink to QTextEdit.
// Color location is determined by the sink log pattern like in the rest of spdlog sinks.
// Colors can be modified if needed using sink->set_color(level, qtTextCharFormat).
// max_lines is the maximum number of lines that the sink will hold before removing the oldest lines.
// By default, only ascii (latin1) is supported by this sink. Set is_utf8 to true if utf8 support is needed.
// max_lines is the maximum number of lines that the sink will hold before removing the oldest
// lines. By default, only ascii (latin1) is supported by this sink. Set is_utf8 to true if utf8
// support is needed.
template <typename Mutex>
class qt_color_sink : public base_sink<Mutex> {
public:
qt_color_sink(QTextEdit *qt_text_edit, int max_lines, bool dark_colors = false, bool is_utf8 = false)
: qt_text_edit_(qt_text_edit),
max_lines_(max_lines),
is_utf8_(is_utf8) {
qt_color_sink(QTextEdit *qt_text_edit,
int max_lines,
bool dark_colors = false,
bool is_utf8 = false)
: qt_text_edit_(qt_text_edit)
, max_lines_(max_lines)
, is_utf8_(is_utf8) {
if (!qt_text_edit_) {
throw_spdlog_ex("qt_color_text_sink: text_edit is null");
}
@@ -127,13 +131,13 @@ protected:
QTextCharFormat level_color,
int color_range_start,
int color_range_end)
: max_lines(max_lines),
q_text_edit(q_text_edit),
payload(std::move(payload)),
default_color(default_color),
level_color(level_color),
color_range_start(color_range_start),
color_range_end(color_range_end) {}
: max_lines(max_lines)
, q_text_edit(q_text_edit)
, payload(std::move(payload))
, default_color(default_color)
, level_color(level_color)
, color_range_start(color_range_start)
, color_range_end(color_range_end) {}
int max_lines;
QTextEdit *q_text_edit;
QString payload;
@@ -178,8 +182,8 @@ protected:
void flush_() override {}
// Add colored text to the text edit widget. This method is invoked in the GUI thread.
// It is a static method to ensure that it is handled correctly even if the sink is destroyed prematurely
// before it is invoked.
// It is a static method to ensure that it is handled correctly even if the sink is destroyed
// prematurely before it is invoked.
static void invoke_method_(invoke_params params) {
auto *document = params.q_text_edit->document();
@@ -206,8 +210,8 @@ protected:
// insert the colorized text
cursor.setCharFormat(params.level_color);
cursor.insertText(
params.payload.mid(params.color_range_start, params.color_range_end - params.color_range_start));
cursor.insertText(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
cursor.setCharFormat(params.default_color);
@@ -236,14 +240,16 @@ using qt_color_sink_st = qt_color_sink<details::null_mutex>;
// log to QTextEdit
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qt_logger_mt(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append") {
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name,
QTextEdit *qt_object,
const std::string &meta_method = "append") {
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qt_logger_st(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append") {
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name,
QTextEdit *qt_object,
const std::string &meta_method = "append") {
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
@@ -276,15 +282,21 @@ qt_logger_st(const std::string &logger_name, QObject *qt_object, const std::stri
// log to QTextEdit with colorize output
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qt_color_logger_mt(const std::string &logger_name, QTextEdit *qt_text_edit, int max_lines, bool is_utf8 = false) {
return Factory::template create<sinks::qt_color_sink_mt>(logger_name, qt_text_edit, max_lines, false, is_utf8);
inline std::shared_ptr<logger> qt_color_logger_mt(const std::string &logger_name,
QTextEdit *qt_text_edit,
int max_lines,
bool is_utf8 = false) {
return Factory::template create<sinks::qt_color_sink_mt>(logger_name, qt_text_edit, max_lines,
false, is_utf8);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
qt_color_logger_st(const std::string &logger_name, QTextEdit *qt_text_edit, int max_lines, bool is_utf8 = false) {
return Factory::template create<sinks::qt_color_sink_st>(logger_name, qt_text_edit, max_lines, false, is_utf8);
inline std::shared_ptr<logger> qt_color_logger_st(const std::string &logger_name,
QTextEdit *qt_text_edit,
int max_lines,
bool is_utf8 = false) {
return Factory::template create<sinks::qt_color_sink_st>(logger_name, qt_text_edit, max_lines,
false, is_utf8);
}
} // namespace spdlog

View File

@@ -16,10 +16,10 @@
namespace spdlog {
namespace sinks {
/*
* Ring buffer sink. Holds fixed amount of log messages in memory. When the buffer is full, new messages override the
* old ones. Useful for storing debug data in memory in case of error. Example: auto rb_sink =
* std::make_shared<spdlog::sinks::ringbuffer_sink_mt>(128); spdlog::logger logger("rb_logger", rb_sink);
* rb->drain([](const std::string_view msg) { process(msg);});
* Ring buffer sink. Holds fixed amount of log messages in memory. When the buffer is full, new
* messages override the old ones. Useful for storing debug data in memory in case of error.
* Example: auto rb_sink = std::make_shared<spdlog::sinks::ringbuffer_sink_mt>(128); spdlog::logger
* logger("rb_logger", rb_sink); rb->drain([](const std::string_view msg) { process(msg);});
*/
template <typename Mutex>
class ringbuffer_sink final : public base_sink<Mutex> {
@@ -47,7 +47,9 @@ public:
}
protected:
void sink_it_(const details::log_msg &msg) override { q_.push_back(details::log_msg_buffer{msg}); }
void sink_it_(const details::log_msg &msg) override {
q_.push_back(details::log_msg_buffer{msg});
}
void flush_() override {}
private:

View File

@@ -14,7 +14,6 @@
namespace spdlog {
namespace sinks {
//
// Rotating file sink based on size
//
@@ -26,6 +25,7 @@ public:
std::size_t max_files,
bool rotate_on_open = false,
const file_event_handlers &event_handlers = {});
static filename_t calc_filename(const filename_t &filename, std::size_t index);
filename_t filename();
@@ -68,8 +68,8 @@ inline std::shared_ptr<logger> rotating_logger_mt(const std::string &logger_name
size_t max_files,
bool rotate_on_open = false,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files,
rotate_on_open, event_handlers);
return Factory::template create<sinks::rotating_file_sink_mt>(
logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
}
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,
bool rotate_on_open = false,
const file_event_handlers &event_handlers = {}) {
return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files,
rotate_on_open, event_handlers);
return Factory::template create<sinks::rotating_file_sink_st>(
logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
}
} // namespace spdlog

View File

@@ -30,15 +30,19 @@ using stderr_color_sink_st = ansicolor_stderr_sink_st;
// template instantations
template <typename Factory = spdlog::synchronous_factory>
std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name,
color_mode mode = color_mode::automatic);
template <typename Factory = spdlog::synchronous_factory>
std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
std::shared_ptr<logger> stdout_color_st(const std::string &logger_name,
color_mode mode = color_mode::automatic);
template <typename Factory = spdlog::synchronous_factory>
std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name,
color_mode mode = color_mode::automatic);
template <typename Factory = spdlog::synchronous_factory>
std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
std::shared_ptr<logger> stderr_color_st(const std::string &logger_name,
color_mode mode = color_mode::automatic);
} // namespace spdlog

View File

@@ -21,15 +21,15 @@ class syslog_sink : public base_sink<Mutex> {
public:
syslog_sink(std::string ident, int syslog_option, int syslog_facility, bool enable_formatting)
: enable_formatting_{enable_formatting},
syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
: enable_formatting_{enable_formatting}
, syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
/* spdlog::level::debug */ LOG_DEBUG,
/* spdlog::level::info */ LOG_INFO,
/* spdlog::level::warn */ LOG_WARNING,
/* spdlog::level::err */ LOG_ERR,
/* spdlog::level::critical */ LOG_CRIT,
/* spdlog::level::off */ LOG_INFO}},
ident_{std::move(ident)} {
/* spdlog::level::off */ LOG_INFO}}
, ident_{std::move(ident)} {
// set ident to be program name if empty
::openlog(ident_.empty() ? nullptr : ident_.c_str(), syslog_option, syslog_facility);
}
@@ -88,8 +88,8 @@ inline std::shared_ptr<logger> syslog_logger_mt(const std::string &logger_name,
int syslog_option = 0,
int syslog_facility = LOG_USER,
bool enable_formatting = false) {
return Factory::template create<sinks::syslog_sink_mt>(logger_name, syslog_ident, syslog_option, syslog_facility,
enable_formatting);
return Factory::template create<sinks::syslog_sink_mt>(logger_name, syslog_ident, syslog_option,
syslog_facility, enable_formatting);
}
template <typename Factory = spdlog::synchronous_factory>
@@ -98,7 +98,7 @@ inline std::shared_ptr<logger> syslog_logger_st(const std::string &logger_name,
int syslog_option = 0,
int syslog_facility = LOG_USER,
bool enable_formatting = false) {
return Factory::template create<sinks::syslog_sink_st>(logger_name, syslog_ident, syslog_option, syslog_facility,
enable_formatting);
return Factory::template create<sinks::syslog_sink_st>(logger_name, syslog_ident, syslog_option,
syslog_facility, enable_formatting);
}
} // namespace spdlog

View File

@@ -24,9 +24,9 @@ template <typename Mutex>
class systemd_sink : public base_sink<Mutex> {
public:
systemd_sink(std::string ident = "", bool enable_formatting = false)
: ident_{std::move(ident)},
enable_formatting_{enable_formatting},
syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
: ident_{std::move(ident)}
, enable_formatting_{enable_formatting}
, syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
/* spdlog::level::debug */ LOG_DEBUG,
/* spdlog::level::info */ LOG_INFO,
/* spdlog::level::warn */ LOG_WARNING,
@@ -67,22 +67,25 @@ protected:
// Do not send source location if not available
if (msg.source.empty()) {
// Note: function call inside '()' to avoid macro expansion
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(), "PRIORITY=%d",
syslog_level(msg.log_level),
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(),
"PRIORITY=%d", syslog_level(msg.log_level),
#ifndef SPDLOG_NO_THREAD_ID
"TID=%zu", details::os::thread_id(),
#endif
"SYSLOG_IDENTIFIER=%.*s", static_cast<int>(syslog_identifier.size()),
"SYSLOG_IDENTIFIER=%.*s",
static_cast<int>(syslog_identifier.size()),
syslog_identifier.data(), nullptr);
} else {
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(), "PRIORITY=%d",
syslog_level(msg.log_level),
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(),
"PRIORITY=%d", syslog_level(msg.log_level),
#ifndef SPDLOG_NO_THREAD_ID
"TID=%zu", details::os::thread_id(),
#endif
"SYSLOG_IDENTIFIER=%.*s", static_cast<int>(syslog_identifier.size()),
syslog_identifier.data(), "CODE_FILE=%s", msg.source.filename, "CODE_LINE=%d",
msg.source.line, "CODE_FUNC=%s", msg.source.funcname, nullptr);
"SYSLOG_IDENTIFIER=%.*s",
static_cast<int>(syslog_identifier.size()),
syslog_identifier.data(), "CODE_FILE=%s", msg.source.filename,
"CODE_LINE=%d", msg.source.line, "CODE_FUNC=%s",
msg.source.funcname, nullptr);
}
if (err) {
@@ -101,14 +104,16 @@ using systemd_sink_st = systemd_sink<details::null_mutex>;
// Create and register a syslog logger
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
systemd_logger_mt(const std::string &logger_name, const std::string &ident = "", bool enable_formatting = false) {
inline std::shared_ptr<logger> systemd_logger_mt(const std::string &logger_name,
const std::string &ident = "",
bool enable_formatting = false) {
return Factory::template create<sinks::systemd_sink_mt>(logger_name, ident, enable_formatting);
}
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger>
systemd_logger_st(const std::string &logger_name, const std::string &ident = "", bool enable_formatting = false) {
inline std::shared_ptr<logger> systemd_logger_st(const std::string &logger_name,
const std::string &ident = "",
bool enable_formatting = false) {
return Factory::template create<sinks::systemd_sink_st>(logger_name, ident, enable_formatting);
}
} // namespace spdlog

View File

@@ -22,7 +22,8 @@
// Simple tcp client sink
// Connects to remote address and send the formatted log.
// Will attempt to reconnect if connection drops.
// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the sink_it_ method.
// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the
// sink_it_ method.
namespace spdlog {
namespace sinks {
@@ -33,8 +34,8 @@ struct tcp_sink_config {
bool lazy_connect = false; // if true connect on first log call instead of on construction
tcp_sink_config(std::string host, int port)
: server_host{std::move(host)},
server_port{port} {}
: server_host{std::move(host)}
, server_port{port} {}
};
template <typename Mutex>

View File

@@ -28,8 +28,8 @@ struct udp_sink_config {
uint16_t server_port;
udp_sink_config(std::string host, uint16_t port)
: server_host{std::move(host)},
server_port{port} {}
: server_host{std::move(host)}
, server_port{port} {}
};
template <typename Mutex>
@@ -61,7 +61,8 @@ using udp_sink_st = udp_sink<spdlog::details::null_mutex>;
// factory functions
//
template <typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> udp_logger_mt(const std::string &logger_name, sinks::udp_sink_config skin_config) {
inline std::shared_ptr<logger> udp_logger_mt(const std::string &logger_name,
sinks::udp_sink_config skin_config) {
return Factory::template create<sinks::udp_sink_mt>(logger_name, skin_config);
}

View File

@@ -1,17 +1,20 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
// Writing to Windows Event Log requires the registry entries below to be present, with the following modifications:
// Writing to Windows Event Log requires the registry entries below to be present, with the
// following modifications:
// 1. <log_name> should be replaced with your log name (e.g. your application name)
// 2. <source_name> should be replaced with the specific source name and the key should be duplicated for
// 2. <source_name> should be replaced with the specific source name and the key should be
// duplicated for
// each source used in the application
//
// Since typically modifications of this kind require elevation, it's better to do it as a part of setup procedure.
// The snippet below uses mscoree.dll as the message file as it exists on most of the Windows systems anyway and
// happens to contain the needed resource.
// Since typically modifications of this kind require elevation, it's better to do it as a part of
// setup procedure. The snippet below uses mscoree.dll as the message file as it exists on most of
// the Windows systems anyway and happens to contain the needed resource.
//
// You can also specify a custom message file if needed.
// Please refer to Event Log functions descriptions in MSDN for more details on custom message files.
// Please refer to Event Log functions descriptions in MSDN for more details on custom message
// files.
/*---------------------------------------------------------------------------------------
@@ -70,9 +73,11 @@ struct win32_error : public spdlog_ex {
std::string system_message;
local_alloc_t format_message_result{};
auto format_message_succeeded = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&format_message_result.hlocal_, 0, nullptr);
auto format_message_succeeded =
::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&format_message_result.hlocal_, 0, nullptr);
if (format_message_succeeded && format_message_result.hlocal_) {
system_message = fmt_lib::format(" ({})", (LPSTR)format_message_result.hlocal_);
@@ -125,18 +130,21 @@ public:
~process_token_t() { ::CloseHandle(token_handle_); }
} current_process_token(::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here!
} current_process_token(
::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here!
// Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return the token size
// Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return
// the token size
DWORD tusize = 0;
if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0, &tusize)) {
if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0,
&tusize)) {
SPDLOG_THROW(win32_error("GetTokenInformation should fail"));
}
// get user token
std::vector<unsigned char> buffer(static_cast<size_t>(tusize));
if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, (LPVOID)buffer.data(), tusize,
&tusize)) {
if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser,
(LPVOID)buffer.data(), tusize, &tusize)) {
SPDLOG_THROW(win32_error("GetTokenInformation"));
}
@@ -205,9 +213,9 @@ protected:
formatted.push_back('\0');
LPCSTR lp_str = formatted.data();
succeeded = static_cast<bool>(::ReportEventA(event_log_handle(), eventlog::get_event_type(msg),
eventlog::get_event_category(msg), event_id_,
current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr));
succeeded = static_cast<bool>(::ReportEventA(
event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg),
event_id_, current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr));
if (!succeeded) {
SPDLOG_THROW(win32_error("ReportEvent"));
@@ -217,14 +225,15 @@ protected:
void flush_() override {}
public:
win_eventlog_sink(std::string const &source, DWORD event_id = 1000 /* according to mscoree.dll */)
: source_(source),
event_id_(event_id) {
win_eventlog_sink(std::string const &source,
DWORD event_id = 1000 /* according to mscoree.dll */)
: source_(source)
, event_id_(event_id) {
try {
current_user_sid_ = internal::sid_t::get_current_user_sid();
} catch (...) {
// get_current_user_sid() is unlikely to fail and if it does, we can still proceed without
// current_user_sid but in the event log the record will have no user name
// get_current_user_sid() is unlikely to fail and if it does, we can still proceed
// without current_user_sid but in the event log the record will have no user name
}
}

View File

@@ -32,7 +32,8 @@ using default_factory = synchronous_factory;
// spdlog::create<daily_file_sink_st>("logger_name", "dailylog_filename", 11, 59);
template <typename Sink, typename... SinkArgs>
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)...);
}
// Initialize and register a logger,
@@ -55,7 +56,8 @@ SPDLOG_API void set_formatter(std::unique_ptr<spdlog::formatter> formatter);
// Set global format string.
// example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v");
SPDLOG_API void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
SPDLOG_API void set_pattern(std::string pattern,
pattern_time_type time_type = pattern_time_type::local);
// Get global logging level
SPDLOG_API level get_level();
@@ -181,17 +183,29 @@ inline void critical(loc_with_fmt fmt, Args &&...args) {
}
// log functions with no format string, just string
inline void trace(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::trace, msg); }
inline void trace(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::trace, msg);
}
inline void debug(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::debug, msg); }
inline void debug(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::debug, msg);
}
inline void info(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::info, msg); }
inline void info(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::info, msg);
}
inline void warn(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, spdlog::level::warn, msg); }
inline void warn(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, spdlog::level::warn, msg);
}
inline void error(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::err, msg); }
inline void error(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::err, msg);
}
inline void critical(string_view_t msg, source_loc loc = source_loc::current()) { log(loc, level::critical, msg); }
inline void critical(string_view_t msg, source_loc loc = source_loc::current()) {
log(loc, level::critical, msg);
}
#else
template <typename... Args>
inline void trace(format_string_t<Args...> fmt, Args &&...args) {
@@ -256,11 +270,13 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#define SPDLOG_LOGGER_CALL(logger, level, ...) \
(logger)->log(spdlog::source_loc{__FILE__, __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__)
#else
#define SPDLOG_LOGGER_CALL(logger, level, ...) (logger)->log(spdlog::source_loc{}, level, __VA_ARGS__)
#define SPDLOG_LOGGER_CALL(logger, level, ...) \
(logger)->log(spdlog::source_loc{}, level, __VA_ARGS__)
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE
#define SPDLOG_LOGGER_TRACE(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::trace, __VA_ARGS__)
#define SPDLOG_LOGGER_TRACE(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::trace, __VA_ARGS__)
#define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_TRACE(logger, ...) (void)0
@@ -268,7 +284,8 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG
#define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::debug, __VA_ARGS__)
#define SPDLOG_LOGGER_DEBUG(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::debug, __VA_ARGS__)
#define SPDLOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0
@@ -276,7 +293,8 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO
#define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::info, __VA_ARGS__)
#define SPDLOG_LOGGER_INFO(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::info, __VA_ARGS__)
#define SPDLOG_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_INFO(logger, ...) (void)0
@@ -284,7 +302,8 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN
#define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::warn, __VA_ARGS__)
#define SPDLOG_LOGGER_WARN(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::warn, __VA_ARGS__)
#define SPDLOG_WARN(...) SPDLOG_LOGGER_WARN(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_WARN(logger, ...) (void)0
@@ -292,7 +311,8 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR
#define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::err, __VA_ARGS__)
#define SPDLOG_LOGGER_ERROR(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::err, __VA_ARGS__)
#define SPDLOG_ERROR(...) SPDLOG_LOGGER_ERROR(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_ERROR(logger, ...) (void)0
@@ -300,7 +320,8 @@ inline void critical(string_view_t msg) { log(level::critical, msg); }
#endif
#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL
#define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::critical, __VA_ARGS__)
#define SPDLOG_LOGGER_CRITICAL(logger, ...) \
SPDLOG_LOGGER_CALL(logger, spdlog::level::critical, __VA_ARGS__)
#define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_CRITICAL(spdlog::default_logger_raw(), __VA_ARGS__)
#else
#define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0

View File

@@ -35,7 +35,9 @@ public:
stopwatch()
: start_tp_{clock::now()} {}
std::chrono::duration<double> elapsed() const { return std::chrono::duration<double>(clock::now() - start_tp_); }
std::chrono::duration<double> elapsed() const {
return std::chrono::duration<double>(clock::now() - start_tp_);
}
void reset() { start_tp_ = clock::now(); }
};

View File

@@ -85,7 +85,8 @@
///////////////////////////////////////////////////////////////////////////////
// Uncomment to customize level names (e.g. "MY 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" }
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////