blob: 24e7ad7d93bdf1767da3cd92ff3a517d32e36062 [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
40 /**
41 * @brief Add raw data from host's console output.
42 *
43 * @param[in] data pointer to raw data buffer
44 * @param[in] sz size of the buffer in bytes
45 */
46 void append(const char* data, size_t sz);
47
48 /**
49 * @brief Set handler called if buffer is full.
50 *
51 * @param[in] cb callback function
52 */
53 void setFullHandler(std::function<void()> cb);
54
55 /** @brief Clear (reset) container. */
56 void clear();
57 /** @brief Check container for empty. */
58 bool empty() const;
59 /** @brief Get container's iterator. */
60 container_t::const_iterator begin() const;
61 /** @brief Get container's iterator. */
62 container_t::const_iterator end() const;
63
64 private:
65 /** @brief Remove the oldest messages from container. */
66 void shrink();
67
68 private:
69 /** @brief Log message list. */
70 container_t messages;
71 /** @brief Flag to indicate that the last message is incomplete. */
72 bool lastComplete;
73 /** @brief Max number of messages that can be stored. */
74 size_t sizeLimit;
75 /** @brief Max age of messages (in minutes) that can be stored. */
76 size_t timeLimit;
77 /** @brief Callback function called if buffer is full. */
78 std::function<void()> fullHandler;
79};