blob: 90715db2ae1fd7e512f0dadf8fc4ef0df6ba212f [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);
58 LogEntry& arg(const std::vector<int32_t>& val);
Erik Klineb31fd692018-06-06 20:50:11 +090059 LogEntry& arg(const std::vector<std::string>& val);
Bernie Innocentic7994ae2018-09-06 16:36:38 +090060 template <typename IntT, typename = std::enable_if_t<std::is_arithmetic_v<IntT>>>
61 LogEntry& arg(IntT val) {
Erik Klineb31fd692018-06-06 20:50:11 +090062 mArgs.push_back(std::to_string(val));
63 return *this;
64 }
Bernie Innocentic7994ae2018-09-06 16:36:38 +090065 // Not using a plain overload here to avoid the implicit conversion from
66 // any pointer to bool, which causes string literals to print as 'true'.
67 template <>
68 LogEntry& arg<>(bool val);
69
70 template <typename... Args> LogEntry& args(const Args&... a) {
71 // Cleverness ahead: we throw away the initializer_list filled with
72 // zeroes, all we care about is calling arg() for each argument.
73 (void)std::initializer_list<int>{ (arg(a), 0)... };
74 return *this;
75 }
Erik Klineb31fd692018-06-06 20:50:11 +090076
77 // Some things can return more than one value, or have multiple output
78 // parameters, so each of these adds to the mReturns vector.
79 LogEntry& returns(const std::string& rval);
80 LogEntry& returns(const Status& status);
81 LogEntry& returns(bool rval);
82 template <class T>
83 LogEntry& returns(T val) {
84 mReturns.push_back(std::to_string(val));
85 return *this;
86 }
87
88 LogEntry& withUid(uid_t uid);
89
90 // Append the duration computed since the creation of this instance.
91 LogEntry& withAutomaticDuration();
92 // Append the string-ified duration computed by some other means.
93 LogEntry& withDuration(const std::string& duration);
94
95 private:
96 std::chrono::steady_clock::time_point mStart = std::chrono::steady_clock::now();
97 std::string mMsg{};
98 std::string mFunc{};
99 std::vector<std::string> mArgs{};
100 std::vector<std::string> mReturns{};
101 std::string mUid{};
102 std::string mDuration{};
103};
104
105class Log {
106 public:
107 Log() = delete;
108 Log(const std::string& tag) : Log(tag, MAX_ENTRIES) {}
109 Log(const std::string& tag, size_t maxEntries) : mTag(tag), mMaxEntries(maxEntries) {}
110 Log(const Log&) = delete;
111 Log(Log&&) = delete;
112 ~Log();
113 Log& operator=(const Log&) = delete;
114 Log& operator=(Log&&) = delete;
115
116 LogEntry newEntry() const { return LogEntry(); }
117
118 // Record a log entry in internal storage only.
119 void log(const std::string& entry) { record(Level::LOG, entry); }
120 template <size_t n>
121 void log(const char entry[n]) { log(std::string(entry)); }
122 void log(const LogEntry& entry) { log(entry.toString()); }
123 void log(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
124 using ::android::base::StringAppendV;
125 std::string result;
126 va_list ap;
127 va_start(ap, fmt);
128 StringAppendV(&result, fmt, ap);
129 va_end(ap);
130 log(result);
131 }
132
133 // Record a log entry in internal storage and to ALOGI as well.
134 void info(const std::string& entry) { record(Level::INFO, entry); }
135 template <size_t n>
136 void info(const char entry[n]) { info(std::string(entry)); }
137 void info(const LogEntry& entry) { info(entry.toString()); }
138 void info(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
139 using ::android::base::StringAppendV;
140 std::string result;
141 va_list ap;
142 va_start(ap, fmt);
143 StringAppendV(&result, fmt, ap);
144 va_end(ap);
145 info(result);
146 }
147
148 // Record a log entry in internal storage and to ALOGW as well.
149 void warn(const std::string& entry) { record(Level::WARN, entry); }
150 template <size_t n>
151 void warn(const char entry[n]) { warn(std::string(entry)); }
152 void warn(const LogEntry& entry) { warn(entry.toString()); }
153 void warn(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
154 using ::android::base::StringAppendV;
155 std::string result;
156 va_list ap;
157 va_start(ap, fmt);
158 StringAppendV(&result, fmt, ap);
159 va_end(ap);
160 warn(result);
161 }
162
163 // Record a log entry in internal storage and to ALOGE as well.
164 void error(const std::string& entry) { record(Level::ERROR, entry); }
165 template <size_t n>
166 void error(const char entry[n]) { error(std::string(entry)); }
167 void error(const LogEntry& entry) { error(entry.toString()); }
168 void error(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
169 using ::android::base::StringAppendV;
170 std::string result;
171 va_list ap;
172 va_start(ap, fmt);
173 StringAppendV(&result, fmt, ap);
174 va_end(ap);
175 error(result);
176 }
177
178 // Iterates over every entry in the log in chronological order. Operates
179 // on a copy of the log entries, and so perEntryFn may itself call one of
180 // the logging functions if needed.
181 void forEachEntry(const std::function<void(const std::string&)>& perEntryFn) const;
182
183 private:
184 static constexpr const size_t MAX_ENTRIES = 750U;
185 const std::string mTag;
186 const size_t mMaxEntries;
187
188 // The LOG level adds an entry to mEntries but does not output the message
189 // to the system log. All other levels append to mEntries and output to the
190 // the system log.
191 enum class Level {
192 LOG,
193 INFO,
194 WARN,
195 ERROR,
196 };
197
198 void record(Level lvl, const std::string& entry);
199
200 mutable std::shared_mutex mLock;
201 std::deque<const std::string> mEntries; // GUARDED_BY(mLock), when supported
202};
203
204} // namespace netdutils
205} // namespace android
206
207#endif /* NETUTILS_LOG_H */