async_logger-inl.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #ifndef SPDLOG_HEADER_ONLY
  5. # include <spdlog/async_logger.h>
  6. #endif
  7. #include <spdlog/sinks/sink.h>
  8. #include <spdlog/details/thread_pool.h>
  9. #include <memory>
  10. #include <string>
  11. SPDLOG_INLINE spdlog::async_logger::async_logger(
  12. std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
  13. : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy)
  14. {}
  15. SPDLOG_INLINE spdlog::async_logger::async_logger(
  16. std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
  17. : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy)
  18. {}
  19. // send the log message to the thread pool
  20. SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg){
  21. SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
  22. }
  23. else
  24. {
  25. throw_spdlog_ex("async log: thread pool doesn't exist anymore");
  26. }
  27. }
  28. SPDLOG_LOGGER_CATCH(msg.source)
  29. }
  30. // send flush request to the thread pool
  31. SPDLOG_INLINE void spdlog::async_logger::flush_(){
  32. SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){pool_ptr->post_flush(shared_from_this(), overflow_policy_);
  33. }
  34. else
  35. {
  36. throw_spdlog_ex("async flush: thread pool doesn't exist anymore");
  37. }
  38. }
  39. SPDLOG_LOGGER_CATCH(source_loc())
  40. }
  41. //
  42. // backend functions - called from the thread pool to do the actual job
  43. //
  44. SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg &msg)
  45. {
  46. for (auto &sink : sinks_)
  47. {
  48. if (sink->should_log(msg.level))
  49. {
  50. SPDLOG_TRY
  51. {
  52. sink->log(msg);
  53. }
  54. SPDLOG_LOGGER_CATCH(msg.source)
  55. }
  56. }
  57. if (should_flush_(msg))
  58. {
  59. backend_flush_();
  60. }
  61. }
  62. SPDLOG_INLINE void spdlog::async_logger::backend_flush_()
  63. {
  64. for (auto &sink : sinks_)
  65. {
  66. SPDLOG_TRY
  67. {
  68. sink->flush();
  69. }
  70. SPDLOG_LOGGER_CATCH(source_loc())
  71. }
  72. }
  73. SPDLOG_INLINE std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name)
  74. {
  75. auto cloned = std::make_shared<spdlog::async_logger>(*this);
  76. cloned->name_ = std::move(new_name);
  77. return cloned;
  78. }