From 74ab7feb35cc8f46c7ce1993b81039657df8110f Mon Sep 17 00:00:00 2001 From: Odysseas Georgoudis Date: Tue, 21 Nov 2023 02:17:12 +0000 Subject: [PATCH] cosmetic changes from static analysis --- benchmarks/hot_path_latency/hot_path_bench.h | 6 +- examples/example_trivial.cpp | 4 +- quill/include/quill/Clock.h | 2 + quill/include/quill/Logger.h | 2 +- quill/include/quill/Quill.h | 2 +- .../include/quill/detail/HandlerCollection.h | 11 ++-- quill/include/quill/detail/LogManager.h | 14 ++--- quill/include/quill/detail/LoggerCollection.h | 2 +- quill/include/quill/detail/Serialize.h | 26 ++++----- quill/include/quill/detail/ThreadContext.h | 18 +----- .../quill/detail/ThreadContextCollection.h | 17 ++---- .../quill/detail/backend/BackendWorker.h | 39 ++++++------- .../quill/detail/backend/TransitEventBuffer.h | 2 +- quill/include/quill/detail/misc/Common.h | 4 +- .../include/quill/detail/misc/FileUtilities.h | 3 +- quill/include/quill/detail/misc/Os.h | 4 +- .../quill/detail/misc/TypeTraitsCopyable.h | 4 +- quill/include/quill/detail/misc/Utilities.h | 20 ++----- .../quill/detail/spsc_queue/UnboundedQueue.h | 11 ++-- quill/include/quill/filters/FilterBase.h | 2 +- quill/include/quill/handlers/ConsoleHandler.h | 2 +- quill/include/quill/handlers/FileHandler.h | 2 +- quill/include/quill/handlers/Handler.h | 4 +- .../include/quill/handlers/JsonFileHandler.h | 2 +- .../quill/handlers/RotatingFileHandler.h | 5 +- quill/src/LogLevel.cpp | 4 +- quill/src/PatternFormatter.cpp | 6 +- quill/src/Quill.cpp | 4 +- quill/src/Utility.cpp | 2 +- quill/src/detail/HandlerCollection.cpp | 19 +++---- quill/src/detail/LoggerCollection.cpp | 31 +++++----- quill/src/detail/SignalHandler.cpp | 16 ++---- quill/src/detail/backend/BackendWorker.cpp | 25 +++------ quill/src/detail/backend/BacktraceStorage.cpp | 4 +- quill/src/detail/backend/StringFromTime.cpp | 6 +- .../src/detail/backend/TimestampFormatter.cpp | 15 ++--- .../src/detail/backend/TransitEventBuffer.cpp | 10 ++-- quill/src/detail/misc/FileUtilities.cpp | 2 +- quill/src/detail/misc/Os.cpp | 8 +-- quill/src/detail/misc/RdtscClock.cpp | 6 +- quill/src/handlers/ConsoleHandler.cpp | 10 ++-- quill/src/handlers/FileHandler.cpp | 8 ++- quill/src/handlers/RotatingFileHandler.cpp | 56 ++++++++----------- quill/src/handlers/StreamHandler.cpp | 9 ++- quill/test/BoundedQueueTest.cpp | 6 +- quill/test/FileUtilitiesTest.cpp | 6 +- quill/test/HandlerCollectionTest.cpp | 4 +- quill/test/LogTest.cpp | 12 ++-- quill/test/QuillLogNoTransitBufferTest.cpp | 2 +- quill/test/QuillLogTest.cpp | 8 +-- quill/test/QuillLogWakeUpBackendTest.cpp | 2 +- quill/test/QuillStructuredLogTest.cpp | 4 +- quill/test/RdtscClockTest.cpp | 4 +- quill/test/TimestampFormatterTest.cpp | 28 +++++----- quill/test/TransitEventBufferTest.cpp | 2 +- quill/test/TypeTraitsCopyableTest.cpp | 4 +- quill/test/UnboundedQueueTest.cpp | 2 +- quill/test/UtilitiesTest.cpp | 16 +++--- quill/test/misc/TestUtilities.cpp | 9 ++- 59 files changed, 248 insertions(+), 310 deletions(-) diff --git a/benchmarks/hot_path_latency/hot_path_bench.h b/benchmarks/hot_path_latency/hot_path_bench.h index cc3b1de1..b7774f9e 100644 --- a/benchmarks/hot_path_latency/hot_path_bench.h +++ b/benchmarks/hot_path_latency/hot_path_bench.h @@ -18,7 +18,11 @@ #include #include -#include +#if defined(_WIN32) + #include +#else + #include +#endif // Instead of sleep inline void wait(std::chrono::nanoseconds min, std::chrono::nanoseconds max) diff --git a/examples/example_trivial.cpp b/examples/example_trivial.cpp index 6d055472..1d786569 100644 --- a/examples/example_trivial.cpp +++ b/examples/example_trivial.cpp @@ -56,7 +56,7 @@ int main() char_arrays.mid_0); // Using a dynamic runtime log level - std::array const runtime_log_levels = { + std::array constexpr runtime_log_levels = { quill::LogLevel::Debug, quill::LogLevel::Info, quill::LogLevel::Warning, quill::LogLevel::Error}; for (auto const& log_level : runtime_log_levels) @@ -123,7 +123,7 @@ int main() LOG_CRITICAL(logger_1, "This is never logged"); // Get all created loggers - std::unordered_map created_loggers = quill::get_all_loggers(); + std::unordered_map const created_loggers = quill::get_all_loggers(); std::vector logger_names; for (auto const& elem : created_loggers) { diff --git a/quill/include/quill/Clock.h b/quill/include/quill/Clock.h index 9e133442..afc31848 100644 --- a/quill/include/quill/Clock.h +++ b/quill/include/quill/Clock.h @@ -3,6 +3,8 @@ * Distributed under the MIT License (http://opensource.org/licenses/MIT) */ +#pragma once + #include "quill/detail/LogManager.h" #include "quill/detail/misc/Attributes.h" #include "quill/detail/misc/Rdtsc.h" diff --git a/quill/include/quill/Logger.h b/quill/include/quill/Logger.h index 215a90eb..8228317a 100644 --- a/quill/include/quill/Logger.h +++ b/quill/include/quill/Logger.h @@ -231,7 +231,7 @@ class alignas(detail::CACHE_LINE_ALIGNED) Logger // look up their types to deserialize them // Note: The metadata variable here is created during program init time, - std::byte* const write_begin = write_buffer; + std::byte const* const write_begin = write_buffer; write_buffer = detail::align_pointer(write_buffer); constexpr bool is_printf_format = macro_metadata.is_printf_format(); diff --git a/quill/include/quill/Quill.h b/quill/include/quill/Quill.h index 0f57f5c6..91a9b798 100644 --- a/quill/include/quill/Quill.h +++ b/quill/include/quill/Quill.h @@ -34,7 +34,7 @@ namespace quill /** Version Info **/ constexpr uint32_t VersionMajor{3}; constexpr uint32_t VersionMinor{4}; -constexpr uint32_t VersionPatch{1}; +constexpr uint32_t VersionPatch{2}; constexpr uint32_t Version{VersionMajor * 10000 + VersionMinor * 100 + VersionPatch}; /** forward declarations **/ diff --git a/quill/include/quill/detail/HandlerCollection.h b/quill/include/quill/detail/HandlerCollection.h index ffe01d3f..d8fb7cfd 100644 --- a/quill/include/quill/detail/HandlerCollection.h +++ b/quill/include/quill/detail/HandlerCollection.h @@ -78,10 +78,9 @@ class HandlerCollection { return handler; } - else - { + // recreate this handler - if constexpr (std::is_base_of::value) + if constexpr (std::is_base_of_v) { handler = std::make_shared(handler_name, std::forward(args)...); } @@ -92,12 +91,12 @@ class HandlerCollection search->second = handler; return handler; - } + } // if first time add it std::shared_ptr handler; - if constexpr (std::is_base_of::value) + if constexpr (std::is_base_of_v) { handler = std::make_shared(handler_name, std::forward(args)...); } @@ -116,7 +115,7 @@ class HandlerCollection * @throws std::runtime_error if the handler does not exist * @return a shared_ptr to the handler */ - QUILL_NODISCARD QUILL_ATTRIBUTE_COLD std::shared_ptr get_handler(std::string const& handler_name); + QUILL_NODISCARD QUILL_ATTRIBUTE_COLD std::shared_ptr get_handler(std::string const& handler_name) const; /** * Subscribe a handler to the vector of active handlers so that the backend thread can see it diff --git a/quill/include/quill/detail/LogManager.h b/quill/include/quill/detail/LogManager.h index 89c902dc..c9ebef70 100644 --- a/quill/include/quill/detail/LogManager.h +++ b/quill/include/quill/detail/LogManager.h @@ -103,7 +103,7 @@ class LogManager std::optional timestamp_clock) { return _logger_collection.create_logger( - logger_name, handlers, + logger_name, std::move(handlers), timestamp_clock_type.has_value() ? *timestamp_clock_type : _config.default_timestamp_clock_type, timestamp_clock.has_value() ? *timestamp_clock : _config.default_custom_timestamp_clock); } @@ -138,7 +138,7 @@ class LogManager // get the root logger - this is needed for the logger_details struct, in order to figure out // the clock type later on the backend thread Logger* default_logger = logger_collection().get_logger(nullptr); - LoggerDetails* logger_details = std::addressof(default_logger->_logger_details); + LoggerDetails const* logger_details = std::addressof(default_logger->_logger_details); // Create an atomic variable std::atomic backend_thread_flushed{false}; @@ -155,11 +155,11 @@ class LogManager detail::ThreadContext* const thread_context = _thread_context_collection.local_thread_context(); - size_t const total_size = sizeof(detail::Header) + sizeof(uintptr_t); + size_t constexpr total_size = sizeof(detail::Header) + sizeof(uintptr_t); std::byte* write_buffer = thread_context->spsc_queue().prepare_write(static_cast(total_size)); - std::byte* const write_begin = write_buffer; + std::byte const* const write_begin = write_buffer; write_buffer = detail::align_pointer(write_buffer); @@ -195,7 +195,7 @@ class LogManager * Starts the backend worker thread. * This should only be called by the LogManagerSingleton and never directly from here */ - QUILL_ATTRIBUTE_COLD void inline start_backend_worker(bool with_signal_handler, + QUILL_ATTRIBUTE_COLD void start_backend_worker(bool with_signal_handler, std::initializer_list const& catchable_signals) { if (with_signal_handler) @@ -247,7 +247,7 @@ class LogManager /** * @return true if backend worker has started */ - QUILL_NODISCARD QUILL_ATTRIBUTE_COLD bool backend_worker_is_running() noexcept + QUILL_NODISCARD QUILL_ATTRIBUTE_COLD bool backend_worker_is_running() const noexcept { return _backend_worker.is_running(); } @@ -300,7 +300,7 @@ class LogManagerSingleton */ detail::LogManager& log_manager() noexcept { return _log_manager; } - QUILL_ATTRIBUTE_COLD void inline start_backend_worker(bool with_signal_handler, + QUILL_ATTRIBUTE_COLD void start_backend_worker(bool with_signal_handler, std::initializer_list const& catchable_signals) { // protect init to be called only once diff --git a/quill/include/quill/detail/LoggerCollection.h b/quill/include/quill/detail/LoggerCollection.h index fc4ff00c..a35aca86 100644 --- a/quill/include/quill/detail/LoggerCollection.h +++ b/quill/include/quill/detail/LoggerCollection.h @@ -122,7 +122,7 @@ class LoggerCollection * This is meant to called before quill:start() and that is checked internally before calling * this function. */ - QUILL_ATTRIBUTE_COLD void enable_console_colours() noexcept; + QUILL_ATTRIBUTE_COLD void enable_console_colours() const noexcept; /** * Get the root logger pointer diff --git a/quill/include/quill/detail/Serialize.h b/quill/include/quill/detail/Serialize.h index 4b5b04ee..6e2cdccc 100644 --- a/quill/include/quill/detail/Serialize.h +++ b/quill/include/quill/detail/Serialize.h @@ -7,7 +7,7 @@ #ifndef __STDC_WANT_LIB_EXT1__ #define __STDC_WANT_LIB_EXT1__ 1 - #include + #include #endif #include "misc/Utilities.h" @@ -42,9 +42,9 @@ class LoggerDetails; template QUILL_NODISCARD constexpr bool is_type_of_c_array() { - using ArgType = detail::remove_cvref_t; - return std::is_array::value && - std::is_same::type>, char>::value; + using ArgType = remove_cvref_t; + return std::is_array_v && + std::is_same_v>, char>; } template @@ -78,7 +78,7 @@ QUILL_NODISCARD constexpr bool is_type_of_wide_string() #endif template -QUILL_NODISCARD inline constexpr bool need_call_dtor_for() +QUILL_NODISCARD constexpr bool need_call_dtor_for() { using ArgType = detail::remove_cvref_t; @@ -94,18 +94,18 @@ QUILL_NODISCARD inline constexpr bool need_call_dtor_for() return false; } - return !std::is_trivially_destructible::value; + return !std::is_trivially_destructible_v; } template -QUILL_NODISCARD QUILL_ATTRIBUTE_HOT inline std::byte* decode_args( +QUILL_NODISCARD QUILL_ATTRIBUTE_HOT std::byte* decode_args( std::byte* in, std::vector>&, std::byte**) { return in; } template -QUILL_NODISCARD QUILL_ATTRIBUTE_HOT inline std::byte* decode_args( +QUILL_NODISCARD QUILL_ATTRIBUTE_HOT std::byte* decode_args( std::byte* in, std::vector>& args, std::byte** destruct_args) { using ArgType = detail::remove_cvref_t; @@ -168,12 +168,12 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_HOT inline std::byte* decode_args( } template -QUILL_ATTRIBUTE_HOT inline void destruct_args(std::byte**) +QUILL_ATTRIBUTE_HOT void destruct_args(std::byte**) { } template -QUILL_ATTRIBUTE_HOT inline void destruct_args(std::byte** args) +QUILL_ATTRIBUTE_HOT void destruct_args(std::byte** args) { using ArgType = detail::remove_cvref_t; if constexpr (need_call_dtor_for()) @@ -364,7 +364,7 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_HOT std::pair format_to { std::string error; constexpr size_t num_dtors = fmtquill::detail::count()...>(); - std::byte* dtor_args[(std::max)(num_dtors, (size_t)1)]; + std::byte* dtor_args[(std::max)(num_dtors, static_cast(1))]; args.clear(); std::byte* ret = decode_args(data, args, dtor_args); @@ -397,7 +397,7 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_HOT std::pair printf_fo { std::string error; constexpr size_t num_dtors = fmtquill::detail::count()...>(); - std::byte* dtor_args[(std::max)(num_dtors, (size_t)1)]; + std::byte* dtor_args[(std::max)(num_dtors, static_cast(1))]; args.clear(); std::byte* ret = decode_args(data, args, dtor_args); @@ -455,7 +455,7 @@ struct Header public: Header() = default; Header(MetadataFormatFn metadata_and_format_fn, detail::LoggerDetails const* logger_details, uint64_t timestamp) - : metadata_and_format_fn(metadata_and_format_fn), logger_details(logger_details), timestamp(timestamp){}; + : metadata_and_format_fn(metadata_and_format_fn), logger_details(logger_details), timestamp(timestamp){} MetadataFormatFn metadata_and_format_fn{nullptr}; detail::LoggerDetails const* logger_details{nullptr}; diff --git a/quill/include/quill/detail/ThreadContext.h b/quill/include/quill/detail/ThreadContext.h index f6a43c2e..a1e89446 100644 --- a/quill/include/quill/detail/ThreadContext.h +++ b/quill/include/quill/detail/ThreadContext.h @@ -28,7 +28,7 @@ namespace quill::detail * The backend thread reads all existing ThreadContext class instances and pop the events * from each thread queue */ -class ThreadContext +class alignas(CACHE_LINE_ALIGNED) ThreadContext { public: /** @@ -55,22 +55,6 @@ class ThreadContext ThreadContext(ThreadContext const&) = delete; ThreadContext& operator=(ThreadContext const&) = delete; - /** - * Operator new to align this object to a cache line boundary as we always create it on the heap - * This object should always be aligned to a cache line as it contains the SPSC queue as a member - * which has cache line alignment requirements - * @param i size of object - * @return a pointer to the allocated object - */ - void* operator new(size_t i) { return alloc_aligned(i, CACHE_LINE_ALIGNED); } - - /** - * Operator delete - * @see operator new - * @param p pointer to object - */ - void operator delete(void* p) { free_aligned(p); } - /** * @return A reference to the backend's thread transit event buffer */ diff --git a/quill/include/quill/detail/ThreadContextCollection.h b/quill/include/quill/detail/ThreadContextCollection.h index e931951a..5d80ef69 100644 --- a/quill/include/quill/detail/ThreadContextCollection.h +++ b/quill/include/quill/detail/ThreadContextCollection.h @@ -54,18 +54,9 @@ class ThreadContextCollection ThreadContextWrapper(ThreadContextCollection& thread_context_collection, uint32_t default_queue_capacity, uint32_t initial_transit_event_buffer_capacity, bool huge_pages) : _thread_context_collection(thread_context_collection), - _thread_context(std::shared_ptr(new ThreadContext( - queue_type, default_queue_capacity, initial_transit_event_buffer_capacity, huge_pages))) + _thread_context(std::make_shared( + queue_type, default_queue_capacity, initial_transit_event_buffer_capacity, huge_pages)) { - // We can not use std::make_shared above. - // Explanation : - // ThreadContext has the SPSC queue as a class member which requires a 64 cache byte alignment, - // since we are creating this object on the heap this is not guaranteed. - // Visual Studio is the only compiler that gives a warning that ThreadContext might not be aligned to 64 bytes, - // as it is allocated on the heap, and we should use aligned alloc instead. - // The solution to solve this would be to define a custom operator new and operator delete for ThreadContext. - // However, when using std::make_shared, the default allocator is used. - // This is a problem if the class is supposed to use a non-default allocator like ThreadContext _thread_context_collection.register_thread_context(_thread_context); } @@ -143,7 +134,7 @@ class ThreadContextCollection template QUILL_NODISCARD_ALWAYS_INLINE_HOT ThreadContext* local_thread_context() noexcept { - static thread_local ThreadContextWrapper thread_context_wrapper{ + thread_local ThreadContextWrapper thread_context_wrapper{ *this, _config.default_queue_capacity, _config.backend_thread_use_transit_buffer ? _config.backend_thread_initial_transit_event_buffer_capacity : 1, _config.enable_huge_pages_hot_path}; @@ -277,7 +268,7 @@ class ThreadContextCollection { std::lock_guard const lock(_mutex); - auto thread_context_it = std::find_if(_thread_contexts.begin(), _thread_contexts.end(), + auto const thread_context_it = std::find_if(_thread_contexts.begin(), _thread_contexts.end(), [thread_context](std::shared_ptr const& elem) { return elem.get() == thread_context; }); diff --git a/quill/include/quill/detail/backend/BackendWorker.h b/quill/include/quill/detail/backend/BackendWorker.h index d6182fc7..372625e9 100644 --- a/quill/include/quill/detail/backend/BackendWorker.h +++ b/quill/include/quill/detail/backend/BackendWorker.h @@ -119,12 +119,13 @@ class BackendWorker /** * Deserialize messages from the raw SPSC queue + * @param queue queue * @param thread_context thread context * @param ts_now timestamp now * @return total events stored in the transit_event_buffer */ template - QUILL_ATTRIBUTE_HOT inline uint32_t _read_queue_messages_and_decode(QueueT& queue, ThreadContext* thread_context, + QUILL_ATTRIBUTE_HOT uint32_t _read_queue_messages_and_decode(QueueT& queue, ThreadContext* thread_context, uint64_t ts_now); QUILL_ATTRIBUTE_HOT inline bool _get_transit_event_from_queue(std::byte*& read_pos, ThreadContext* thread_context, @@ -144,7 +145,7 @@ class BackendWorker /** * Write a transit event */ - QUILL_ATTRIBUTE_HOT inline void _write_transit_event(TransitEvent const& transit_event); + QUILL_ATTRIBUTE_HOT inline void _write_transit_event(TransitEvent const& transit_event) const; /** * Process the lowest timestamp from the queues and write it to the log file @@ -160,6 +161,7 @@ class BackendWorker /** * Check for dropped messages - only when bounded queue is used * @param cached_thread_contexts loaded thread contexts + * @param notification_handler notification handler */ QUILL_ATTRIBUTE_HOT inline static void _check_message_failures( ThreadContextCollection::backend_thread_contexts_cache_t const& cached_thread_contexts, @@ -180,7 +182,7 @@ class BackendWorker * @return start position of read */ QUILL_NODISCARD QUILL_ATTRIBUTE_HOT inline std::byte* _read_unbounded_queue(UnboundedQueue& queue, - ThreadContext* thread_context); + ThreadContext* thread_context) const; QUILL_NODISCARD QUILL_ATTRIBUTE_HOT inline bool _check_all_queues_empty( ThreadContextCollection::backend_thread_contexts_cache_t const& cached_thread_contexts); @@ -387,7 +389,7 @@ uint32_t BackendWorker::_read_queue_messages_and_decode(QueueT& queue, ThreadCon // This means that if we can read something from the queue it will be a full message // The producer will add items to the buffer : // |timestamp|metadata*|logger_details*|args...| - detail::UnboundedTransitEventBuffer& transit_event_buffer = thread_context->transit_event_buffer(); + detail::UnboundedTransitEventBuffer const& transit_event_buffer = thread_context->transit_event_buffer(); size_t const queue_capacity = queue.capacity(); uint32_t total_bytes_read{0}; @@ -412,11 +414,9 @@ uint32_t BackendWorker::_read_queue_messages_and_decode(QueueT& queue, ThreadCon return transit_event_buffer.size(); } - std::byte* const read_begin = read_pos; + std::byte const* const read_begin = read_pos; - bool res = _get_transit_event_from_queue(read_pos, thread_context, ts_now); - - if (!res) + if (!_get_transit_event_from_queue(read_pos, thread_context, ts_now)) { // if _get_transit_event_from_queue returns false we stop reading return transit_event_buffer.size(); @@ -558,8 +558,7 @@ bool BackendWorker::_get_transit_event_from_queue(std::byte*& read_pos, ThreadCo std::vector const* s_keys{nullptr}; // for messages containing named arguments threat them as structured logs - auto const search = _slog_templates.find(_structured_fmt_str); - if (search != std::cend(_slog_templates)) + if (auto const search = _slog_templates.find(_structured_fmt_str); search != std::cend(_slog_templates)) { auto const& [fmt_str, structured_keys] = search->second; s_keys = &structured_keys; @@ -682,8 +681,7 @@ void BackendWorker::_process_transit_events(ThreadContextCollection::backend_thr for (ThreadContext* thread_context : cached_thread_contexts) { - TransitEvent* te = thread_context->transit_event_buffer().front(); - if (te && min_ts > te->header.timestamp) + if (TransitEvent const* te = thread_context->transit_event_buffer().front(); te && (min_ts > te->header.timestamp)) { min_ts = te->header.timestamp; transit_buffer = std::addressof(thread_context->transit_event_buffer()); @@ -729,8 +727,8 @@ void BackendWorker::_process_transit_event(TransitEvent& transit_event) if (QUILL_UNLIKELY(transit_event.log_level() >= transit_event.header.logger_details->backtrace_flush_level())) { _backtrace_log_message_storage.process(transit_event.header.logger_details->name(), - [this](TransitEvent const& transit_event) - { _write_transit_event(transit_event); }); + [this](TransitEvent const& te) + { _write_transit_event(te); }); } } else @@ -751,8 +749,8 @@ void BackendWorker::_process_transit_event(TransitEvent& transit_event) { // process all records in backtrace for this logger_name and log them by calling backend_process_backtrace_log_message _backtrace_log_message_storage.process(transit_event.header.logger_details->name(), - [this](TransitEvent const& transit_event) - { _write_transit_event(transit_event); }); + [this](TransitEvent const& te) + { _write_transit_event(te); }); } else if (macro_metadata.event() == MacroMetadata::Event::Flush) { @@ -780,7 +778,7 @@ void BackendWorker::_process_transit_event(TransitEvent& transit_event) } /***/ -void BackendWorker::_write_transit_event(TransitEvent const& transit_event) +void BackendWorker::_write_transit_event(TransitEvent const& transit_event) const { // Forward the record to all the logger handlers MacroMetadata const macro_metadata = transit_event.metadata(); @@ -862,7 +860,7 @@ bool BackendWorker::_process_and_write_single_message(const ThreadContextCollect } assert(read_pos); - std::byte* const read_begin = read_pos; + std::byte const* const read_begin = read_pos; _get_transit_event_from_queue(read_pos, tc, 0); @@ -951,7 +949,7 @@ void BackendWorker::_check_message_failures(ThreadContextCollection::backend_thr } /***/ -std::byte* BackendWorker::_read_unbounded_queue(UnboundedQueue& queue, ThreadContext* thread_context) +std::byte* BackendWorker::_read_unbounded_queue(UnboundedQueue& queue, ThreadContext* thread_context) const { auto [read_pos, allocation_info] = queue.prepare_read(); @@ -979,7 +977,6 @@ std::byte* BackendWorker::_read_unbounded_queue(UnboundedQueue& queue, ThreadCon } /***/ - bool BackendWorker::_check_all_queues_empty(ThreadContextCollection::backend_thread_contexts_cache_t const& cached_thread_contexts) { bool all_empty{true}; @@ -1183,7 +1180,7 @@ void BackendWorker::_exit() } } - RdtscClock* rdtsc_clock{_rdtsc_clock.load(std::memory_order_relaxed)}; + RdtscClock const* rdtsc_clock{_rdtsc_clock.load(std::memory_order_relaxed)}; _rdtsc_clock.store(nullptr, std::memory_order_release); delete rdtsc_clock; } diff --git a/quill/include/quill/detail/backend/TransitEventBuffer.h b/quill/include/quill/detail/backend/TransitEventBuffer.h index 568d4292..36fc5890 100644 --- a/quill/include/quill/detail/backend/TransitEventBuffer.h +++ b/quill/include/quill/detail/backend/TransitEventBuffer.h @@ -46,7 +46,7 @@ class UnboundedTransitEventBuffer { /** * Constructor - * @param capacity the capacity of the fixed buffer + * @param transit_buffer_capacity the capacity of the fixed buffer */ explicit Node(uint32_t transit_buffer_capacity) : transit_buffer(transit_buffer_capacity) {} diff --git a/quill/include/quill/detail/misc/Common.h b/quill/include/quill/detail/misc/Common.h index 001fe1d7..8c8a7dc3 100644 --- a/quill/include/quill/detail/misc/Common.h +++ b/quill/include/quill/detail/misc/Common.h @@ -131,11 +131,9 @@ constexpr bool detect_structured_log_template(std::string_view fmt) ++char_cnt; continue; } - else - { + // we found '{' match, we can break break; - } } ++pos; diff --git a/quill/include/quill/detail/misc/FileUtilities.h b/quill/include/quill/detail/misc/FileUtilities.h index 1fde5236..e00f01f0 100644 --- a/quill/include/quill/detail/misc/FileUtilities.h +++ b/quill/include/quill/detail/misc/FileUtilities.h @@ -80,7 +80,7 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_COLD fs::path append_date_time_to_filename( /** * Constructs a datetime string that can be used for filename naming - * @param timestamp timestamp + * @param timestamp_ns timestamp * @param timezone timezone * @param with_time with_time * @return @@ -101,7 +101,6 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_COLD fs::path append_index_to_filename(fs::path * Append an index to the given filename * @param filename the name of the file * @param text the text to append - * @param separator the text to append * @return a filepath with the index appended */ QUILL_NODISCARD QUILL_ATTRIBUTE_COLD fs::path append_string_to_filename(fs::path const& filename, diff --git a/quill/include/quill/detail/misc/Os.h b/quill/include/quill/detail/misc/Os.h index 8ba53ac2..13aa56ca 100644 --- a/quill/include/quill/detail/misc/Os.h +++ b/quill/include/quill/detail/misc/Os.h @@ -125,7 +125,7 @@ QUILL_NODISCARD QUILL_ATTRIBUTE_COLD bool is_in_terminal(FILE* file) noexcept; /** * fsync the file descriptor - * @param f file + * @param fd file */ -bool fsync(FILE* f); +bool fsync(FILE* fd); } // namespace quill::detail diff --git a/quill/include/quill/detail/misc/TypeTraitsCopyable.h b/quill/include/quill/detail/misc/TypeTraitsCopyable.h index 3a093d00..f93168e0 100644 --- a/quill/include/quill/detail/misc/TypeTraitsCopyable.h +++ b/quill/include/quill/detail/misc/TypeTraitsCopyable.h @@ -63,7 +63,7 @@ template< class T > using remove_cvref_t = typename remove_cvref::type; template -constexpr size_t array_size_v = std::extent>::value; +constexpr size_t array_size_v = std::extent_v>; /** * fmtquill::streamed detection @@ -117,7 +117,7 @@ template constexpr bool is_copyable_v = is_copyable>::value; template -using are_copyable_t = typename std::conjunction>...>; +using are_copyable_t = std::conjunction>...>; template constexpr bool are_copyable_v = std::conjunction_v>...>; diff --git a/quill/include/quill/detail/misc/Utilities.h b/quill/include/quill/detail/misc/Utilities.h index 162b863a..0c7c794a 100644 --- a/quill/include/quill/detail/misc/Utilities.h +++ b/quill/include/quill/detail/misc/Utilities.h @@ -33,11 +33,11 @@ QUILL_NODISCARD constexpr bool is_pow_of_two(uint64_t number) noexcept /** * Round up to the next power of 2 - * @param number input + * @param n input * @return the next power of 2 */ template -QUILL_NODISCARD inline T next_power_of_2(T n) +QUILL_NODISCARD T next_power_of_2(T n) { constexpr T max_power_of_2 = (std::numeric_limits::max() >> 1) + 1; @@ -98,25 +98,13 @@ void safe_strncpy(std::array& destination, char const* source) noexcept template QUILL_NODISCARD QUILL_ATTRIBUTE_HOT constexpr T* align_pointer(void* pointer) noexcept { - if constexpr (alignment == 0) - { - return reinterpret_cast(pointer); - } - else - { - static_assert(is_pow_of_two(alignment), "alignment must be a power of two"); - return reinterpret_cast((reinterpret_cast(pointer) + (alignment - 1ul)) & ~(alignment - 1ul)); - } + static_assert(is_pow_of_two(alignment), "alignment must be a power of two"); + return reinterpret_cast((reinterpret_cast(pointer) + (alignment - 1ul)) & ~(alignment - 1ul)); } template QUILL_NODISCARD QUILL_ATTRIBUTE_HOT T* align_pointer(void* pointer, size_t alignment) noexcept { - if (alignment == 0) - { - return reinterpret_cast(pointer); - } - assert(is_pow_of_two(alignment) && "alignment must be a power of two"); return reinterpret_cast((reinterpret_cast(pointer) + (alignment - 1ul)) & ~(alignment - 1ul)); } diff --git a/quill/include/quill/detail/spsc_queue/UnboundedQueue.h b/quill/include/quill/detail/spsc_queue/UnboundedQueue.h index ebb75425..3c49621a 100644 --- a/quill/include/quill/detail/spsc_queue/UnboundedQueue.h +++ b/quill/include/quill/detail/spsc_queue/UnboundedQueue.h @@ -42,7 +42,8 @@ class UnboundedQueue { /** * Constructor - * @param capacity the capacity of the fixed buffer + * @param bounded_queue_capacity the capacity of the fixed buffer + * @param huge_pages enables huge pages */ explicit Node(uint32_t bounded_queue_capacity, bool huge_pages) : bounded_queue(bounded_queue_capacity, huge_pages) @@ -75,12 +76,12 @@ class UnboundedQueue ~UnboundedQueue() { // Get the current consumer node - Node* current_node = _consumer; + Node const* current_node = _consumer; // Look for extra nodes to delete while (current_node != nullptr) { - auto to_delete = current_node; + auto const to_delete = current_node; current_node = current_node->next; delete to_delete; } @@ -109,7 +110,7 @@ class UnboundedQueue } // bounded queue max power of 2 capacity since uint32_t type is used to hold the value 2147483648 bytes - constexpr uint64_t max_bounded_queue_capacity = + uint64_t constexpr max_bounded_queue_capacity = (std::numeric_limits::max() >> 1) + 1; if (QUILL_UNLIKELY(capacity > max_bounded_queue_capacity)) @@ -138,7 +139,7 @@ class UnboundedQueue _producer->bounded_queue.commit_write(); // We failed to reserve because the queue was full, create a new node with a new queue - auto next_node = new Node{static_cast(capacity), _huge_pages}; + auto const next_node = new Node{static_cast(capacity), _huge_pages}; // store the new node pointer as next in the current node _producer->next.store(next_node, std::memory_order_release); diff --git a/quill/include/quill/filters/FilterBase.h b/quill/include/quill/filters/FilterBase.h index 7f153d5e..cd48099d 100644 --- a/quill/include/quill/filters/FilterBase.h +++ b/quill/include/quill/filters/FilterBase.h @@ -24,7 +24,7 @@ class FilterBase * Constructor * @param filter_name unique filter name */ - explicit FilterBase(std::string filter_name) : _filter_name(std::move(filter_name)){}; + explicit FilterBase(std::string filter_name) : _filter_name(std::move(filter_name)){} /** * Destructor diff --git a/quill/include/quill/handlers/ConsoleHandler.h b/quill/include/quill/handlers/ConsoleHandler.h index b3858ecb..26df663f 100644 --- a/quill/include/quill/handlers/ConsoleHandler.h +++ b/quill/include/quill/handlers/ConsoleHandler.h @@ -187,7 +187,7 @@ class ConsoleColours class ConsoleHandler : public StreamHandler { public: - ConsoleHandler(std::string stream, FILE* file, ConsoleColours const& console_colours); + ConsoleHandler(std::string const& stream, FILE* file, ConsoleColours const& console_colours); ~ConsoleHandler() override = default; diff --git a/quill/include/quill/handlers/FileHandler.h b/quill/include/quill/handlers/FileHandler.h index ccfc063d..f819c37b 100644 --- a/quill/include/quill/handlers/FileHandler.h +++ b/quill/include/quill/handlers/FileHandler.h @@ -105,7 +105,7 @@ class FileHandler : public StreamHandler * @param file_event_notifier notifies on file events * @param do_fopen if false the file will not be opened */ - FileHandler(fs::path const& filename, FileHandlerConfig config, + FileHandler(fs::path const& filename, FileHandlerConfig const& config, FileEventNotifier file_event_notifier, bool do_fopen = true); ~FileHandler() override; diff --git a/quill/include/quill/handlers/Handler.h b/quill/include/quill/handlers/Handler.h index 111dabe3..ddfdeee9 100644 --- a/quill/include/quill/handlers/Handler.h +++ b/quill/include/quill/handlers/Handler.h @@ -61,7 +61,7 @@ class Handler * @note: Accessor for backend processing * @return reference to the pattern formatter of this handler */ - QUILL_ATTRIBUTE_HOT PatternFormatter& formatter() { return *_formatter; } + QUILL_ATTRIBUTE_HOT PatternFormatter& formatter() const { return *_formatter; } /** * Logs a formatted log message to the handler @@ -85,7 +85,7 @@ class Handler * @note It is recommended to avoid performing heavy operations within this function * as it may adversely affect the performance of the backend thread. */ - QUILL_ATTRIBUTE_HOT virtual void run_loop() noexcept {}; + QUILL_ATTRIBUTE_HOT virtual void run_loop() noexcept {} /** * Sets a log level filter on the handler. Log statements with higher or equal severity only will be logged diff --git a/quill/include/quill/handlers/JsonFileHandler.h b/quill/include/quill/handlers/JsonFileHandler.h index 7f296e9e..837e7d78 100644 --- a/quill/include/quill/handlers/JsonFileHandler.h +++ b/quill/include/quill/handlers/JsonFileHandler.h @@ -27,7 +27,7 @@ class JsonFileHandler : public FileHandler { // JsonFileHandler requires an empty pattern set_pattern(""); - }; + } ~JsonFileHandler() override = default; diff --git a/quill/include/quill/handlers/RotatingFileHandler.h b/quill/include/quill/handlers/RotatingFileHandler.h index 078b2568..55848fe9 100644 --- a/quill/include/quill/handlers/RotatingFileHandler.h +++ b/quill/include/quill/handlers/RotatingFileHandler.h @@ -62,7 +62,7 @@ class RotatingFileHandlerConfig : public FileHandlerConfig * @brief Sets the time of day for daily log file rotation. * When this option is set, the rotation frequency is automatically set to 'daily'. * By default, this option is disabled. - * @param time The time of day to perform the log file rotation. The value must be in the format "HH:MM". + * @param at_time The time of day to perform the log file rotation. The value must be in the format "HH:MM". */ QUILL_ATTRIBUTE_COLD void set_rotation_time_daily(std::string const& at_time); @@ -138,8 +138,9 @@ class RotatingFileHandler : public FileHandler * Creates a new instance of the RotatingFileHandler class. * * @param filename The base file name to be used for logs. - * @param mode The mode to open the file. * @param config The handler configuration. + * @param file_event_notifier file event notifier + * @param start_time start time */ RotatingFileHandler(fs::path const& filename, RotatingFileHandlerConfig const& config, FileEventNotifier file_event_notifier, diff --git a/quill/src/LogLevel.cpp b/quill/src/LogLevel.cpp index 0bae62aa..850d032b 100644 --- a/quill/src/LogLevel.cpp +++ b/quill/src/LogLevel.cpp @@ -17,7 +17,7 @@ std::string_view loglevel_to_string(LogLevel log_level) {"TRACE_L3", "TRACE_L2", "TRACE_L1", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "BACKTRACE", "NONE", "DYNAMIC"}}; - using log_lvl_t = std::underlying_type::type; + using log_lvl_t = std::underlying_type_t; auto const log_lvl = static_cast(log_level); if (QUILL_UNLIKELY(log_lvl > (log_levels_map.size() - 1))) @@ -37,7 +37,7 @@ std::string_view loglevel_to_string_id(LogLevel log_level) static constexpr std::array log_levels_map = { {"T3", "T2", "T1", "D", "I", "W", "E", "C", "BT", "N", "DN"}}; - using log_lvl_t = std::underlying_type::type; + using log_lvl_t = std::underlying_type_t; auto const log_lvl = static_cast(log_level); if (QUILL_UNLIKELY(log_lvl > (log_levels_map.size() - 1))) diff --git a/quill/src/PatternFormatter.cpp b/quill/src/PatternFormatter.cpp index a21a3717..c8568cad 100644 --- a/quill/src/PatternFormatter.cpp +++ b/quill/src/PatternFormatter.cpp @@ -75,6 +75,7 @@ constexpr void _store_named_args( * i: 9 order idx[i] is: 10 - empty * i: 10 order idx[i] is: 10 - empty * @tparam Args Args + * @param is_set_in_pattern is set in pattern * @param pattern pattern * @param args args * @return processed pattern @@ -98,11 +99,10 @@ QUILL_NODISCARD std::pair std::string _to_hex(T* buffer, size_t size) noexcept { - static constexpr char const hex_chars[] = "0123456789ABCDEF"; + static constexpr char hex_chars[] = "0123456789ABCDEF"; std::string hex_string; hex_string.reserve(3 * size); diff --git a/quill/src/detail/HandlerCollection.cpp b/quill/src/detail/HandlerCollection.cpp index 0614102b..b2425294 100644 --- a/quill/src/detail/HandlerCollection.cpp +++ b/quill/src/detail/HandlerCollection.cpp @@ -23,7 +23,7 @@ std::shared_ptr HandlerCollection::stderr_console_handler(std::string c } /***/ -std::shared_ptr HandlerCollection::get_handler(std::string const& handler_name) +std::shared_ptr HandlerCollection::get_handler(std::string const& handler_name) const { // Protect shared access std::lock_guard const lock{_mutex}; @@ -55,10 +55,9 @@ void HandlerCollection::subscribe_handler(std::shared_ptr const& handle { return false; } - else - { + return elem.get() == handler_to_insert.get(); - } + }); if (search == _active_handlers_collection.cend()) @@ -119,7 +118,7 @@ std::shared_ptr HandlerCollection::_create_console_handler(std::string if (handler_ptr) { - auto handler = reinterpret_cast(handler_ptr.get()); + auto const handler = reinterpret_cast(handler_ptr.get()); // if the handler with that name was already created check that the user didn't try to create it again passing a different file if (file == stdout && (handler->stream_handler_type() != StreamHandler::StreamHandlerType::Stdout)) @@ -128,13 +127,15 @@ std::shared_ptr HandlerCollection::_create_console_handler(std::string "Trying to insert an stdout handler again, but the handler already exists as a different " "file. Use an unique stream_handler name")); } - else if (file == stderr && (handler->stream_handler_type() != StreamHandler::StreamHandlerType::Stderr)) + + if (file == stderr && (handler->stream_handler_type() != StreamHandler::StreamHandlerType::Stderr)) { QUILL_THROW(QuillError( "Trying to insert an stderr handler again, but the handler already exists as a different " "file. Use an unique stream_handler name")); } - else if (handler->stream_handler_type() == StreamHandler::StreamHandlerType::File) + + if (handler->stream_handler_type() == StreamHandler::StreamHandlerType::File) { QUILL_THROW( QuillError("Trying to insert an stdout/stderr handler, but the handler already exists. " @@ -144,15 +145,13 @@ std::shared_ptr HandlerCollection::_create_console_handler(std::string return handler_ptr; } - else - { + // found a similar handler but with an out of date weak ptr, this is very rare to happen // as the backend logging thread is cleaning them // in that case allocate a new handler in that location handler_ptr = std::make_shared(stream, file, console_colours); search->second = handler_ptr; return handler_ptr; - } } // if first time add it diff --git a/quill/src/detail/LoggerCollection.cpp b/quill/src/detail/LoggerCollection.cpp index 19e3c4a6..eb4f3d4d 100644 --- a/quill/src/detail/LoggerCollection.cpp +++ b/quill/src/detail/LoggerCollection.cpp @@ -29,7 +29,7 @@ Logger* LoggerCollection::get_logger(char const* logger_name /* = nullptr */) co { if (logger_name) { - std::string logger_name_str{logger_name}; + std::string const logger_name_str{logger_name}; std::lock_guard const lock{_rmutex}; // Search for the logger @@ -40,12 +40,11 @@ Logger* LoggerCollection::get_logger(char const* logger_name /* = nullptr */) co QUILL_THROW(QuillError{std::string{"logger does not exist. name: "} + logger_name_str}); } - return (*search).second.get(); + return search->second.get(); } - else - { + return _root_logger; - } + } /***/ @@ -68,7 +67,7 @@ Logger* LoggerCollection::create_logger(std::string const& logger_name, Timestam TimestampClock* timestamp_clock) { // Get a copy of the root logger handlers - std::vector> handlers = _root_logger->_logger_details.handlers(); + std::vector> const handlers = _root_logger->_logger_details.handlers(); // Register the handlers, even if they already exist for (auto& handler : handlers) @@ -86,7 +85,7 @@ Logger* LoggerCollection::create_logger(std::string const& logger_name, Timestam auto const insert_result = _logger_name_map.emplace(std::string{logger_name}, std::move(logger)); // Return the inserted logger or the existing logger - return (*insert_result.first).second.get(); + return insert_result.first->second.get(); } /***/ @@ -105,7 +104,7 @@ Logger* LoggerCollection::create_logger(std::string const& logger_name, std::sha auto const insert_result = _logger_name_map.emplace(std::string{logger_name}, std::move(logger)); // Return the inserted logger or the existing logger - return (*insert_result.first).second.get(); + return insert_result.first->second.get(); } /***/ @@ -138,7 +137,7 @@ QUILL_NODISCARD Logger* LoggerCollection::create_logger(std::string const& logge auto const insert_result = _logger_name_map.emplace(std::string{logger_name}, std::move(logger)); // Return the inserted logger or the existing logger - return (*insert_result.first).second.get(); + return insert_result.first->second.get(); } /***/ @@ -149,14 +148,14 @@ void LoggerCollection::remove_logger(Logger* logger) } /***/ -void LoggerCollection::enable_console_colours() noexcept +void LoggerCollection::enable_console_colours() const noexcept { // Get the previous created default stdout handler - std::shared_ptr stdout_stream_handler = + std::shared_ptr const stdout_stream_handler = _handler_collection.stdout_console_handler("stdout"); assert(stdout_stream_handler && "stdout_stream_handler can not be nullptr"); - auto console_handler = reinterpret_cast(stdout_stream_handler.get()); + auto const console_handler = reinterpret_cast(stdout_stream_handler.get()); console_handler->enable_console_colours(); } @@ -174,7 +173,7 @@ void LoggerCollection::create_root_logger() if (_config.default_handlers.empty()) { // Add the default console handler to the root logger - std::shared_ptr stdout_stream_handler = + std::shared_ptr const stdout_stream_handler = _handler_collection.stdout_console_handler("stdout"); if (_config.enable_console_colours) @@ -201,7 +200,7 @@ void LoggerCollection::create_root_logger() if (_config.default_handlers.empty()) { // Add the default console handler to the root logger - std::shared_ptr stdout_stream_handler = + std::shared_ptr const stdout_stream_handler = _handler_collection.stdout_console_handler("stdout"); if (_config.enable_console_colours) @@ -213,7 +212,7 @@ void LoggerCollection::create_root_logger() _handler_collection.subscribe_handler(stdout_stream_handler); // get the pointer to the existing logger - auto search = _logger_name_map.find(_root_logger->_logger_details.name()); + auto const search = _logger_name_map.find(_root_logger->_logger_details.name()); assert(search != _logger_name_map.end() && "we must always find the previous root logger in the map"); @@ -242,7 +241,7 @@ void LoggerCollection::create_root_logger() } // get the pointer to the existing logger - auto search = _logger_name_map.find(_root_logger->_logger_details.name()); + auto const search = _logger_name_map.find(_root_logger->_logger_details.name()); assert(search != _logger_name_map.end() && "we must always find the previous root logger in the map"); diff --git a/quill/src/detail/SignalHandler.cpp b/quill/src/detail/SignalHandler.cpp index 02ffa294..4a6d1adc 100644 --- a/quill/src/detail/SignalHandler.cpp +++ b/quill/src/detail/SignalHandler.cpp @@ -114,9 +114,8 @@ BOOL WINAPI on_console_signal(DWORD signal) LONG WINAPI on_exception(EXCEPTION_POINTERS* exception_p) { // Get the id of this thread in the handler and make sure it is not the backend worker thread - uint32_t const tid = get_thread_id(); if ((LogManagerSingleton::instance().log_manager().backend_worker_thread_id() == 0) || - (tid == LogManagerSingleton::instance().log_manager().backend_worker_thread_id())) + (get_thread_id() == LogManagerSingleton::instance().log_manager().backend_worker_thread_id())) { // backend worker thread is not running or the handler is called in the backend worker thread } @@ -153,21 +152,19 @@ void on_signal(int32_t signal_number) } // Get the id of this thread in the handler and make sure it is not the backend worker thread - uint32_t const tid = get_thread_id(); if ((LogManagerSingleton::instance().log_manager().backend_worker_thread_id() == 0) || - (tid == LogManagerSingleton::instance().log_manager().backend_worker_thread_id())) + (get_thread_id() == LogManagerSingleton::instance().log_manager().backend_worker_thread_id())) { // backend worker thread is not running or the handler is called in the backend worker thread if (signal_number == SIGINT || signal_number == SIGTERM) { std::exit(EXIT_SUCCESS); } - else - { + // for other signals expect SIGINT and SIGTERM we re-raise std::signal(signal_number, SIG_DFL); std::raise(signal_number); - } + } else { @@ -180,8 +177,7 @@ void on_signal(int32_t signal_number) quill::flush(); std::exit(EXIT_SUCCESS); } - else - { + LOG_CRITICAL(quill::get_logger(), "Terminated unexpectedly because of signal: {}", signal_number); quill::flush(); @@ -189,7 +185,7 @@ void on_signal(int32_t signal_number) // Reset to the default signal handler and re-raise the signal std::signal(signal_number, SIG_DFL); std::raise(signal_number); - } + } } diff --git a/quill/src/detail/backend/BackendWorker.cpp b/quill/src/detail/backend/BackendWorker.cpp index 6800741c..c4752775 100644 --- a/quill/src/detail/backend/BackendWorker.cpp +++ b/quill/src/detail/backend/BackendWorker.cpp @@ -3,9 +3,7 @@ #include // for endl, basic_ostream, cerr, ostream #include // for vector -namespace quill -{ -namespace detail +namespace quill::detail { /***/ BackendWorker::BackendWorker(Config const& config, ThreadContextCollection& thread_context_collection, @@ -31,9 +29,7 @@ BackendWorker::~BackendWorker() void BackendWorker::stop() noexcept { // Stop the backend worker - auto const is_running = _is_running.exchange(false); - - if (!is_running) + if (!_is_running.exchange(false)) { // already stopped return; @@ -77,9 +73,8 @@ std::pair> BackendWorker::_process_structu while (open_bracket_pos != std::string::npos) { // found an open bracket - size_t const open_bracket_2_pos = fmt_template.find_first_of('{', open_bracket_pos + 1); - - if (open_bracket_2_pos != std::string::npos) + if (size_t const open_bracket_2_pos = fmt_template.find_first_of('{', open_bracket_pos + 1); + open_bracket_2_pos != std::string::npos) { // found another open bracket if ((open_bracket_2_pos - 1) == open_bracket_pos) @@ -94,9 +89,8 @@ std::pair> BackendWorker::_process_structu while (close_bracket_pos != std::string::npos) { // found closed bracket - size_t const close_bracket_2_pos = fmt_template.find_first_of('}', close_bracket_pos + 1); - - if (close_bracket_2_pos != std::string::npos) + if (size_t const close_bracket_2_pos = fmt_template.find_first_of('}', close_bracket_pos + 1); + close_bracket_2_pos != std::string::npos) { // found another open bracket if ((close_bracket_2_pos - 1) == close_bracket_pos) @@ -130,13 +124,12 @@ void BackendWorker::_resync_rdtsc_clock() if (_rdtsc_clock.load(std::memory_order_relaxed)) { // resync in rdtsc if we are not logging so that time_since_epoch() still works - auto const now = std::chrono::system_clock::now(); - if ((now - _last_rdtsc_resync) > _rdtsc_resync_interval) + + if (auto const now = std::chrono::system_clock::now(); (now - _last_rdtsc_resync) > _rdtsc_resync_interval) { _rdtsc_clock.load(std::memory_order_relaxed)->resync(2500); _last_rdtsc_resync = now; } } } -} // namespace detail -} // namespace quill \ No newline at end of file +} // namespace quill::detail \ No newline at end of file diff --git a/quill/src/detail/backend/BacktraceStorage.cpp b/quill/src/detail/backend/BacktraceStorage.cpp index 0ed6062b..f7459f04 100644 --- a/quill/src/detail/backend/BacktraceStorage.cpp +++ b/quill/src/detail/backend/BacktraceStorage.cpp @@ -10,7 +10,7 @@ namespace quill::detail /***/ void BacktraceStorage::store(TransitEvent transit_event) { - auto stored_records_it = _stored_records_map.find(transit_event.header.logger_details->name()); + auto const stored_records_it = _stored_records_map.find(transit_event.header.logger_details->name()); if (QUILL_UNLIKELY(stored_records_it == _stored_records_map.end())) { @@ -63,7 +63,7 @@ void BacktraceStorage::store(TransitEvent transit_event) void BacktraceStorage::process(std::string const& logger_name, std::function const& callback) { - auto stored_records_it = _stored_records_map.find(logger_name); + auto const stored_records_it = _stored_records_map.find(logger_name); if (QUILL_UNLIKELY(stored_records_it == _stored_records_map.end())) { diff --git a/quill/src/detail/backend/StringFromTime.cpp b/quill/src/detail/backend/StringFromTime.cpp index aa313c04..7ed13069 100644 --- a/quill/src/detail/backend/StringFromTime.cpp +++ b/quill/src/detail/backend/StringFromTime.cpp @@ -29,8 +29,7 @@ std::pair _split_timestamp_format_once(std::string& ti for (auto const& modifier : modifiers) { - auto const search = timestamp_format.find(modifier); - if (search != std::string::npos) + if (auto const search = timestamp_format.find(modifier); search != std::string::npos) { // Add the index and the modifier string to our map found_format_modifiers.emplace(std::make_pair(search, modifier)); @@ -145,8 +144,7 @@ std::string const& StringFromTime::format_timestamp(time_t timestamp) } else if (_time_zone == Timezone::GmtTime) { - _next_recalculation_timestamp = - next_noon_or_midnight_timestamp(timestamp + 1, _time_zone); + _next_recalculation_timestamp = next_noon_or_midnight_timestamp(timestamp + 1, _time_zone); } } diff --git a/quill/src/detail/backend/TimestampFormatter.cpp b/quill/src/detail/backend/TimestampFormatter.cpp index 8a3c0d3b..56a8a772 100644 --- a/quill/src/detail/backend/TimestampFormatter.cpp +++ b/quill/src/detail/backend/TimestampFormatter.cpp @@ -33,15 +33,16 @@ TimestampFormatter::TimestampFormatter(std::string const& timestamp_format_strin size_t specifier_begin{std::string::npos}; // look for all three special specifiers - size_t search_qms = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qms]); - if (search_qms != std::string::npos) + + if (size_t const search_qms = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qms]); + search_qms != std::string::npos) { _additional_format_specifier = AdditionalSpecifier::Qms; specifier_begin = search_qms; } - size_t search_qus = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qus]); - if (search_qus != std::string::npos) + if (size_t const search_qus = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qus]); + search_qus != std::string::npos) { if (specifier_begin != std::string::npos) { @@ -52,8 +53,8 @@ TimestampFormatter::TimestampFormatter(std::string const& timestamp_format_strin specifier_begin = search_qus; } - size_t search_qns = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qns]); - if (search_qns != std::string::npos) + if (size_t const search_qns = timestamp_format_string.find(specifier_name[AdditionalSpecifier::Qns]); + search_qns != std::string::npos) { if (specifier_begin != std::string::npos) { @@ -147,7 +148,7 @@ std::string_view TimestampFormatter::format_timestamp(std::chrono::nanoseconds t void TimestampFormatter::_append_fractional_seconds(uint32_t extracted_fractional_seconds) { // Format the seconds and add them - fmtquill::format_int extracted_ms_string{extracted_fractional_seconds}; + fmtquill::format_int const extracted_ms_string{extracted_fractional_seconds}; // _formatted_date.size() - extracted_ms_string.size() is where we want to begin placing the fractional seconds memcpy(&_formatted_date[_formatted_date.size() - extracted_ms_string.size()], diff --git a/quill/src/detail/backend/TransitEventBuffer.cpp b/quill/src/detail/backend/TransitEventBuffer.cpp index 469c1bfa..e1ea6425 100644 --- a/quill/src/detail/backend/TransitEventBuffer.cpp +++ b/quill/src/detail/backend/TransitEventBuffer.cpp @@ -87,12 +87,12 @@ UnboundedTransitEventBuffer::UnboundedTransitEventBuffer(uint32_t initial_transi /***/ UnboundedTransitEventBuffer::~UnboundedTransitEventBuffer() { - Node* reader_node = _reader; + Node const* reader_node = _reader; // Look for extra nodes to delete while (reader_node) { - auto to_delete = reader_node; + auto const to_delete = reader_node; reader_node = reader_node->next; delete to_delete; } @@ -134,7 +134,7 @@ TransitEvent* UnboundedTransitEventBuffer::back() noexcept { // buffer doesn't have enough space uint64_t capacity = static_cast(_writer->transit_buffer.capacity()) * 2ull; - constexpr uint64_t max_bounded_queue_capacity = + uint64_t constexpr max_bounded_queue_capacity = (std::numeric_limits::max() >> 1) + 1; if (QUILL_UNLIKELY(capacity > max_bounded_queue_capacity)) @@ -142,7 +142,7 @@ TransitEvent* UnboundedTransitEventBuffer::back() noexcept capacity = max_bounded_queue_capacity; } - auto new_node = new Node{static_cast(capacity)}; + auto const new_node = new Node{static_cast(capacity)}; _writer->next = new_node; _writer = _writer->next; write_event = _writer->transit_buffer.back(); @@ -159,7 +159,7 @@ void UnboundedTransitEventBuffer::push_back() noexcept { _writer->transit_buffer /***/ uint32_t UnboundedTransitEventBuffer::size() const noexcept { - Node* reader = _reader; + Node const* reader = _reader; uint32_t size = reader->transit_buffer.size(); diff --git a/quill/src/detail/misc/FileUtilities.cpp b/quill/src/detail/misc/FileUtilities.cpp index cc96a07b..0a7cd01c 100644 --- a/quill/src/detail/misc/FileUtilities.cpp +++ b/quill/src/detail/misc/FileUtilities.cpp @@ -105,7 +105,7 @@ fs::path append_date_time_to_filename(fs::path const& filename, bool with_time, std::string get_datetime_string(uint64_t timestamp_ns, Timezone timezone, bool with_time) { // convert to seconds - time_t time_now = static_cast(timestamp_ns / 1000000000); + auto const time_now = static_cast(timestamp_ns / 1000000000); tm now_tm; if (timezone == Timezone::GmtTime) diff --git a/quill/src/detail/misc/Os.cpp b/quill/src/detail/misc/Os.cpp index 895839b3..cd4d513f 100644 --- a/quill/src/detail/misc/Os.cpp +++ b/quill/src/detail/misc/Os.cpp @@ -68,7 +68,7 @@ size_t get_wide_string_encoding_size(std::wstring_view s) void wide_string_to_narrow(void* dest, size_t required_bytes, std::wstring_view s) { ::WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast(s.size()), - reinterpret_cast(dest), static_cast(required_bytes), NULL, NULL); + static_cast(dest), static_cast(required_bytes), nullptr, nullptr); } #endif @@ -139,7 +139,7 @@ ReturnT callRunTimeDynamicLinkedFunction(const std::string& dll_name, HINSTANCE const hinstLibrary = LoadLibraryA(dll_name.c_str()); #endif - if (QUILL_UNLIKELY(hinstLibrary == NULL)) + if (QUILL_UNLIKELY(hinstLibrary == nullptr)) { std::ostringstream error_msg; error_msg << "Failed to load library " @@ -149,7 +149,7 @@ ReturnT callRunTimeDynamicLinkedFunction(const std::string& dll_name, auto const callable = reinterpret_cast(GetProcAddress(hinstLibrary, function_name.c_str())); - if (QUILL_UNLIKELY(callable == NULL)) + if (QUILL_UNLIKELY(callable == nullptr)) { FreeLibrary(hinstLibrary); std::ostringstream error_msg; @@ -181,7 +181,7 @@ void set_cpu_affinity(uint16_t cpu_id) // setting cpu affinity on cygwin is not supported #elif defined(_WIN32) // core number starts from 0 - auto mask = (static_cast(1) << cpu_id); + auto const mask = (static_cast(1) << cpu_id); auto ret = SetThreadAffinityMask(GetCurrentThread(), mask); if (ret == 0) { diff --git a/quill/src/detail/misc/RdtscClock.cpp b/quill/src/detail/misc/RdtscClock.cpp index 27c21ee0..36b77e2a 100644 --- a/quill/src/detail/misc/RdtscClock.cpp +++ b/quill/src/detail/misc/RdtscClock.cpp @@ -67,12 +67,10 @@ RdtscClock::RdtscClock(std::chrono::nanoseconds resync_interval /* = std::chrono _ns_per_tick(RdtscTicks::instance().ns_per_tick()) { - bool res = resync(2500); - if (!res) + if (!resync(2500)) { // try to resync again with higher lag - res = resync(10000); - if (!res) + if (!resync(10000)) { std::cerr << "Failed to sync RdtscClock. Timestamps will be incorrect" << std::endl; } diff --git a/quill/src/handlers/ConsoleHandler.cpp b/quill/src/handlers/ConsoleHandler.cpp index 86f203fa..d54c5b41 100644 --- a/quill/src/handlers/ConsoleHandler.cpp +++ b/quill/src/handlers/ConsoleHandler.cpp @@ -56,7 +56,7 @@ void ConsoleColours::set_default_colours() noexcept /***/ void ConsoleColours::set_colour(LogLevel log_level, WORD colour) noexcept { - using log_lvl_t = std::underlying_type::type; + using log_lvl_t = std::underlying_type_t; auto const log_lvl = static_cast(log_level); _colours[log_lvl] = colour; _using_colours = true; @@ -71,7 +71,7 @@ bool ConsoleColours::using_colours() const noexcept { return _using_colours; } /***/ WORD ConsoleColours::colour_code(LogLevel log_level) const noexcept { - using log_lvl_t = std::underlying_type::type; + using log_lvl_t = std::underlying_type_t; auto const log_lvl = static_cast(log_level); return _colours[log_lvl]; } @@ -164,8 +164,8 @@ void ConsoleColours::_set_can_use_colours(FILE* file) noexcept #endif /***/ -ConsoleHandler::ConsoleHandler(std::string stream, FILE* file, ConsoleColours const& console_colours) - : StreamHandler{std::move(stream), file}, _console_colours(console_colours) +ConsoleHandler::ConsoleHandler(std::string const& stream, FILE* file, ConsoleColours const& console_colours) + : StreamHandler{stream, file}, _console_colours(console_colours) { // In this ctor we take a full copy of console_colours and in our instance we modify it _console_colours._set_can_use_colours(_file); @@ -243,7 +243,7 @@ void ConsoleHandler::enable_console_colours() noexcept { _console_colours.set_de ConsoleColours::WORD ConsoleHandler::_set_foreground_colour(ConsoleColours::WORD attributes) { CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info; - auto out_handle = reinterpret_cast(_get_osfhandle(_fileno(_file))); + auto const out_handle = reinterpret_cast(_get_osfhandle(_fileno(_file))); bool const screen_buffer_info = ::GetConsoleScreenBufferInfo(out_handle, &orig_buffer_info); if (QUILL_UNLIKELY(!screen_buffer_info)) diff --git a/quill/src/handlers/FileHandler.cpp b/quill/src/handlers/FileHandler.cpp index 2eed963a..7ae15c76 100644 --- a/quill/src/handlers/FileHandler.cpp +++ b/quill/src/handlers/FileHandler.cpp @@ -14,11 +14,13 @@ QUILL_NODISCARD quill::fs::path get_appended_filename(quill::fs::path const& fil { return filename; } - else if (append_to_filename == quill::FilenameAppend::StartDate) + + if (append_to_filename == quill::FilenameAppend::StartDate) { return quill::detail::append_date_time_to_filename(filename, false, timezone); } - else if (append_to_filename == quill::FilenameAppend::StartDateTime) + + if (append_to_filename == quill::FilenameAppend::StartDateTime) { return quill::detail::append_date_time_to_filename(filename, true, timezone); } @@ -53,7 +55,7 @@ void FileHandlerConfig::set_pattern(std::string const& log_pattern, } /***/ -FileHandler::FileHandler(fs::path const& filename, FileHandlerConfig config, +FileHandler::FileHandler(fs::path const& filename, FileHandlerConfig const& config, FileEventNotifier file_event_notifier, bool do_fopen /* = true */) : StreamHandler(get_appended_filename(filename, config.append_to_filename(), config.timezone()), nullptr, std::move(file_event_notifier)), diff --git a/quill/src/handlers/RotatingFileHandler.cpp b/quill/src/handlers/RotatingFileHandler.cpp index 7a6fec49..2e943e58 100644 --- a/quill/src/handlers/RotatingFileHandler.cpp +++ b/quill/src/handlers/RotatingFileHandler.cpp @@ -29,8 +29,7 @@ std::pair parse_at_time_format(std::st { QUILL_THROW(quill::QuillError{"Invalid at_time value format. The format should be `HH:MM`."}); } - else - { + for (auto const& parsed_token : tokens) { if (parsed_token.size() != 2) @@ -40,9 +39,8 @@ std::pair parse_at_time_format(std::st "should be two digits."}); } } - } - auto at_time_tp = + auto const at_time_tp = std::make_pair(std::chrono::hours{std::stoi(tokens[0])}, std::chrono::minutes{std::stoi(tokens[1])}); if ((at_time_tp.first > std::chrono::hours{23}) || (at_time_tp.second > std::chrono::minutes{59})) @@ -58,7 +56,7 @@ std::pair parse_at_time_format(std::st /***/ uint64_t calculate_initial_rotation_tp(uint64_t start_time_ns, quill::RotatingFileHandlerConfig const& config) { - time_t time_now = static_cast(start_time_ns) / 1000000000; + time_t const time_now = static_cast(start_time_ns) / 1000000000; tm date; // here we do this because of `at_time` that might have specified the time in UTC @@ -98,7 +96,7 @@ uint64_t calculate_initial_rotation_tp(uint64_t start_time_ns, quill::RotatingFi time_t const rotation_time = (config.timezone() == quill::Timezone::GmtTime) ? quill::detail::timegm(&date) : std::mktime(&date); - uint64_t rotation_time_seconds = (rotation_time > time_now) + uint64_t const rotation_time_seconds = (rotation_time > time_now) ? static_cast(rotation_time) : static_cast(rotation_time + std::chrono::seconds{std::chrono::hours{24}}.count()); @@ -114,12 +112,14 @@ uint64_t calculate_rotation_tp(uint64_t rotation_timestamp_ns, quill::RotatingFi static_cast( std::chrono::nanoseconds{std::chrono::minutes{config.rotation_interval()}}.count()); } - else if (config.rotation_frequency() == quill::RotatingFileHandlerConfig::RotationFrequency::Hourly) + + if (config.rotation_frequency() == quill::RotatingFileHandlerConfig::RotationFrequency::Hourly) { return rotation_timestamp_ns + static_cast(std::chrono::nanoseconds{std::chrono::hours{config.rotation_interval()}}.count()); } - else if (config.rotation_frequency() == quill::RotatingFileHandlerConfig::RotationFrequency::Daily) + + if (config.rotation_frequency() == quill::RotatingFileHandlerConfig::RotationFrequency::Daily) { return rotation_timestamp_ns + std::chrono::nanoseconds{std::chrono::hours{24}}.count(); } @@ -426,17 +426,15 @@ void RotatingFileHandler::_clean_and_recover_files(fs::path const& filename, std { // Find the first dot in the filename // stem will be something like `logfile.1` - size_t pos = entry.path().stem().string().find_last_of('.'); - if (pos != std::string::npos) + if (size_t const pos = entry.path().stem().string().find_last_of('.'); pos != std::string::npos) { // Get the today's date, we won't remove the files of the previous dates as they won't collide std::string const today_date = quill::detail::get_datetime_string(today_timestamp_ns, _config.timezone(), false); - std::string const index_or_date = - entry.path().stem().string().substr(pos + 1, entry.path().stem().string().length()); - - if ((index_or_date.length() >= 8) && (index_or_date == today_date)) + if (std::string const index_or_date = + entry.path().stem().string().substr(pos + 1, entry.path().stem().string().length()); + (index_or_date.length() >= 8) && (index_or_date == today_date)) { // assume it is a date, no need to find the index if (index_or_date == today_date) @@ -449,14 +447,12 @@ void RotatingFileHandler::_clean_and_recover_files(fs::path const& filename, std // assume it is an index // Find the second last dot to get the date std::string const filename_with_date = entry.path().filename().string().substr(0, pos); - size_t second_last = filename_with_date.find_last_of('.'); - if (second_last != std::string::npos) + if (size_t const second_last = filename_with_date.find_last_of('.'); second_last != std::string::npos) { - std::string const date_part = - filename_with_date.substr(second_last + 1, filename_with_date.length()); - - if (date_part == today_date) + if (std::string const date_part = + filename_with_date.substr(second_last + 1, filename_with_date.length()); + date_part == today_date) { fs::remove(entry); } @@ -488,8 +484,7 @@ void RotatingFileHandler::_clean_and_recover_files(fs::path const& filename, std std::string const extension = entry.path().extension().string(); // e.g. ".log" // stem will be something like `logfile.1` - size_t pos = entry.path().stem().string().find_last_of('.'); - if (pos != std::string::npos) + if (size_t const pos = entry.path().stem().string().find_last_of('.'); pos != std::string::npos) { if (_config.rotation_naming_scheme() == RotatingFileHandlerConfig::RotationNamingScheme::Index) { @@ -513,10 +508,9 @@ void RotatingFileHandler::_clean_and_recover_files(fs::path const& filename, std std::string const today_date = quill::detail::get_datetime_string(today_timestamp_ns, _config.timezone(), false); - std::string const index_or_date = - entry.path().stem().string().substr(pos + 1, entry.path().stem().string().length()); - - if ((index_or_date.length() >= 8) && (index_or_date == today_date)) + if (std::string const index_or_date = + entry.path().stem().string().substr(pos + 1, entry.path().stem().string().length()); + (index_or_date.length() >= 8) && (index_or_date == today_date)) { // assume it is a date, no need to find the index std::string const current_filename = entry.path().filename().string().substr(0, pos) + extension; @@ -530,14 +524,12 @@ void RotatingFileHandler::_clean_and_recover_files(fs::path const& filename, std // assume it is an index // Find the second last dot to get the date std::string const filename_with_date = entry.path().filename().string().substr(0, pos); - size_t second_last = filename_with_date.find_last_of('.'); - if (second_last != std::string::npos) + if (size_t const second_last = filename_with_date.find_last_of('.'); second_last != std::string::npos) { - std::string const date_part = - filename_with_date.substr(second_last + 1, filename_with_date.length()); - - if (date_part == today_date) + if (std::string const date_part = + filename_with_date.substr(second_last + 1, filename_with_date.length()); + date_part == today_date) { std::string const current_filename = filename_with_date.substr(0, second_last) + extension; fs::path current_file = entry.path().parent_path(); diff --git a/quill/src/handlers/StreamHandler.cpp b/quill/src/handlers/StreamHandler.cpp index b75ac7af..daf2df7d 100644 --- a/quill/src/handlers/StreamHandler.cpp +++ b/quill/src/handlers/StreamHandler.cpp @@ -97,14 +97,13 @@ StreamHandler::StreamHandlerType StreamHandler::stream_handler_type() const noex { return StreamHandler::StreamHandlerType::Stdout; } - else if (_file == stderr) + + if (_file == stderr) { return StreamHandler::StreamHandlerType::Stderr; } - else - { - return StreamHandler::StreamHandlerType::File; - } + + return StreamHandler::StreamHandlerType::File; } /***/ diff --git a/quill/test/BoundedQueueTest.cpp b/quill/test/BoundedQueueTest.cpp index 9c67b607..92c8eb45 100644 --- a/quill/test/BoundedQueueTest.cpp +++ b/quill/test/BoundedQueueTest.cpp @@ -59,7 +59,7 @@ TEST_CASE("read_write_buffer") TEST_CASE("bounded_queue_integer_overflow") { BoundedQueueImpl buffer{128, false, 0}; - size_t const iterations = static_cast(std::numeric_limits::max()) * 8ull; + size_t constexpr iterations = static_cast(std::numeric_limits::max()) * 8ull; for (size_t i = 0; i < iterations; ++i) { @@ -115,14 +115,14 @@ TEST_CASE("bounded_queue_read_write_multithreaded_plain_ints") { for (uint32_t i = 0; i < 8192; ++i) { - std::byte* read_buffer = buffer.prepare_read(); + std::byte const* read_buffer = buffer.prepare_read(); while (!read_buffer) { std::this_thread::sleep_for(std::chrono::microseconds{2}); read_buffer = buffer.prepare_read(); } - auto value = reinterpret_cast(read_buffer); + auto const value = reinterpret_cast(read_buffer); REQUIRE_EQ(*value, i); buffer.finish_read(sizeof(uint32_t)); buffer.commit_read(); diff --git a/quill/test/FileUtilitiesTest.cpp b/quill/test/FileUtilitiesTest.cpp index 51a87655..756648a2 100644 --- a/quill/test/FileUtilitiesTest.cpp +++ b/quill/test/FileUtilitiesTest.cpp @@ -123,10 +123,10 @@ TEST_CASE("extract_stem_and_extension") /***/ TEST_CASE("append_date_to_filename") { - std::chrono::system_clock::time_point ts = + std::chrono::system_clock::time_point const ts = std::chrono::system_clock::time_point{std::chrono::seconds{1583376945}}; - fs::path expected_fname = "logfile_20200305.log"; - fs::path base_fname = "logfile.log"; + fs::path const expected_fname = "logfile_20200305.log"; + fs::path const base_fname = "logfile.log"; REQUIRE_STREQ( append_date_time_to_filename(base_fname, false, quill::Timezone::GmtTime, ts).string().data(), diff --git a/quill/test/HandlerCollectionTest.cpp b/quill/test/HandlerCollectionTest.cpp index 2238bac5..2a50bf91 100644 --- a/quill/test/HandlerCollectionTest.cpp +++ b/quill/test/HandlerCollectionTest.cpp @@ -53,7 +53,7 @@ TEST_CASE("create_get") HandlerCollection hc; // Create a file handler - std::shared_ptr filehandler = hc.create_handler( + std::shared_ptr const filehandler = hc.create_handler( "create_get_file_handler", []() { @@ -64,7 +64,7 @@ TEST_CASE("create_get") FileEventNotifier{}); // Request the same file handler - std::shared_ptr filehandler_2 = hc.create_handler( + std::shared_ptr const filehandler_2 = hc.create_handler( "create_get_file_handler", []() { diff --git a/quill/test/LogTest.cpp b/quill/test/LogTest.cpp index 06d826b2..7142fced 100644 --- a/quill/test/LogTest.cpp +++ b/quill/test/LogTest.cpp @@ -112,9 +112,9 @@ TEST_CASE("default_logger_with_filehandler_1_empty_strings") Logger* default_logger = lm.logger_collection().get_logger(); std::string s = "adipiscing"; - std::string_view const begin_s{"begin_s"}; - std::string_view const end_s{"end_s"}; - std::string_view const empty_sv{}; + std::string_view constexpr begin_s{"begin_s"}; + std::string_view constexpr end_s{"end_s"}; + std::string_view constexpr empty_sv{}; std::string const empty_s{}; char const* empty_cs = ""; char empty_ca[] = ""; @@ -901,7 +901,7 @@ TEST_CASE("many_loggers_multiple_threads") [&lm, i]() { // Create a logger in this thread - std::string logger_name = "logger_" + std::to_string(i); + std::string const logger_name = "logger_" + std::to_string(i); Logger* logger = lm.create_logger(logger_name.data(), std::nullopt, std::nullopt); for (size_t j = 0; j < message_count; ++j) @@ -1582,7 +1582,7 @@ TEST_CASE("log_backtrace_manual_flush") class FileFilter1 : public quill::FilterBase { public: - FileFilter1() : quill::FilterBase("FileFilter1"){}; + FileFilter1() : quill::FilterBase("FileFilter1"){} QUILL_NODISCARD bool filter(char const*, std::chrono::nanoseconds, quill::MacroMetadata const& metadata, fmt_buffer_t const&) noexcept override @@ -1601,7 +1601,7 @@ class FileFilter1 : public quill::FilterBase class FileFilter2 : public quill::FilterBase { public: - FileFilter2() : quill::FilterBase("FileFilter2"){}; + FileFilter2() : quill::FilterBase("FileFilter2"){} QUILL_NODISCARD bool filter(char const*, std::chrono::nanoseconds, quill::MacroMetadata const& metadata, fmt_buffer_t const&) noexcept override diff --git a/quill/test/QuillLogNoTransitBufferTest.cpp b/quill/test/QuillLogNoTransitBufferTest.cpp index 919790e0..642cb3d1 100644 --- a/quill/test/QuillLogNoTransitBufferTest.cpp +++ b/quill/test/QuillLogNoTransitBufferTest.cpp @@ -45,7 +45,7 @@ void test_quill_log(char const* test_id, std::string const& filename, uint16_t n return cfg; }()); - std::string logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); + std::string const logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); quill::Logger* logger = quill::create_logger(logger_name.data(), std::move(log_from_one_thread_file)); for (uint32_t j = 0; j < number_of_messages; ++j) diff --git a/quill/test/QuillLogTest.cpp b/quill/test/QuillLogTest.cpp index 8c8f2005..daa57dd7 100644 --- a/quill/test/QuillLogTest.cpp +++ b/quill/test/QuillLogTest.cpp @@ -41,7 +41,7 @@ void test_quill_log(char const* test_id, std::string const& filename, uint16_t n return cfg; }()); - std::string logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); + std::string const logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); quill::Logger* logger = quill::create_logger(logger_name.data(), std::move(log_from_one_thread_file)); for (uint32_t j = 0; j < number_of_messages; ++j) @@ -137,7 +137,7 @@ class log_test_class /** * Use logger in normal function */ - void use_logger() { LOG_INFO(_logger, "Test message for test class non const"); } + void use_logger() const { LOG_INFO(_logger, "Test message for test class non const"); } private: quill::Logger* _logger{nullptr}; @@ -479,7 +479,7 @@ TEST_CASE("log_using_stderr") quill::flush(); - std::string results = quill::testing::GetCapturedStderr(); + std::string const results = quill::testing::GetCapturedStderr(); REQUIRE_EQ(results, "log_using_stderr - Hello log stderr (DOCTEST_ANON_FUNC_19)\n" @@ -682,7 +682,7 @@ TEST_CASE("log_enums_with_overloaded_insertion_operator") quill::flush(); - std::string results = quill::testing::GetCapturedStdout(); + std::string const results = quill::testing::GetCapturedStdout(); REQUIRE_EQ(results, "Test1,Test2,Test3,Test4,Test5,Test6\n"); } diff --git a/quill/test/QuillLogWakeUpBackendTest.cpp b/quill/test/QuillLogWakeUpBackendTest.cpp index 3e7f734c..acafad32 100644 --- a/quill/test/QuillLogWakeUpBackendTest.cpp +++ b/quill/test/QuillLogWakeUpBackendTest.cpp @@ -42,7 +42,7 @@ void test_quill_log(char const* test_id, std::string const& filename, uint16_t n return cfg; }()); - std::string logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); + std::string const logger_name = "logger_" + std::string{test_id} + "_" + std::to_string(i); quill::Logger* logger = quill::create_logger(logger_name, std::move(log_from_one_thread_file)); for (uint32_t j = 0; j < number_of_messages; ++j) diff --git a/quill/test/QuillStructuredLogTest.cpp b/quill/test/QuillStructuredLogTest.cpp index ce261a70..3fe40412 100644 --- a/quill/test/QuillStructuredLogTest.cpp +++ b/quill/test/QuillStructuredLogTest.cpp @@ -39,7 +39,7 @@ void test_quill_log(char const* test_id, std::string const& filename, std::strin for (int i = 0; i < number_of_threads; ++i) { threads.emplace_back( - [log_from_one_thread_file, filename, filename_s, number_of_messages, test_id, i]() mutable + [log_from_one_thread_file, filename_s, number_of_messages, test_id, i]() mutable { // Also use preallocate quill::preallocate(); @@ -54,7 +54,7 @@ void test_quill_log(char const* test_id, std::string const& filename, std::strin return cfg; }()); - std::string logger_name = "jlogger_" + std::string{test_id} + "_" + std::to_string(i); + std::string const logger_name = "jlogger_" + std::string{test_id} + "_" + std::to_string(i); quill::Logger* logger = quill::create_logger( logger_name, std::vector>{std::move(log_from_one_thread_file), diff --git a/quill/test/RdtscClockTest.cpp b/quill/test/RdtscClockTest.cpp index 6e962eb9..7f629a4b 100644 --- a/quill/test/RdtscClockTest.cpp +++ b/quill/test/RdtscClockTest.cpp @@ -9,7 +9,7 @@ TEST_SUITE_BEGIN("RdtscClock"); void check_wall_time_now(quill::detail::RdtscClock const& tsc_clock) { - std::chrono::milliseconds const offset{10}; + std::chrono::milliseconds constexpr offset{10}; auto const wall_time_chrono = std::chrono::system_clock::now().time_since_epoch(); auto const wall_time_tsc = std::chrono::nanoseconds{tsc_clock.time_since_epoch(quill::detail::rdtsc())}; @@ -27,7 +27,7 @@ void check_wall_time_now(quill::detail::RdtscClock const& tsc_clock) TEST_CASE("wall_time") { - quill::detail::RdtscClock tsc_clock{std::chrono::milliseconds{700}}; + quill::detail::RdtscClock const tsc_clock{std::chrono::milliseconds{700}}; constexpr size_t num_reps{10}; diff --git a/quill/test/TimestampFormatterTest.cpp b/quill/test/TimestampFormatterTest.cpp index 30fda695..dcf84318 100644 --- a/quill/test/TimestampFormatterTest.cpp +++ b/quill/test/TimestampFormatterTest.cpp @@ -25,7 +25,7 @@ TEST_CASE("simple_format_string") /***/ TEST_CASE("format_string_no_additional_specifier") { - const std::chrono::nanoseconds timestamp{1587161887987654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887987654321}; // simple formats without any ms/us/ns specifiers { @@ -56,7 +56,7 @@ TEST_CASE("format_string_with_millisecond_precision") { // simple { - const std::chrono::nanoseconds timestamp{1587161887987654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887987654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qms", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -65,7 +65,7 @@ TEST_CASE("format_string_with_millisecond_precision") // with double formatting { - const std::chrono::nanoseconds timestamp{1587161887803654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887803654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qms %D", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -74,7 +74,7 @@ TEST_CASE("format_string_with_millisecond_precision") // with double formatting 2 { - const std::chrono::nanoseconds timestamp{1587161887023654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887023654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qms-%G", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -83,7 +83,7 @@ TEST_CASE("format_string_with_millisecond_precision") // with zeros { - const std::chrono::nanoseconds timestamp{1587161887009654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887009654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qms", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -96,7 +96,7 @@ TEST_CASE("format_string_with_microsecond_precision") { // simple { - const std::chrono::nanoseconds timestamp{1587161887987654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887987654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qus", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -105,7 +105,7 @@ TEST_CASE("format_string_with_microsecond_precision") // with double formatting { - const std::chrono::nanoseconds timestamp{1587161887803654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887803654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qus %D", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -114,7 +114,7 @@ TEST_CASE("format_string_with_microsecond_precision") // with double formatting 2 { - const std::chrono::nanoseconds timestamp{1587161887010654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887010654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qus-%G", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -123,7 +123,7 @@ TEST_CASE("format_string_with_microsecond_precision") // with zeros { - const std::chrono::nanoseconds timestamp{1587161887000004321}; + std::chrono::nanoseconds constexpr timestamp{1587161887000004321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qus", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -136,7 +136,7 @@ TEST_CASE("format_string_with_nanosecond_precision") { // simple { - const std::chrono::nanoseconds timestamp{1587161887987654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887987654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qns", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -145,7 +145,7 @@ TEST_CASE("format_string_with_nanosecond_precision") // with double formatting { - const std::chrono::nanoseconds timestamp{1587161887803654320}; + std::chrono::nanoseconds constexpr timestamp{1587161887803654320}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qns %D", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -154,7 +154,7 @@ TEST_CASE("format_string_with_nanosecond_precision") // with double formatting 2 { - const std::chrono::nanoseconds timestamp{1587161887000654321}; + std::chrono::nanoseconds constexpr timestamp{1587161887000654321}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qns-%G", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -163,7 +163,7 @@ TEST_CASE("format_string_with_nanosecond_precision") // with zeros { - const std::chrono::nanoseconds timestamp{1587161887000000009}; + std::chrono::nanoseconds constexpr timestamp{1587161887000000009}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qns", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); @@ -172,7 +172,7 @@ TEST_CASE("format_string_with_nanosecond_precision") // with max { - const std::chrono::nanoseconds timestamp{1587161887999999999}; + std::chrono::nanoseconds constexpr timestamp{1587161887999999999}; TimestampFormatter ts_formatter{"%H:%M:%S.%Qns", quill::Timezone::GmtTime}; auto const& result = ts_formatter.format_timestamp(timestamp); diff --git a/quill/test/TransitEventBufferTest.cpp b/quill/test/TransitEventBufferTest.cpp index 23f9969f..2022a030 100644 --- a/quill/test/TransitEventBufferTest.cpp +++ b/quill/test/TransitEventBufferTest.cpp @@ -107,7 +107,7 @@ TEST_CASE("transit_event_bounded_buffer") TEST_CASE("transit_event_bounded_buffer_integer_overflow") { BoundedTransitEventBufferImpl bte{128}; - size_t const iterations = static_cast(std::numeric_limits::max()) * 8ull; + size_t constexpr iterations = static_cast(std::numeric_limits::max()) * 8ull; for (size_t i = 0; i < iterations; ++i) { diff --git a/quill/test/TypeTraitsCopyableTest.cpp b/quill/test/TypeTraitsCopyableTest.cpp index f80bfbad..5f3ca444 100644 --- a/quill/test/TypeTraitsCopyableTest.cpp +++ b/quill/test/TypeTraitsCopyableTest.cpp @@ -28,7 +28,7 @@ struct TaggedNonTrivial public: using copy_loggable = std::true_type; - explicit TaggedNonTrivial(std::string x) : x(std::move(x)){}; + explicit TaggedNonTrivial(std::string x) : x(std::move(x)){} private: std::string x; @@ -37,7 +37,7 @@ struct TaggedNonTrivial struct NonTrivial { public: - explicit NonTrivial(std::string x) : x(std::move(x)){}; + explicit NonTrivial(std::string x) : x(std::move(x)){} private: std::string x; diff --git a/quill/test/UnboundedQueueTest.cpp b/quill/test/UnboundedQueueTest.cpp index 6d915340..c89647f4 100644 --- a/quill/test/UnboundedQueueTest.cpp +++ b/quill/test/UnboundedQueueTest.cpp @@ -53,7 +53,7 @@ TEST_CASE("unbounded_queue_read_write_multithreaded_plain_ints") std::tie(read_buffer, alloc) = buffer.prepare_read(); } - auto value = reinterpret_cast(read_buffer); + auto const value = reinterpret_cast(read_buffer); REQUIRE_EQ(*value, i); buffer.finish_read(sizeof(uint32_t)); buffer.commit_read(); diff --git a/quill/test/UtilitiesTest.cpp b/quill/test/UtilitiesTest.cpp index 49877fae..cbf490c2 100644 --- a/quill/test/UtilitiesTest.cpp +++ b/quill/test/UtilitiesTest.cpp @@ -20,16 +20,16 @@ TEST_CASE("next_noon_or_midnight_timestamp") { // Noon utc - time_t timestamp{1599033200}; - time_t expected_timestamp{1599048000}; + time_t constexpr timestamp{1599033200}; + time_t constexpr expected_timestamp{1599048000}; time_t const res = next_noon_or_midnight_timestamp(timestamp, Timezone::GmtTime); REQUIRE_EQ(res, expected_timestamp); } { // Midnight utc - time_t timestamp{1599079200}; - time_t expected_timestamp{1599091200}; + time_t constexpr timestamp{1599079200}; + time_t constexpr expected_timestamp{1599091200}; time_t const res = next_noon_or_midnight_timestamp(timestamp, Timezone::GmtTime); REQUIRE_EQ(res, expected_timestamp); } @@ -38,16 +38,16 @@ TEST_CASE("next_noon_or_midnight_timestamp") /***/ TEST_CASE("nearest_hour_timestamp") { - time_t const timestamp = 1599473669; - time_t const expected_timestamp = 1599472800; + time_t constexpr timestamp = 1599473669; + time_t constexpr expected_timestamp = 1599472800; REQUIRE_EQ(nearest_hour_timestamp(timestamp), expected_timestamp); } /***/ TEST_CASE("next_hour_timestamp") { - time_t const timestamp = 1599473669; - time_t const expected_timestamp = 1599476400; + time_t constexpr timestamp = 1599473669; + time_t constexpr expected_timestamp = 1599476400; REQUIRE_EQ(next_hour_timestamp(timestamp), expected_timestamp); } diff --git a/quill/test/misc/TestUtilities.cpp b/quill/test/misc/TestUtilities.cpp index 7378d060..b4a2ec37 100644 --- a/quill/test/misc/TestUtilities.cpp +++ b/quill/test/misc/TestUtilities.cpp @@ -39,9 +39,9 @@ std::vector wfile_contents(fs::path const& filename) // Search a vector for the given string bool file_contains(std::vector const& file_vector, std::string const& search_string) { - auto const search = std::find_if(file_vector.cbegin(), file_vector.cend(), - [&search_string](std::string const& elem) - { return elem.find(search_string) != std::string::npos; }); + auto const search = + std::find_if(file_vector.cbegin(), file_vector.cend(), [&search_string](std::string const& elem) + { return elem.find(search_string) != std::string::npos; }); bool const success = search != file_vector.cend(); @@ -60,8 +60,7 @@ bool file_contains(std::vector const& file_vector, std::string cons void create_file(fs::path const& filename, std::string const& text) { - std::ofstream file(filename); - if (file.is_open()) + if (std::ofstream file(filename); file.is_open()) { if (!text.empty()) {