blob: be1806b00bb3e9774e400b69d3e6f4f8b9be7819 [file] [log] [blame]
Artem Senicheve8837d52020-06-07 11:59:04 +03001// SPDX-License-Identifier: Apache-2.0
2// Copyright (C) 2020 YADRO
3
4#pragma once
5
6#include <ctime>
7#include <functional>
8#include <list>
9#include <string>
10
11/**
12 * @class LogBuffer
13 * @brief Container with automatic log message rotation.
14 */
15class LogBuffer
16{
17 public:
18 /**
19 * @struct Message
20 * @brief Single log message.
21 */
22 struct Message
23 {
24 /** @brief Message creation time. */
25 time_t timeStamp;
26 /** @brief Text of the message. */
27 std::string text;
28 };
29
30 using container_t = std::list<Message>;
31
32 /**
33 * @brief Constructor.
34 *
35 * @param[in] maxSize max number of messages that can be stored
36 * @param[in] maxTime max age of messages that can be stored, in minutes
37 */
38 LogBuffer(size_t maxSize, size_t maxTime);
39
Nan Zhou042b5ba2021-06-18 09:32:45 -070040 virtual ~LogBuffer() = default;
41
Artem Senicheve8837d52020-06-07 11:59:04 +030042 /**
43 * @brief Add raw data from host's console output.
44 *
45 * @param[in] data pointer to raw data buffer
46 * @param[in] sz size of the buffer in bytes
47 */
Nan Zhou042b5ba2021-06-18 09:32:45 -070048 virtual void append(const char* data, size_t sz);
Artem Senicheve8837d52020-06-07 11:59:04 +030049
50 /**
51 * @brief Set handler called if buffer is full.
52 *
53 * @param[in] cb callback function
54 */
Nan Zhou042b5ba2021-06-18 09:32:45 -070055 virtual void setFullHandler(std::function<void()> cb);
Artem Senicheve8837d52020-06-07 11:59:04 +030056
57 /** @brief Clear (reset) container. */
Nan Zhou042b5ba2021-06-18 09:32:45 -070058 virtual void clear();
Artem Senicheve8837d52020-06-07 11:59:04 +030059 /** @brief Check container for empty. */
Nan Zhou042b5ba2021-06-18 09:32:45 -070060 virtual bool empty() const;
Artem Senicheve8837d52020-06-07 11:59:04 +030061 /** @brief Get container's iterator. */
62 container_t::const_iterator begin() const;
63 /** @brief Get container's iterator. */
64 container_t::const_iterator end() const;
65
66 private:
67 /** @brief Remove the oldest messages from container. */
68 void shrink();
69
70 private:
71 /** @brief Log message list. */
72 container_t messages;
73 /** @brief Flag to indicate that the last message is incomplete. */
74 bool lastComplete;
75 /** @brief Max number of messages that can be stored. */
76 size_t sizeLimit;
77 /** @brief Max age of messages (in minutes) that can be stored. */
78 size_t timeLimit;
79 /** @brief Callback function called if buffer is full. */
80 std::function<void()> fullHandler;
81};