blob: 1e5c57b87d5d2bc957b15a1420279966d0a68d86 [file] [log] [blame]
Brian Silverman01f0d222014-02-16 01:09:11 -08001#ifndef AOS_COMMON_UTIL_LOG_INTERVAL_H_
2#define AOS_COMMON_UTIL_LOG_INTERVAL_H_
3
4#include "aos/common/time.h"
5#include "aos/common/logging/logging.h"
6
7#include <string>
8
9namespace aos {
10namespace util {
11
12// A class to help with logging things that happen a lot only occasionally.
13//
14// Intended use {
15// static LogInterval interval(::aos::time::Time::InSeconds(0.2));
16//
17// if (WantToLog()) {
18// interval.WantToLog();
19// }
20// if (interval.ShouldLog()) {
21// LOG(DEBUG, "thingie happened! (%d times)\n", interval.Count());
22// }
23// }
24class LogInterval {
25 public:
26 constexpr LogInterval(const ::aos::time::Time &interval)
27 : count_(0), interval_(interval), last_done_(0, 0) {}
28
29 void WantToLog() {
30 if (count_ == 0) {
31 last_done_ = ::aos::time::Time::Now();
32 }
33 ++count_;
34 }
35 bool ShouldLog() {
36 const ::aos::time::Time now = ::aos::time::Time::Now();
37 const bool r = (now - last_done_) >= interval_;
38 if (r) {
39 last_done_ = now;
40 }
41 return r;
42 }
43 int Count() {
44 const int r = count_;
45 count_ = 0;
46 return r;
47 }
48
49 private:
50 int count_;
51 const ::aos::time::Time interval_;
52 ::aos::time::Time last_done_;
53};
54
55// This one is even easier to use. It always logs with a message "%s %d
56// times\n".
57class SimpleLogInterval {
58 public:
59 SimpleLogInterval(const ::aos::time::Time &interval, log_level level,
60 const ::std::string &message)
61 : interval_(interval), level_(level), message_(message) {}
62
63#define LOG_INTERVAL(simple_log) \
64 simple_log.Hit(LOG_SOURCENAME ": " STRINGIFY(__LINE__))
65 void Hit(const char *context) {
66 interval_.WantToLog();
67 if (interval_.ShouldLog()) {
68 log_do(level_, "%s: %.*s %d times\n", context, message_.size(),
69 message_.data(), interval_.Count());
70 }
71 }
72
73 private:
74 LogInterval interval_;
75 const log_level level_;
76 const ::std::string message_;
77};
78
79} // namespace util
80} // namespace aos
81
82#endif // AOS_COMMON_UTIL_LOG_INTERVAL_H_