exception_log.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* exception_log.h - exception logging classes
  2. * Copyright (C) 2017 caryoscelus
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #ifndef CORE_LOG_EXCEPTION_LOG_H_E986976B_AEA1_5C3F_B5B0_FBD290939F9D
  18. #define CORE_LOG_EXCEPTION_LOG_H_E986976B_AEA1_5C3F_B5B0_FBD290939F9D
  19. #include <exception>
  20. #include <core/std/memory.h>
  21. namespace rainynite::core {
  22. /**
  23. * Empty interface for all exception sources
  24. */
  25. class ExceptionSource {
  26. public:
  27. virtual ~ExceptionSource() = default;
  28. };
  29. /**
  30. * Exception logger interface
  31. */
  32. class ExceptionLogger {
  33. public:
  34. virtual ~ExceptionLogger() = default;
  35. /// Write exception ex (caused by source) to log
  36. virtual void log_exception(weak_ptr<ExceptionSource const> source, std::exception const& ex) const noexcept = 0;
  37. };
  38. /**
  39. * Proxy exception logger
  40. */
  41. class HasExceptionLogger :
  42. public ExceptionLogger,
  43. public ExceptionSource,
  44. public enable_shared_from_this<HasExceptionLogger>
  45. {
  46. public:
  47. explicit HasExceptionLogger(shared_ptr<ExceptionLogger> logger_ = nullptr) :
  48. logger(logger_)
  49. {}
  50. void set_logger(shared_ptr<ExceptionLogger> logger_) {
  51. logger = logger_;
  52. }
  53. void log_exception_from_this(std::exception const& ex) const {
  54. log_exception(dynamic_pointer_cast<ExceptionSource const>(shared_from_this()), ex);
  55. }
  56. void log_exception(weak_ptr<ExceptionSource const> source, std::exception const& ex) const noexcept override {
  57. if (logger)
  58. logger->log_exception(source, ex);
  59. }
  60. private:
  61. shared_ptr<ExceptionLogger> logger;
  62. };
  63. } // namespace rainynite::core
  64. #endif