log_writer.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2019 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef TEST_LOGGING_LOG_WRITER_H_
  11. #define TEST_LOGGING_LOG_WRITER_H_
  12. #include <stdarg.h>
  13. #include <memory>
  14. #include <string>
  15. #include <utility>
  16. #include "api/rtc_event_log_output.h"
  17. #include "rtc_base/strings/string_builder.h"
  18. namespace webrtc {
  19. template <class... Args>
  20. inline void LogWriteFormat(RtcEventLogOutput* out_, const char* fmt, ...) {
  21. va_list args, copy;
  22. va_start(args, fmt);
  23. va_copy(copy, args);
  24. const int predicted_length = std::vsnprintf(nullptr, 0, fmt, copy);
  25. va_end(copy);
  26. RTC_DCHECK_GE(predicted_length, 0);
  27. std::string out_str(predicted_length, '\0');
  28. if (predicted_length > 0) {
  29. // Pass "+ 1" to vsnprintf to include space for the '\0'.
  30. const int actual_length =
  31. std::vsnprintf(&out_str.front(), predicted_length + 1, fmt, args);
  32. RTC_DCHECK_GE(actual_length, 0);
  33. }
  34. va_end(args);
  35. out_->Write(out_str);
  36. }
  37. class LogWriterFactoryInterface {
  38. public:
  39. virtual std::unique_ptr<RtcEventLogOutput> Create(std::string filename) = 0;
  40. virtual ~LogWriterFactoryInterface() = default;
  41. };
  42. class LogWriterFactoryAddPrefix : public LogWriterFactoryInterface {
  43. public:
  44. LogWriterFactoryAddPrefix(LogWriterFactoryInterface* base,
  45. std::string prefix);
  46. std::unique_ptr<RtcEventLogOutput> Create(std::string filename) override;
  47. private:
  48. LogWriterFactoryInterface* const base_factory_;
  49. const std::string prefix_;
  50. };
  51. } // namespace webrtc
  52. #endif // TEST_LOGGING_LOG_WRITER_H_