Fix clang-tidy warnings about missing braces around if and for statements

This commit is contained in:
gabime 2018-03-17 13:42:09 +02:00
parent 7eb6ca6337
commit 200815892f
10 changed files with 118 additions and 0 deletions

View File

@ -47,7 +47,9 @@ int main(int, char *[])
// Create a file rotating logger with 5mb size max and 3 rotated files // Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i); rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am // Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
@ -106,8 +108,10 @@ void async_example()
spdlog::set_async_mode(q_size); spdlog::set_async_mode(q_size);
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt"); auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
for (int i = 0; i < 100; ++i) for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i); async_file->info("Async message #{}", i);
} }
}
// syslog example (linux/osx/freebsd) // syslog example (linux/osx/freebsd)
void syslog_example() void syslog_example()

View File

@ -247,13 +247,17 @@ inline void spdlog::details::async_log_helper::flush(bool wait_for_q)
{ {
push_msg(async_msg(async_msg_type::flush)); push_msg(async_msg(async_msg_type::flush));
if (wait_for_q) if (wait_for_q)
{
wait_empty_q(); // return when queue is empty wait_empty_q(); // return when queue is empty
} }
}
inline void spdlog::details::async_log_helper::worker_loop() inline void spdlog::details::async_log_helper::worker_loop()
{ {
if (_worker_warmup_cb) if (_worker_warmup_cb)
{
_worker_warmup_cb(); _worker_warmup_cb();
}
auto last_pop = details::os::now(); auto last_pop = details::os::now();
auto last_flush = last_pop; auto last_flush = last_pop;
auto active = true; auto active = true;
@ -273,8 +277,10 @@ inline void spdlog::details::async_log_helper::worker_loop()
} }
} }
if (_worker_teardown_cb) if (_worker_teardown_cb)
{
_worker_teardown_cb(); _worker_teardown_cb();
} }
}
// process next message in the queue // process next message in the queue
// return true if this thread should still be active (while no terminate msg was received) // return true if this thread should still be active (while no terminate msg was received)
@ -327,7 +333,9 @@ inline void spdlog::details::async_log_helper::handle_flush_interval(log_clock::
if (should_flush) if (should_flush)
{ {
for (auto &s : _sinks) for (auto &s : _sinks)
{
s->flush(); s->flush();
}
now = last_flush = details::os::now(); now = last_flush = details::os::now();
_flush_requested = false; _flush_requested = false;
} }
@ -349,15 +357,21 @@ inline void spdlog::details::async_log_helper::sleep_or_yield(
// spin upto 50 micros // spin upto 50 micros
if (time_since_op <= microseconds(50)) if (time_since_op <= microseconds(50))
{
return; return;
}
// yield upto 150 micros // yield upto 150 micros
if (time_since_op <= microseconds(100)) if (time_since_op <= microseconds(100))
{
return std::this_thread::yield(); return std::this_thread::yield();
}
// sleep for 20 ms upto 200 ms // sleep for 20 ms upto 200 ms
if (time_since_op <= milliseconds(200)) if (time_since_op <= milliseconds(200))
{
return details::os::sleep_for_millis(20); return details::os::sleep_for_millis(20);
}
// sleep for 500 ms // sleep for 500 ms
return details::os::sleep_for_millis(500); return details::os::sleep_for_millis(500);

View File

@ -79,8 +79,10 @@ inline void spdlog::async_logger::_sink_it(details::log_msg &msg)
#endif #endif
_async_log_helper->log(msg); _async_log_helper->log(msg);
if (_should_flush_on(msg)) if (_should_flush_on(msg))
{
_async_log_helper->flush(false); // do async flush _async_log_helper->flush(false); // do async flush
} }
}
catch (const std::exception &ex) catch (const std::exception &ex)
{ {
_err_handler(ex.what()); _err_handler(ex.what());

View File

@ -47,7 +47,9 @@ public:
for (int tries = 0; tries < open_tries; ++tries) for (int tries = 0; tries < open_tries; ++tries)
{ {
if (!os::fopen_s(&_fd, fname, mode)) if (!os::fopen_s(&_fd, fname, mode))
{
return; return;
}
details::os::sleep_for_millis(open_interval); details::os::sleep_for_millis(open_interval);
} }
@ -58,7 +60,9 @@ public:
void reopen(bool truncate) void reopen(bool truncate)
{ {
if (_filename.empty()) if (_filename.empty())
{
throw spdlog_ex("Failed re opening file - was not opened before"); throw spdlog_ex("Failed re opening file - was not opened before");
}
open(_filename, truncate); open(_filename, truncate);
} }
@ -81,8 +85,10 @@ public:
size_t msg_size = msg.formatted.size(); size_t msg_size = msg.formatted.size();
auto data = msg.formatted.data(); auto data = msg.formatted.data();
if (std::fwrite(data, 1, msg_size, _fd) != msg_size) if (std::fwrite(data, 1, msg_size, _fd) != msg_size)
{
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno); throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
} }
}
size_t size() const size_t size() const
{ {
@ -122,12 +128,16 @@ public:
// no valid extension found - return whole path and empty string as extension // no valid extension found - return whole path and empty string as extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
{
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());
}
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile" // treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep); auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != fname.npos && folder_index >= ext_index - 1) if (folder_index != fname.npos && folder_index >= ext_index - 1)
{
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());
}
// finally - return a valid base and extension tuple // finally - return a valid base and extension tuple
return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index)); return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));

View File

@ -54,7 +54,9 @@ template<typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args) inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Args &... args)
{ {
if (!should_log(lvl)) if (!should_log(lvl))
{
return; return;
}
try try
{ {
@ -82,7 +84,9 @@ template<typename... Args>
inline void spdlog::logger::log(level::level_enum lvl, const char *msg) inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
{ {
if (!should_log(lvl)) if (!should_log(lvl))
{
return; return;
}
try try
{ {
details::log_msg log_msg(&_name, lvl); details::log_msg log_msg(&_name, lvl);
@ -104,7 +108,9 @@ template<typename T>
inline void spdlog::logger::log(level::level_enum lvl, const T &msg) inline void spdlog::logger::log(level::level_enum lvl, const T &msg)
{ {
if (!should_log(lvl)) if (!should_log(lvl))
{
return; return;
}
try try
{ {
details::log_msg log_msg(&_name, lvl); details::log_msg log_msg(&_name, lvl);
@ -309,8 +315,10 @@ inline void spdlog::logger::_sink_it(details::log_msg &msg)
} }
if (_should_flush_on(msg)) if (_should_flush_on(msg))
{
flush(); flush();
} }
}
inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time) inline void spdlog::logger::_set_pattern(const std::string &pattern, pattern_time_type pattern_time)
{ {
@ -325,14 +333,18 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter)
inline void spdlog::logger::flush() inline void spdlog::logger::flush()
{ {
for (auto &sink : _sinks) for (auto &sink : _sinks)
{
sink->flush(); sink->flush();
} }
}
inline void spdlog::logger::_default_err_handler(const std::string &msg) inline void spdlog::logger::_default_err_handler(const std::string &msg)
{ {
auto now = time(nullptr); auto now = time(nullptr);
if (now - _last_err_time < 60) if (now - _last_err_time < 60)
{
return; return;
}
auto tm_time = details::os::localtime(now); auto tm_time = details::os::localtime(now);
char date_buf[100]; char date_buf[100];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time); std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);

View File

@ -64,10 +64,14 @@ public:
{ {
// queue size must be power of two // queue size must be power of two
if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0))) if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)))
{
throw spdlog_ex("async logger queue size must be power of two"); throw spdlog_ex("async logger queue size must be power of two");
}
for (size_t i = 0; i != buffer_size; i += 1) for (size_t i = 0; i != buffer_size; i += 1)
{
buffer_[i].sequence_.store(i, std::memory_order_relaxed); buffer_[i].sequence_.store(i, std::memory_order_relaxed);
}
enqueue_pos_.store(0, std::memory_order_relaxed); enqueue_pos_.store(0, std::memory_order_relaxed);
dequeue_pos_.store(0, std::memory_order_relaxed); dequeue_pos_.store(0, std::memory_order_relaxed);
} }
@ -92,8 +96,10 @@ public:
if (dif == 0) if (dif == 0)
{ {
if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
{
break; break;
} }
}
else if (dif < 0) else if (dif < 0)
{ {
return false; return false;
@ -120,13 +126,19 @@ public:
if (dif == 0) if (dif == 0)
{ {
if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
{
break; break;
} }
}
else if (dif < 0) else if (dif < 0)
{
return false; return false;
}
else else
{
pos = dequeue_pos_.load(std::memory_order_relaxed); pos = dequeue_pos_.load(std::memory_order_relaxed);
} }
}
data = std::move(cell->data_); data = std::move(cell->data_);
cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release); cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release);
return true; return true;

View File

@ -148,7 +148,9 @@ inline void prevent_child_fd(FILE *f)
#else #else
auto fd = fileno(f); auto fd = fileno(f);
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
{
throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno); throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
}
#endif #endif
} }
@ -167,7 +169,9 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod
#ifdef SPDLOG_PREVENT_CHILD_FD #ifdef SPDLOG_PREVENT_CHILD_FD
if (*fp != nullptr) if (*fp != nullptr)
{
prevent_child_fd(*fp); prevent_child_fd(*fp);
}
#endif #endif
return *fp == nullptr; return *fp == nullptr;
} }
@ -210,18 +214,24 @@ inline bool file_exists(const filename_t &filename)
inline size_t filesize(FILE *f) inline size_t filesize(FILE *f)
{ {
if (f == nullptr) if (f == nullptr)
{
throw spdlog_ex("Failed getting file size. fd is null"); throw spdlog_ex("Failed getting file size. fd is null");
}
#if defined(_WIN32) && !defined(__CYGWIN__) #if defined(_WIN32) && !defined(__CYGWIN__)
int fd = _fileno(f); int fd = _fileno(f);
#if _WIN64 // 64 bits #if _WIN64 // 64 bits
struct _stat64 st; struct _stat64 st;
if (_fstat64(fd, &st) == 0) if (_fstat64(fd, &st) == 0)
{
return st.st_size; return st.st_size;
}
#else // windows 32 bits #else // windows 32 bits
long ret = _filelength(fd); long ret = _filelength(fd);
if (ret >= 0) if (ret >= 0)
{
return static_cast<size_t>(ret); return static_cast<size_t>(ret);
}
#endif #endif
#else // unix #else // unix
@ -230,11 +240,15 @@ inline size_t filesize(FILE *f)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st; struct stat64 st;
if (fstat64(fd, &st) == 0) if (fstat64(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size); return static_cast<size_t>(st.st_size);
}
#else // unix 32 bits or cygwin #else // unix 32 bits or cygwin
struct stat st; struct stat st;
if (fstat(fd, &st) == 0) if (fstat(fd, &st) == 0)
{
return static_cast<size_t>(st.st_size); return static_cast<size_t>(st.st_size);
}
#endif #endif
#endif #endif
throw spdlog_ex("Failed getting file size from fd", errno); throw spdlog_ex("Failed getting file size from fd", errno);
@ -257,9 +271,13 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
int offset = -tzinfo.Bias; int offset = -tzinfo.Bias;
if (tm.tm_isdst) if (tm.tm_isdst)
{
offset -= tzinfo.DaylightBias; offset -= tzinfo.DaylightBias;
}
else else
{
offset -= tzinfo.StandardBias; offset -= tzinfo.StandardBias;
}
return offset; return offset;
#else #else
@ -386,17 +404,25 @@ inline std::string errno_str(int err_num)
#ifdef _WIN32 #ifdef _WIN32
if (strerror_s(buf, buf_size, err_num) == 0) if (strerror_s(buf, buf_size, err_num) == 0)
{
return std::string(buf); return std::string(buf);
}
else else
{
return "Unknown error"; return "Unknown error";
}
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \ #elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \
((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version ((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version
if (strerror_r(err_num, buf, buf_size) == 0) if (strerror_r(err_num, buf, buf_size) == 0)
{
return std::string(buf); return std::string(buf);
}
else else
{
return "Unknown error"; return "Unknown error";
}
#else // gnu version (might not use the given buf, so its retval pointer must be used) #else // gnu version (might not use the given buf, so its retval pointer must be used)
auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type

View File

@ -488,16 +488,24 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string &patter
if (*it == '%') if (*it == '%')
{ {
if (user_chars) // append user chars found so far if (user_chars) // append user chars found so far
{
_formatters.push_back(std::move(user_chars)); _formatters.push_back(std::move(user_chars));
}
if (++it != end) if (++it != end)
{
handle_flag(*it); handle_flag(*it);
}
else else
{
break; break;
} }
}
else // chars not following the % sign should be displayed as is else // chars not following the % sign should be displayed as is
{ {
if (!user_chars) if (!user_chars)
{
user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter()); user_chars = std::unique_ptr<details::aggregate_formatter>(new details::aggregate_formatter());
}
user_chars->add_ch(*it); user_chars->add_ch(*it);
} }
} }

View File

@ -53,16 +53,24 @@ public:
throw_if_exists(logger_name); throw_if_exists(logger_name);
std::shared_ptr<logger> new_logger; std::shared_ptr<logger> new_logger;
if (_async_mode) if (_async_mode)
{
new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy, new_logger = std::make_shared<async_logger>(logger_name, sinks_begin, sinks_end, _async_q_size, _overflow_policy,
_worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb); _worker_warmup_cb, _flush_interval_ms, _worker_teardown_cb);
}
else else
{
new_logger = std::make_shared<logger>(logger_name, sinks_begin, sinks_end); new_logger = std::make_shared<logger>(logger_name, sinks_begin, sinks_end);
}
if (_formatter) if (_formatter)
{
new_logger->set_formatter(_formatter); new_logger->set_formatter(_formatter);
}
if (_err_handler) if (_err_handler)
{
new_logger->set_error_handler(_err_handler); new_logger->set_error_handler(_err_handler);
}
new_logger->set_level(_level); new_logger->set_level(_level);
new_logger->flush_on(_flush_level); new_logger->flush_on(_flush_level);
@ -84,10 +92,14 @@ public:
logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb); logger_name, sinks_begin, sinks_end, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb);
if (_formatter) if (_formatter)
{
new_logger->set_formatter(_formatter); new_logger->set_formatter(_formatter);
}
if (_err_handler) if (_err_handler)
{
new_logger->set_error_handler(_err_handler); new_logger->set_error_handler(_err_handler);
}
new_logger->set_level(_level); new_logger->set_level(_level);
new_logger->flush_on(_flush_level); new_logger->flush_on(_flush_level);
@ -101,8 +113,10 @@ public:
{ {
std::lock_guard<Mutex> lock(_mutex); std::lock_guard<Mutex> lock(_mutex);
for (auto &l : _loggers) for (auto &l : _loggers)
{
fun(l.second); fun(l.second);
} }
}
void drop(const std::string &logger_name) void drop(const std::string &logger_name)
{ {
@ -146,22 +160,28 @@ public:
std::lock_guard<Mutex> lock(_mutex); std::lock_guard<Mutex> lock(_mutex);
_formatter = f; _formatter = f;
for (auto &l : _loggers) for (auto &l : _loggers)
{
l.second->set_formatter(_formatter); l.second->set_formatter(_formatter);
} }
}
void set_pattern(const std::string &pattern) void set_pattern(const std::string &pattern)
{ {
std::lock_guard<Mutex> lock(_mutex); std::lock_guard<Mutex> lock(_mutex);
_formatter = std::make_shared<pattern_formatter>(pattern); _formatter = std::make_shared<pattern_formatter>(pattern);
for (auto &l : _loggers) for (auto &l : _loggers)
{
l.second->set_formatter(_formatter); l.second->set_formatter(_formatter);
} }
}
void set_level(level::level_enum log_level) void set_level(level::level_enum log_level)
{ {
std::lock_guard<Mutex> lock(_mutex); std::lock_guard<Mutex> lock(_mutex);
for (auto &l : _loggers) for (auto &l : _loggers)
{
l.second->set_level(log_level); l.second->set_level(log_level);
}
_level = log_level; _level = log_level;
} }
@ -169,14 +189,18 @@ public:
{ {
std::lock_guard<Mutex> lock(_mutex); std::lock_guard<Mutex> lock(_mutex);
for (auto &l : _loggers) for (auto &l : _loggers)
{
l.second->flush_on(log_level); l.second->flush_on(log_level);
}
_flush_level = log_level; _flush_level = log_level;
} }
void set_error_handler(log_err_handler handler) void set_error_handler(log_err_handler handler)
{ {
for (auto &l : _loggers) for (auto &l : _loggers)
{
l.second->set_error_handler(handler); l.second->set_error_handler(handler);
}
_err_handler = handler; _err_handler = handler;
} }
@ -210,8 +234,10 @@ private:
void throw_if_exists(const std::string &logger_name) void throw_if_exists(const std::string &logger_name)
{ {
if (_loggers.find(logger_name) != _loggers.end()) if (_loggers.find(logger_name) != _loggers.end())
{
throw spdlog_ex("logger with name '" + logger_name + "' already exists"); throw spdlog_ex("logger with name '" + logger_name + "' already exists");
} }
}
Mutex _mutex; Mutex _mutex;
std::unordered_map<std::string, std::shared_ptr<logger>> _loggers; std::unordered_map<std::string, std::shared_ptr<logger>> _loggers;

View File

@ -43,8 +43,10 @@ protected:
{ {
_file_helper.write(msg); _file_helper.write(msg);
if (_force_flush) if (_force_flush)
{
_file_helper.flush(); _file_helper.flush();
} }
}
void _flush() override void _flush() override
{ {
@ -199,7 +201,9 @@ public:
, _rotation_m(rotation_minute) , _rotation_m(rotation_minute)
{ {
if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59) if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
{
throw spdlog_ex("daily_file_sink: Invalid rotation time in ctor"); throw spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
}
_rotation_tp = _next_rotation_tp(); _rotation_tp = _next_rotation_tp();
_file_helper.open(FileNameCalc::calc_filename(_base_filename)); _file_helper.open(FileNameCalc::calc_filename(_base_filename));
} }