-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogging.h
More file actions
274 lines (231 loc) · 10.2 KB
/
Copy pathlogging.h
File metadata and controls
274 lines (231 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// SPDX-License-Identifier: MIT
#ifndef STDCORELIB_LOGGING_H
#define STDCORELIB_LOGGING_H
#include <stdcorelib/str.h>
/// \defgroup logging Logging
///
/// Named categories with per-level switches and Qt-style filter rules.
///
/// \code
/// static stdc::LogCategory lc("app.io");
///
/// lc.stdcWarning("cannot read %1", path);
/// lc.stdcDebugF("offset=%zu", off); // the printf-style variant
/// stdcInfo("no category in scope, so this goes to the default one");
///
/// lc.setFilterRules("*.debug = false\n" // silence debug everywhere
/// "app.io = false\n" // silence this category
/// "app.io.warning = true"); // except for its warnings
/// \endcode
///
/// \c Logger::setLogCallback() replaces the sink, which is how records reach a file or a UI instead
/// of the terminal.
namespace stdc {
/// \addtogroup logging
/// @{
class LogContext {
public:
inline LogContext() noexcept = default;
inline LogContext(const char *fileName, int lineNumber, const char *functionName,
const char *categoryName) noexcept
: line(lineNumber), file(fileName), function(functionName), category(categoryName) {
}
int line = 0;
const char *file = nullptr;
const char *function = nullptr;
const char *category = nullptr;
};
class STDC_EXPORT Logger {
public:
enum Level {
Trace = 1,
Debug,
Success,
Information,
Warning,
Critical,
Fatal,
};
inline Logger(LogContext context) : _context(std::move(context)) {
}
inline Logger(const char *file, int line, const char *function, const char *category)
: _context(file, line, function, category) {
}
template <class... Args>
inline void trace(const std::string_view &format, Args &&...args) {
print(Trace, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
inline void debug(const std::string_view &format, Args &&...args) {
print(Debug, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
inline void success(const std::string_view &format, Args &&...args) {
print(Success, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
inline void info(const std::string_view &format, Args &&...args) {
print(Information, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
inline void warning(const std::string_view &format, Args &&...args) {
print(Warning, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
inline void critical(const std::string_view &format, Args &&...args) {
print(Critical, stdc::formatN(format, std::forward<Args>(args)...));
}
template <class... Args>
[[noreturn]] inline void fatal(const std::string_view &format, Args &&...args) {
print(Fatal, stdc::formatN(format, std::forward<Args>(args)...));
abort();
}
template <class... Args>
inline void log(int level, const std::string_view &format, Args &&...args) {
print(level, stdc::formatN(format, std::forward<Args>(args)...));
}
void print(int level, const std::string_view &message);
void printf(int level, const char *fmt, ...);
[[noreturn]] static void abort();
public:
using LogCallback = void (*)(int, const LogContext &, const std::string_view &);
static LogCallback logCallback();
/// Replaces the sink every record goes to.
///
/// \param callback the new sink, or \c nullptr to put the built-in one back
static void setLogCallback(LogCallback callback);
protected:
LogContext _context;
};
/// A named channel with independently switchable levels, after Qt's \c QLoggingCategory.
///
/// Each category registers itself on construction and picks up whatever filter rules are
/// already in effect.
///
/// \sa setFilterRules()
class STDC_EXPORT LogCategory {
public:
explicit LogCategory(const char *name);
~LogCategory();
inline const char *name() const {
return _name;
}
inline bool isLevelEnabled(int level) const {
return levelEnabled[level];
}
inline void setLevelEnabled(int level, bool enabled) {
levelEnabled[level] = enabled;
}
using LogCategoryFilter = void (*)(LogCategory *);
/// The filter in force, which is the default one where none was installed.
///
/// \return never \c nullptr. setLogFilter() takes one to mean the default rather than
/// none, so there is no state in which nothing is filtering.
static LogCategoryFilter logFilter();
/// Replaces the category filter and re-runs it over every registered category.
///
/// \param filter the new filter, or \c nullptr to restore the default one
/// \note A custom filter takes over entirely, so setFilterRules() has no effect unless
/// that filter chooses to consult the rules itself.
static void setLogFilter(LogCategoryFilter filter);
static std::string filterRules();
/// Installs Qt-style filter rules controlling which levels each category emits.
///
/// Rules are separated by newlines or \c ;, and a \c # starts a comment line. Each rule
/// reads <tt>category[.level] = true|false</tt>, where:
/// \li category may carry a single leading and/or trailing \c * wildcard, and
/// otherwise matches exactly
/// \li level is one of \c trace, \c debug, \c success, \c info, \c warning,
/// \c critical or \c fatal, and omitting it affects every level
///
/// Rules apply in order over an all-enabled baseline, so a later match wins.
///
/// \code
/// *.debug = false // silence debug everywhere
/// stdc.io = false // silence the stdc.io category
/// stdc.io.warning = true // except for its warnings
/// \endcode
///
/// \note This affects every category in the process, not just this one, despite being a
/// member. A malformed rule is skipped rather than reported.
void setFilterRules(std::string rules);
static LogCategory &defaultCategory();
template <int Level, class... Args>
void log(const char *fileName, int lineNumber, const char *functionName,
const std::string_view &format, Args &&...args) const {
if (!isLevelEnabled(Level)) {
return;
}
Logger(fileName, lineNumber, functionName, _name)
.log(Level, format, std::forward<Args>(args)...);
if constexpr (Level == stdc::Logger::Fatal) {
Logger::abort();
}
}
template <int Level, class... Args>
void logf(const char *fileName, int lineNumber, const char *functionName, const char *fmt,
Args &&...args) const {
if (!isLevelEnabled(Level)) {
return;
}
Logger(fileName, lineNumber, functionName, _name)
.printf(Level, fmt, std::forward<Args>(args)...);
if constexpr (Level == stdc::Logger::Fatal) {
Logger::abort();
}
}
inline const LogCategory &stdcGetLogCategory() const {
return *this;
}
protected:
const char *_name;
union {
bool levelEnabled[8];
uint64_t enabled;
};
};
/// @}
}
/// What the macros below fall back to when no LogCategory is in scope. A category of your own
/// provides a member of the same name, which unqualified lookup finds first.
///
/// \internal
static inline const stdc::LogCategory &stdcGetLogCategory() {
return stdc::LogCategory::defaultCategory();
}
/// Logs one record at \a LEVEL, tagged with the file, line and function it came from.
///
/// Written on a category it goes to that one, written bare it goes to the default category. The
/// message uses formatN() placeholders (\c %1, \c %2, ...), and the \c F variants below take
/// printf conversions instead.
///
/// \warning This expands to an ordinary call, so the arguments are evaluated whether the level
/// is enabled or not. Unlike Qt's \c qCDebug, which short circuits, anything expensive
/// belongs behind an isLevelEnabled() check of your own.
///
/// \code
/// stdc::LogCategory lc("app.io");
/// lc.stdcWarning("cannot read %1", path);
/// lc.stdcWarningF("cannot read %s", path.c_str());
///
/// stdcWarning("something to say about nothing in particular");
/// \endcode
#define stdcLog(LEVEL, ...) \
stdcGetLogCategory().log<stdc::Logger::LEVEL>(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define stdcTrace(...) stdcLog(Trace, __VA_ARGS__)
#define stdcDebug(...) stdcLog(Debug, __VA_ARGS__)
#define stdcSuccess(...) stdcLog(Success, __VA_ARGS__)
#define stdcInfo(...) stdcLog(Information, __VA_ARGS__)
#define stdcWarning(...) stdcLog(Warning, __VA_ARGS__)
#define stdcCritical(...) stdcLog(Critical, __VA_ARGS__)
#define stdcFatal(...) stdcLog(Fatal, __VA_ARGS__)
#define stdcLogF(LEVEL, ...) \
stdcGetLogCategory().logf<stdc::Logger::LEVEL>(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
#define stdcTraceF(...) stdcLogF(Trace, __VA_ARGS__)
#define stdcDebugF(...) stdcLogF(Debug, __VA_ARGS__)
#define stdcSuccessF(...) stdcLogF(Success, __VA_ARGS__)
#define stdcInfoF(...) stdcLogF(Information, __VA_ARGS__)
#define stdcWarningF(...) stdcLogF(Warning, __VA_ARGS__)
#define stdcCriticalF(...) stdcLogF(Critical, __VA_ARGS__)
#define stdcFatalF(...) stdcLogF(Fatal, __VA_ARGS__)
#endif // STDCORELIB_LOGGING_H