async_logger.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. block, // Block until message can be enqueued
  19. overrun_oldest, // Discard oldest message in the queue if full when trying to
  20. // add new item.
  21. discard_new // Discard new message if the queue is full when trying to add new item.
  22. };
  23. namespace details {
  24. class thread_pool;
  25. }
  26. class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>,
  27. public logger {
  28. friend class details::thread_pool;
  29. public:
  30. template <typename It>
  31. async_logger(std::string logger_name,
  32. It begin,
  33. It end,
  34. std::weak_ptr<details::thread_pool> tp,
  35. async_overflow_policy overflow_policy = async_overflow_policy::block)
  36. : logger(std::move(logger_name), begin, end),
  37. thread_pool_(std::move(tp)),
  38. overflow_policy_(overflow_policy) {}
  39. async_logger(std::string logger_name,
  40. sinks_init_list sinks_list,
  41. std::weak_ptr<details::thread_pool> tp,
  42. async_overflow_policy overflow_policy = async_overflow_policy::block);
  43. async_logger(std::string logger_name,
  44. sink_ptr single_sink,
  45. std::weak_ptr<details::thread_pool> tp,
  46. async_overflow_policy overflow_policy = async_overflow_policy::block);
  47. std::shared_ptr<logger> clone(std::string new_name) override;
  48. protected:
  49. void sink_it_(const details::log_msg &msg) override;
  50. void flush_() override;
  51. void backend_sink_it_(const details::log_msg &incoming_log_msg);
  52. void backend_flush_();
  53. private:
  54. std::weak_ptr<details::thread_pool> thread_pool_;
  55. async_overflow_policy overflow_policy_;
  56. };
  57. } // namespace spdlog
  58. #ifdef SPDLOG_HEADER_ONLY
  59. #include "async_logger-inl.h"
  60. #endif