You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2KB

  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. // Fast asynchronous logger.
  5. // Uses pre allocated queue.
  6. // Creates a single back thread to pop messages from the queue and log them.
  7. //
  8. // Upon each log write the logger:
  9. // 1. Checks if its log level is enough to log the message
  10. // 2. Push a new copy of the message to a queue (or block the caller until
  11. // space is available in the queue)
  12. // Upon destruction, logs all remaining messages in the queue before
  13. // destructing..
  14. #include "spdlog/logger.h"
  15. namespace spdlog {
  16. // Async overflow policy - block by default.
  17. enum class async_overflow_policy
  18. {
  19. block, // Block until message can be enqueued
  20. overrun_oldest // Discard oldest message in the queue if full when trying to
  21. // add new item.
  22. };
  23. namespace details {
  24. class thread_pool;
  25. }
  26. class async_logger final : public std::enable_shared_from_this<async_logger>, public logger
  27. {
  28. friend class details::thread_pool;
  29. public:
  30. template<typename It>
  31. async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp,
  32. async_overflow_policy overflow_policy = async_overflow_policy::block)
  33. : logger(std::move(logger_name), begin, end)
  34. , thread_pool_(std::move(tp))
  35. , overflow_policy_(overflow_policy)
  36. {}
  37. async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp,
  38. async_overflow_policy overflow_policy = async_overflow_policy::block);
  39. async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,
  40. async_overflow_policy overflow_policy = async_overflow_policy::block);
  41. std::shared_ptr<logger> clone(std::string new_name) override;
  42. protected:
  43. void sink_it_(const details::log_msg &msg) override;
  44. void flush_() override;
  45. void backend_sink_it_(const details::log_msg &incoming_log_msg);
  46. void backend_flush_();
  47. private:
  48. std::weak_ptr<details::thread_pool> thread_pool_;
  49. async_overflow_policy overflow_policy_;
  50. };
  51. } // namespace spdlog
  52. #ifdef SPDLOG_HEADER_ONLY
  53. #include "async_logger-inl.h"
  54. #endif