clang format

This commit is contained in:
gabime
2023-09-25 16:08:29 +03:00
parent 230e15f499
commit 9d52261185
93 changed files with 1527 additions and 1430 deletions

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

@@ -15,9 +15,9 @@ namespace sinks {
template <typename ConsoleMutex>
SPDLOG_INLINE ansicolor_sink<ConsoleMutex>::ansicolor_sink(FILE *target_file, color_mode mode)
: target_file_(target_file),
mutex_(ConsoleMutex::mutex()),
formatter_(details::make_unique<spdlog::pattern_formatter>())
: target_file_(target_file)
, mutex_(ConsoleMutex::mutex())
, formatter_(details::make_unique<spdlog::pattern_formatter>())
{
set_color_mode(mode);
@@ -31,7 +31,8 @@ SPDLOG_INLINE ansicolor_sink<ConsoleMutex>::ansicolor_sink(FILE *target_file, co
}
template <typename ConsoleMutex>
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color(level::level_enum color_level, string_view_t color) {
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color(level::level_enum color_level,
string_view_t color) {
std::lock_guard<mutex_t> lock(mutex_);
colors_.at(static_cast<size_t>(color_level)) = to_string_(color);
}
@@ -74,7 +75,8 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_pattern(const std::string &
}
template <typename ConsoleMutex>
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
SPDLOG_INLINE void
ansicolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
@@ -91,7 +93,8 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color_mode(color_mode mode)
should_do_colors_ = true;
return;
case color_mode::automatic:
should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal();
should_do_colors_ =
details::os::in_terminal(target_file_) && details::os::is_color_terminal();
return;
case color_mode::never:
should_do_colors_ = false;
@@ -107,7 +110,9 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_ccode_(const string_view_
}
template <typename ConsoleMutex>
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end) {
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted,
size_t start,
size_t end) {
fwrite(formatted.data() + start, sizeof(char), end - start, target_file_);
}

View File

@@ -18,7 +18,8 @@ SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::base_sink()
: formatter_{details::make_unique<spdlog::pattern_formatter>()} {}
template <typename Mutex>
SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::base_sink(std::unique_ptr<spdlog::formatter> formatter)
SPDLOG_INLINE
spdlog::sinks::base_sink<Mutex>::base_sink(std::unique_ptr<spdlog::formatter> formatter)
: formatter_{std::move(formatter)} {}
template <typename Mutex>
@@ -40,7 +41,8 @@ void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern(const std::strin
}
template <typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
void SPDLOG_INLINE
spdlog::sinks::base_sink<Mutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
std::lock_guard<Mutex> lock(mutex_);
set_formatter_(std::move(sink_formatter));
}
@@ -51,6 +53,7 @@ void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern_(const std::stri
}
template <typename Mutex>
void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) {
void SPDLOG_INLINE
spdlog::sinks::base_sink<Mutex>::set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) {
formatter_ = std::move(sink_formatter);
}

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,19 @@ 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_FMT_STRING(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_FMT_STRING(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 +73,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 +172,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 +192,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 +208,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 +233,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::level_enum 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::details::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.level).data() << "level_num" << msg.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.level).data() << "level_num"
<< msg.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

@@ -50,7 +50,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

@@ -24,15 +24,16 @@ namespace spdlog {
namespace sinks {
template <typename Mutex>
SPDLOG_INLINE rotating_file_sink<Mutex>::rotating_file_sink(filename_t base_filename,
std::size_t max_size,
std::size_t max_files,
bool rotate_on_open,
const file_event_handlers &event_handlers)
: base_filename_(std::move(base_filename)),
max_size_(max_size),
max_files_(max_files),
file_helper_{event_handlers} {
SPDLOG_INLINE
rotating_file_sink<Mutex>::rotating_file_sink(filename_t base_filename,
std::size_t max_size,
std::size_t max_files,
bool rotate_on_open,
const file_event_handlers &event_handlers)
: base_filename_(std::move(base_filename))
, max_size_(max_size)
, max_files_(max_files)
, file_helper_{event_handlers} {
if (max_size == 0) {
throw_spdlog_ex("rotating sink constructor: max_size arg cannot be zero");
}
@@ -51,7 +52,8 @@ SPDLOG_INLINE rotating_file_sink<Mutex>::rotating_file_sink(filename_t base_file
// calc filename according to index and file extension if exists.
// e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt".
template <typename Mutex>
SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename_t &filename, std::size_t index) {
SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename_t &filename,
std::size_t index) {
if (index == 0u) {
return filename;
}
@@ -116,10 +118,11 @@ SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_() {
// rates can cause the rename to fail with permission denied (because of antivirus?).
details::os::sleep_for_millis(100);
if (!rename_file_(src, target)) {
file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
file_helper_.reopen(
true); // truncate the log file anyway to prevent it to grow beyond its limit!
current_size_ = 0;
throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " +
filename_to_str(target),
throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) +
" to " + filename_to_str(target),
errno);
}
}

View File

@@ -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,8 +79,8 @@ 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

@@ -13,22 +13,26 @@
namespace spdlog {
template <typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode) {
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name,
color_mode mode) {
return Factory::template create<sinks::stdout_color_sink_mt>(logger_name, mode);
}
template <typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode) {
SPDLOG_INLINE std::shared_ptr<logger> stdout_color_st(const std::string &logger_name,
color_mode mode) {
return Factory::template create<sinks::stdout_color_sink_st>(logger_name, mode);
}
template <typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode) {
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name,
color_mode mode) {
return Factory::template create<sinks::stderr_color_sink_mt>(logger_name, mode);
}
template <typename Factory>
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode) {
SPDLOG_INLINE std::shared_ptr<logger> stderr_color_st(const std::string &logger_name,
color_mode mode) {
return Factory::template create<sinks::stderr_color_sink_st>(logger_name, mode);
}
} // namespace spdlog

View File

@@ -27,16 +27,20 @@ using stderr_color_sink_st = ansicolor_stderr_sink_st;
} // namespace sinks
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

@@ -30,9 +30,9 @@ namespace sinks {
template <typename ConsoleMutex>
SPDLOG_INLINE stdout_sink_base<ConsoleMutex>::stdout_sink_base(FILE *file)
: mutex_(ConsoleMutex::mutex()),
file_(file),
formatter_(details::make_unique<spdlog::pattern_formatter>()) {
: mutex_(ConsoleMutex::mutex())
, file_(file)
, formatter_(details::make_unique<spdlog::pattern_formatter>()) {
#ifdef _WIN32
// get windows handle from the FILE* object
@@ -60,7 +60,8 @@ SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::log(const details::log_msg &m
DWORD bytes_written = 0;
bool ok = ::WriteFile(handle_, formatted.data(), size, &bytes_written, nullptr) != 0;
if (!ok) {
throw_spdlog_ex("stdout_sink_base: WriteFile() failed. GetLastError(): " + std::to_string(::GetLastError()));
throw_spdlog_ex("stdout_sink_base: WriteFile() failed. GetLastError(): " +
std::to_string(::GetLastError()));
}
#else
std::lock_guard<mutex_t> lock(mutex_);
@@ -84,7 +85,8 @@ SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::set_pattern(const std::string
}
template <typename ConsoleMutex>
SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
SPDLOG_INLINE void
stdout_sink_base<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}

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.level),
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(),
"PRIORITY=%d", syslog_level(msg.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.level),
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), payload.data(),
"PRIORITY=%d", syslog_level(msg.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) {
@@ -90,7 +93,9 @@ protected:
}
}
int syslog_level(level::level_enum l) { return syslog_levels_.at(static_cast<levels_array::size_type>(l)); }
int syslog_level(level::level_enum l) {
return syslog_levels_.at(static_cast<levels_array::size_type>(l));
}
void flush_() override {}
};
@@ -101,14 +106,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.
/*---------------------------------------------------------------------------------------
@@ -69,9 +72,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_);
@@ -124,18 +129,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"));
}
@@ -208,14 +216,14 @@ protected:
details::os::utf8_to_wstrbuf(string_view_t(formatted.data(), formatted.size()), buf);
LPCWSTR lp_wstr = buf.data();
succeeded = static_cast<bool>(::ReportEventW(event_log_handle(), eventlog::get_event_type(msg),
eventlog::get_event_category(msg), event_id_,
current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr));
succeeded = static_cast<bool>(::ReportEventW(
event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg),
event_id_, current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr));
#else
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));
#endif
if (!succeeded) {
@@ -226,14 +234,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

@@ -17,18 +17,20 @@ namespace spdlog {
namespace sinks {
template <typename ConsoleMutex>
SPDLOG_INLINE wincolor_sink<ConsoleMutex>::wincolor_sink(void *out_handle, color_mode mode)
: out_handle_(out_handle),
mutex_(ConsoleMutex::mutex()),
formatter_(details::make_unique<spdlog::pattern_formatter>()) {
: out_handle_(out_handle)
, mutex_(ConsoleMutex::mutex())
, formatter_(details::make_unique<spdlog::pattern_formatter>()) {
set_color_mode_impl(mode);
// set level colors
colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white
colors_[level::debug] = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan
colors_[level::info] = FOREGROUND_GREEN; // green
colors_[level::warn] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow
colors_[level::err] = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red
colors_[level::critical] = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white
colors_[level::debug] = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan
colors_[level::info] = FOREGROUND_GREEN; // green
colors_[level::warn] =
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow
colors_[level::err] = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red
colors_[level::critical] = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN |
FOREGROUND_BLUE |
FOREGROUND_INTENSITY; // intense white on red background
colors_[level::off] = 0;
}
@@ -40,7 +42,8 @@ SPDLOG_INLINE wincolor_sink<ConsoleMutex>::~wincolor_sink() {
// change the color for the given level
template <typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color(level::level_enum level, std::uint16_t color) {
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color(level::level_enum level,
std::uint16_t color) {
std::lock_guard<mutex_t> lock(mutex_);
colors_[static_cast<size_t>(level)] = color;
}
@@ -60,7 +63,8 @@ void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::log(const details::log_msg &msg)
// before color range
print_range_(formatted, 0, msg.color_range_start);
// in color range
auto orig_attribs = static_cast<WORD>(set_foreground_color_(colors_[static_cast<size_t>(msg.level)]));
auto orig_attribs =
static_cast<WORD>(set_foreground_color_(colors_[static_cast<size_t>(msg.level)]));
print_range_(formatted, msg.color_range_start, msg.color_range_end);
// reset to orig colors
::SetConsoleTextAttribute(static_cast<HANDLE>(out_handle_), orig_attribs);
@@ -83,7 +87,8 @@ void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_pattern(const std::string &p
}
template <typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
void SPDLOG_INLINE
wincolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) {
std::lock_guard<mutex_t> lock(mutex_);
formatter_ = std::move(sink_formatter);
}
@@ -108,7 +113,8 @@ void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color_mode_impl(color_mode m
// set foreground color and return the orig console attributes (for resetting later)
template <typename ConsoleMutex>
std::uint16_t SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_foreground_color_(std::uint16_t attribs) {
std::uint16_t SPDLOG_INLINE
wincolor_sink<ConsoleMutex>::set_foreground_color_(std::uint16_t attribs) {
CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info;
if (!::GetConsoleScreenBufferInfo(static_cast<HANDLE>(out_handle_), &orig_buffer_info)) {
// just return white if failed getting console info
@@ -117,18 +123,21 @@ std::uint16_t SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_foreground_color_(s
// change only the foreground bits (lowest 4 bits)
auto new_attribs = static_cast<WORD>(attribs) | (orig_buffer_info.wAttributes & 0xfff0);
auto ignored = ::SetConsoleTextAttribute(static_cast<HANDLE>(out_handle_), static_cast<WORD>(new_attribs));
auto ignored =
::SetConsoleTextAttribute(static_cast<HANDLE>(out_handle_), static_cast<WORD>(new_attribs));
(void)(ignored);
return static_cast<std::uint16_t>(orig_buffer_info.wAttributes); // return orig attribs
}
// print a range of formatted message to console
template <typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end) {
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted,
size_t start,
size_t end) {
if (end > start) {
auto size = static_cast<DWORD>(end - start);
auto ignored =
::WriteConsoleA(static_cast<HANDLE>(out_handle_), formatted.data() + start, size, nullptr, nullptr);
auto ignored = ::WriteConsoleA(static_cast<HANDLE>(out_handle_), formatted.data() + start,
size, nullptr, nullptr);
(void)(ignored);
}
}
@@ -137,7 +146,8 @@ template <typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::write_to_file_(const memory_buf_t &formatted) {
auto size = static_cast<DWORD>(formatted.size());
DWORD bytes_written = 0;
auto ignored = ::WriteFile(static_cast<HANDLE>(out_handle_), formatted.data(), size, &bytes_written, nullptr);
auto ignored = ::WriteFile(static_cast<HANDLE>(out_handle_), formatted.data(), size,
&bytes_written, nullptr);
(void)(ignored);
}