async_logger-inl.h 2.8 KB

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