blob: 2e94fdf477ee5798bac10c2b691c3fe3241b0b96 [file] [log] [blame]
Erik Klineb31fd692018-06-06 20:50:11 +09001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef NETUTILS_LOG_H
18#define NETUTILS_LOG_H
19
20#include <chrono>
21#include <deque>
22#include <shared_mutex>
23#include <string>
Bernie Innocentic7994ae2018-09-06 16:36:38 +090024#include <type_traits>
Erik Klineb31fd692018-06-06 20:50:11 +090025
26#include <android-base/stringprintf.h>
27#include <android-base/thread_annotations.h>
28
29#include <netdutils/Status.h>
30
31namespace android {
32namespace netdutils {
33
34class LogEntry {
35 public:
36 LogEntry() = default;
37 LogEntry(const LogEntry&) = default;
38 LogEntry(LogEntry&&) = default;
39 ~LogEntry() = default;
40 LogEntry& operator=(const LogEntry&) = default;
41 LogEntry& operator=(LogEntry&&) = default;
42
43 std::string toString() const;
44
45 ///
46 // Helper methods that make it easy to build up a LogEntry message.
47 // If performance becomes a factor the implementations could be inlined.
48 ///
49 LogEntry& message(const std::string& message);
50
51 // For calling with __FUNCTION__.
52 LogEntry& function(const std::string& function_name);
53 // For calling with __PRETTY_FUNCTION__.
54 LogEntry& prettyFunction(const std::string& pretty_function);
55
56 // Convenience methods for each of the common types of function arguments.
57 LogEntry& arg(const std::string& val);
Bernie Innocentie2cda072018-09-06 21:39:49 +090058 // Intended for binary buffers, formats as hex
59 LogEntry& arg(const std::vector<uint8_t>& val);
Erik Klineb31fd692018-06-06 20:50:11 +090060 LogEntry& arg(const std::vector<int32_t>& val);
Erik Klineb31fd692018-06-06 20:50:11 +090061 LogEntry& arg(const std::vector<std::string>& val);
Bernie Innocentic7994ae2018-09-06 16:36:38 +090062 template <typename IntT, typename = std::enable_if_t<std::is_arithmetic_v<IntT>>>
63 LogEntry& arg(IntT val) {
Erik Klineb31fd692018-06-06 20:50:11 +090064 mArgs.push_back(std::to_string(val));
65 return *this;
66 }
Bernie Innocentic7994ae2018-09-06 16:36:38 +090067 // Not using a plain overload here to avoid the implicit conversion from
68 // any pointer to bool, which causes string literals to print as 'true'.
69 template <>
70 LogEntry& arg<>(bool val);
71
Bernie Innocentie2cda072018-09-06 21:39:49 +090072 template <typename... Args>
73 LogEntry& args(const Args&... a) {
Bernie Innocentic7994ae2018-09-06 16:36:38 +090074 // Cleverness ahead: we throw away the initializer_list filled with
75 // zeroes, all we care about is calling arg() for each argument.
Bernie Innocentie2cda072018-09-06 21:39:49 +090076 (void) std::initializer_list<int>{(arg(a), 0)...};
Bernie Innocentic7994ae2018-09-06 16:36:38 +090077 return *this;
78 }
Erik Klineb31fd692018-06-06 20:50:11 +090079
80 // Some things can return more than one value, or have multiple output
81 // parameters, so each of these adds to the mReturns vector.
82 LogEntry& returns(const std::string& rval);
83 LogEntry& returns(const Status& status);
84 LogEntry& returns(bool rval);
85 template <class T>
86 LogEntry& returns(T val) {
87 mReturns.push_back(std::to_string(val));
88 return *this;
89 }
90
91 LogEntry& withUid(uid_t uid);
92
93 // Append the duration computed since the creation of this instance.
94 LogEntry& withAutomaticDuration();
95 // Append the string-ified duration computed by some other means.
96 LogEntry& withDuration(const std::string& duration);
97
98 private:
99 std::chrono::steady_clock::time_point mStart = std::chrono::steady_clock::now();
100 std::string mMsg{};
101 std::string mFunc{};
102 std::vector<std::string> mArgs{};
103 std::vector<std::string> mReturns{};
104 std::string mUid{};
105 std::string mDuration{};
106};
107
108class Log {
109 public:
110 Log() = delete;
111 Log(const std::string& tag) : Log(tag, MAX_ENTRIES) {}
112 Log(const std::string& tag, size_t maxEntries) : mTag(tag), mMaxEntries(maxEntries) {}
113 Log(const Log&) = delete;
114 Log(Log&&) = delete;
115 ~Log();
116 Log& operator=(const Log&) = delete;
117 Log& operator=(Log&&) = delete;
118
119 LogEntry newEntry() const { return LogEntry(); }
120
121 // Record a log entry in internal storage only.
122 void log(const std::string& entry) { record(Level::LOG, entry); }
123 template <size_t n>
124 void log(const char entry[n]) { log(std::string(entry)); }
125 void log(const LogEntry& entry) { log(entry.toString()); }
126 void log(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
127 using ::android::base::StringAppendV;
128 std::string result;
129 va_list ap;
130 va_start(ap, fmt);
131 StringAppendV(&result, fmt, ap);
132 va_end(ap);
133 log(result);
134 }
135
136 // Record a log entry in internal storage and to ALOGI as well.
137 void info(const std::string& entry) { record(Level::INFO, entry); }
138 template <size_t n>
139 void info(const char entry[n]) { info(std::string(entry)); }
140 void info(const LogEntry& entry) { info(entry.toString()); }
141 void info(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
142 using ::android::base::StringAppendV;
143 std::string result;
144 va_list ap;
145 va_start(ap, fmt);
146 StringAppendV(&result, fmt, ap);
147 va_end(ap);
148 info(result);
149 }
150
151 // Record a log entry in internal storage and to ALOGW as well.
152 void warn(const std::string& entry) { record(Level::WARN, entry); }
153 template <size_t n>
154 void warn(const char entry[n]) { warn(std::string(entry)); }
155 void warn(const LogEntry& entry) { warn(entry.toString()); }
156 void warn(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
157 using ::android::base::StringAppendV;
158 std::string result;
159 va_list ap;
160 va_start(ap, fmt);
161 StringAppendV(&result, fmt, ap);
162 va_end(ap);
163 warn(result);
164 }
165
166 // Record a log entry in internal storage and to ALOGE as well.
167 void error(const std::string& entry) { record(Level::ERROR, entry); }
168 template <size_t n>
169 void error(const char entry[n]) { error(std::string(entry)); }
170 void error(const LogEntry& entry) { error(entry.toString()); }
171 void error(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
172 using ::android::base::StringAppendV;
173 std::string result;
174 va_list ap;
175 va_start(ap, fmt);
176 StringAppendV(&result, fmt, ap);
177 va_end(ap);
178 error(result);
179 }
180
181 // Iterates over every entry in the log in chronological order. Operates
182 // on a copy of the log entries, and so perEntryFn may itself call one of
183 // the logging functions if needed.
184 void forEachEntry(const std::function<void(const std::string&)>& perEntryFn) const;
185
186 private:
187 static constexpr const size_t MAX_ENTRIES = 750U;
188 const std::string mTag;
189 const size_t mMaxEntries;
190
191 // The LOG level adds an entry to mEntries but does not output the message
192 // to the system log. All other levels append to mEntries and output to the
193 // the system log.
194 enum class Level {
195 LOG,
196 INFO,
197 WARN,
198 ERROR,
199 };
200
201 void record(Level lvl, const std::string& entry);
202
203 mutable std::shared_mutex mLock;
204 std::deque<const std::string> mEntries; // GUARDED_BY(mLock), when supported
205};
206
207} // namespace netdutils
208} // namespace android
209
210#endif /* NETUTILS_LOG_H */