tls_backend.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <library/cpp/logger/backend.h>
  3. #include <util/generic/ptr.h>
  4. #include <utility>
  5. namespace NYql {
  6. namespace NLog {
  7. /**
  8. * @brief Dispatches all invocations to default logger backend configured
  9. * for current thread. Must be used in conjunction with
  10. * SetLogBackendForCurrentThread() function or TScopedBackend class.
  11. */
  12. class TTlsLogBackend: public TLogBackend {
  13. public:
  14. TTlsLogBackend(TAutoPtr<TLogBackend> defaultBackend)
  15. : DefaultBackend_(defaultBackend)
  16. {
  17. Y_DEBUG_ABORT_UNLESS(DefaultBackend_, "default backend is not set");
  18. }
  19. void WriteData(const TLogRecord& rec) override;
  20. void ReopenLog() override;
  21. ELogPriority FiltrationLevel() const override;
  22. private:
  23. TAutoPtr<TLogBackend> DefaultBackend_;
  24. };
  25. /**
  26. * @brief Sets given backend as default for current thread. Must be used in
  27. * conjunction with TTlsLogBackend.
  28. *
  29. * @param backend - pointer to logger backend
  30. * @return previous default logger backend
  31. */
  32. TLogBackend* SetLogBackendForCurrentThread(TLogBackend* backend);
  33. /**
  34. * @brief Sets itself as default for current thread on instantiation
  35. * and restores previous one on destruction. Must be used in
  36. * conjunction with TTlsLogBackend.
  37. */
  38. template <typename TBackend>
  39. class TScopedBackend: public TBackend {
  40. public:
  41. template <typename... TArgs>
  42. TScopedBackend(TArgs&&... args)
  43. : TBackend(std::forward<TArgs>(args)...)
  44. , PrevBacked_(SetLogBackendForCurrentThread(this))
  45. {
  46. }
  47. ~TScopedBackend() {
  48. SetLogBackendForCurrentThread(PrevBacked_);
  49. }
  50. private:
  51. TLogBackend* PrevBacked_;
  52. };
  53. } // namspace NLog
  54. } // namspace NYql