log_buffer.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef ASH_QUICK_PAIR_COMMON_LOG_BUFFER_H_
  5. #define ASH_QUICK_PAIR_COMMON_LOG_BUFFER_H_
  6. #include <stddef.h>
  7. #include <list>
  8. #include "base/component_export.h"
  9. #include "base/logging.h"
  10. #include "base/observer_list.h"
  11. #include "base/time/time.h"
  12. namespace ash {
  13. namespace quick_pair {
  14. // Contains logs specific to the Quick Pair implementations (e.g. Fast Pair).
  15. // This buffer has a maximum size and will discard entries in FIFO order. Call
  16. // LogBuffer::GetInstance() to get the global LogBuffer instance.
  17. class COMPONENT_EXPORT(QUICK_PAIR_COMMON) LogBuffer {
  18. public:
  19. // Represents a single log entry in the log buffer.
  20. struct LogMessage {
  21. const std::string text;
  22. const base::Time time;
  23. const std::string file;
  24. const int line;
  25. const logging::LogSeverity severity;
  26. LogMessage(const std::string& text,
  27. const base::Time& time,
  28. const std::string& file,
  29. int line,
  30. logging::LogSeverity severity);
  31. };
  32. class Observer {
  33. public:
  34. // Called when a new message is added to the log buffer.
  35. virtual void OnLogMessageAdded(const LogMessage& log_message) = 0;
  36. // Called when all messages in the log buffer are cleared.
  37. virtual void OnLogBufferCleared() = 0;
  38. };
  39. LogBuffer();
  40. LogBuffer(const LogBuffer&) = delete;
  41. LogBuffer& operator=(const LogBuffer&) = delete;
  42. ~LogBuffer();
  43. // Returns the global instance.
  44. static LogBuffer* GetInstance();
  45. // Adds and removes log buffer observers.
  46. void AddObserver(Observer* observer);
  47. void RemoveObserver(Observer* observer);
  48. // Adds a new log message to the buffer. If the number of log messages exceeds
  49. // the maximum, then the earliest added log will be removed.
  50. void AddLogMessage(const LogMessage& log_message);
  51. // Clears all logs in the buffer.
  52. void Clear();
  53. // Returns the maximum number of logs that can be stored.
  54. size_t MaxBufferSize() const;
  55. // Returns the list logs in the buffer, sorted chronologically.
  56. const std::list<LogMessage>* logs() { return &log_messages_; }
  57. private:
  58. // The messages currently in the buffer.
  59. std::list<LogMessage> log_messages_;
  60. // List of observers.
  61. base::ObserverList<Observer>::Unchecked observers_;
  62. };
  63. } // namespace quick_pair
  64. } // namespace ash
  65. #endif // ASH_QUICK_PAIR_COMMON_LOG_BUFFER_H_