C/C++ API Reference
Loading...
Searching...
No Matches
rate_limited.h
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#pragma once
16
17#include "pw_chrono/system_clock.h"
18#include "pw_log/log.h"
19
20// rate_limited adds a wrapper around a normal PW_LOG call to provide a rate
21// limitor parameter to suppress chatty logs and provide info on how many logs
22// were suppressed
23// PW_LOG_EVERY_N_DURATION(level, min_interval_between_logs, msg, ...)
24// - Required.
25// level - An integer level as defined by pw_log/levels.h
26// min_interval_between_logs - A std::chrono::duration of the minimum
27// interval between
28// two of the same logs.
29// msg - Formattable message, same as you would use for PW_LOG or variants
30//
31// Does not check that input parameters have changed to un-suppress logs.
32
33namespace pw::log::internal {
34
36 public:
37 struct PollResult {
38 uint16_t count;
39 uint16_t logs_per_s;
40 };
41
42 explicit RateLimiter() {}
43 ~RateLimiter() = default;
44
45 PollResult Poll(chrono::SystemClock::duration min_interval_between_logs);
46
47 private:
48 uint32_t count_ = 0;
49 chrono::SystemClock::time_point last_timestamp_;
50};
51
52} // namespace pw::log::internal
53
55
80#define PW_LOG_EVERY_N_DURATION(level, min_interval_between_logs, msg, ...) \
81 do { \
82 static pw::log::internal::RateLimiter rate_limiter; \
83 \
84 if (auto result = rate_limiter.Poll(min_interval_between_logs); \
85 result.count == std::numeric_limits<uint16_t>::max()) { \
86 PW_LOG(level, \
87 PW_LOG_LEVEL, \
88 PW_LOG_MODULE_NAME, \
89 PW_LOG_FLAGS, \
90 msg " (skipped %d or more, %d/s)", \
91 ##__VA_ARGS__, \
92 static_cast<unsigned>(result.count), \
93 static_cast<unsigned>(result.logs_per_s)); \
94 } else if (result.count != 0) { \
95 PW_LOG(level, \
96 PW_LOG_LEVEL, \
97 PW_LOG_MODULE_NAME, \
98 PW_LOG_FLAGS, \
99 msg " (skipped %d, %d/s)", \
100 ##__VA_ARGS__, \
101 static_cast<unsigned>(result.count - 1), \
102 static_cast<unsigned>(result.logs_per_s)); \
103 } \
104 } while (0)
105
Definition: rate_limited.h:35
std::chrono::duration< rep, period > duration
Alias for durations representable with this clock.
Definition: system_clock.h:90
Definition: rate_limited.h:37