-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlogger.h
417 lines (367 loc) · 9.96 KB
/
logger.h
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// SPDX-FileCopyrightText: 2013-2024 Technical University of Munich
//
// SPDX-License-Identifier: BSD-3-Clause
//
// SPDX-FileContributor: Sebastian Rettenberger
// SPDX-FileContributor: David Schneller
#ifndef UTILS_LOGGER_H_
#define UTILS_LOGGER_H_
#include "utils/common.h"
#include "utils/stringutils.h"
#include "utils/timeutils.h"
#include <algorithm>
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <ctime>
#include <execinfo.h>
#include <functional>
#include <iostream>
#include <signal.h>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <tuple>
#include <type_traits>
#ifndef LOG_LEVEL
#ifdef NDEBUG
#define LOG_LEVEL 2
#else // NDEBUG
#define LOG_LEVEL 3
#endif // NDEBUG
#endif // LOG_LEVEL
#ifndef LOG_ABORT
#ifdef MPI_VERSION
#define LOG_ABORT MPI_Abort(MPI_COMM_WORLD, 134)
#else // MPI_VERSION
#define LOG_ABORT abort()
#endif // MPI_VERSION
#endif // LOG_ABORT
#ifndef BACKTRACE_SIZE
#define BACKTRACE_SIZE 50
#endif // BACKTRACE_SIZE
/**
* A collection of useful utility functions
*/
namespace utils {
/**
* Handles debugging/logging output
*
* Most of the code is taken from QDebug form the Qt Framework
*/
class Logger {
public:
/** Message type */
enum class DebugType {
/** A debug messages */
LogDebug,
/** A info message (printed to stdout) */
LogInfo,
/** A warning message */
LogWarning,
/** A fatal error */
LogError
};
private:
static inline int displayRank{0};
static inline int rank{-1};
static inline bool logAll{false};
/** Contains all information for a debug message */
struct Stream {
/** The debug type */
DebugType type;
/** MPI Rank, set to 0 to print message */
int rank;
/** References */
int ref{1};
/** Buffer for the output */
std::stringstream buffer;
/** Print additional space */
bool space{true};
bool broadcast;
/**
* Set defaults for a debug message
*/
Stream(DebugType t, int r, bool broadcast)
: type(t), rank(r), buffer(std::stringstream::out), broadcast(broadcast) {}
}* stream;
/**
* Pointer to all information about the message
*/
template <typename T, std::size_t Idx>
static void printTuple(Logger& logger, const T& data) {
if constexpr (Idx < std::tuple_size_v<T>) {
if constexpr (Idx > 0) {
logger << ", ";
}
logger << std::get<Idx>(data);
printTuple<T, Idx + 1>(logger, data);
}
}
public:
static void setDisplayRank(int rank) { Logger::displayRank = rank; }
static void setRank(int rank) { Logger::rank = rank; }
static void setLogAll(bool logAll) { Logger::logAll = logAll; }
/**
* Start a new Debug message
*
* @param t Type of the message
* @param rank Rank of the current process, only messages form rank
* 0 will be printed
*/
Logger(DebugType t, bool broadcast) : stream(new Stream(t, Logger::rank, broadcast)) {
auto timepoint = std::chrono::system_clock::now();
auto milliTotal =
std::chrono::duration_cast<std::chrono::milliseconds>(timepoint.time_since_epoch()).count();
auto milli = milliTotal % 1000;
const time_t time = std::chrono::system_clock::to_time_t(timepoint);
stream->buffer << utils::TimeUtils::timeAsString("%F %T", time) << "."
<< StringUtils::padLeft(std::to_string(milli), 3, '0');
switch (t) {
case DebugType::LogDebug:
stream->buffer << " debug ";
break;
case DebugType::LogInfo:
stream->buffer << " info ";
break;
case DebugType::LogWarning:
stream->buffer << " warn ";
break;
case DebugType::LogError:
stream->buffer << " error ";
break;
default:
stream->buffer << " unknown ";
break;
}
if (stream->rank >= 0) {
stream->buffer << stream->rank << " : ";
} else {
stream->buffer << "- : ";
}
}
Logger(const Logger& o) : stream(o.stream) { stream->ref++; }
// for now, delete the move constructors/operators
Logger(Logger&& o) = delete;
auto operator=(Logger&& o) = delete;
~Logger() {
if (--stream->ref == 0) {
if (stream->rank == Logger::displayRank || stream->rank == -1 || Logger::logAll ||
stream->broadcast) {
if (stream->type == DebugType::LogInfo || stream->type == DebugType::LogDebug) {
std::cout << stream->buffer.str() << '\n';
} else {
std::cerr << stream->buffer.str() << '\n';
}
}
if (stream->type == DebugType::LogError) {
delete stream;
stream = nullptr; // Avoid double free if LOG_ABORT does
// does not exit the program
// Backtrace
if (BACKTRACE_SIZE > 0) {
void* buffer[BACKTRACE_SIZE];
const int nptrs = backtrace(buffer, BACKTRACE_SIZE);
char** strings = backtrace_symbols(buffer, nptrs);
// Buffer output to avoid interlacing with other processes
std::stringstream outputBuffer;
outputBuffer << "Backtrace:" << '\n';
for (int i = 0; i < nptrs; i++) {
outputBuffer << strings[i] << '\n';
}
free(strings);
// Write backtrace to stderr
std::cerr << outputBuffer.str() << std::flush;
}
std::raise(SIGTRAP);
LOG_ABORT;
}
delete stream;
}
}
/**
* Copy operator
*/
auto operator=(const Logger& other) -> Logger& {
if (this != &other) {
Logger copy(other);
std::swap(stream, copy.stream);
}
return *this;
}
/********* Space handling *********/
/**
* Add a space to output message and activate spaces
*/
auto space() -> Logger& {
stream->space = true;
stream->buffer << ' ';
return *this;
}
/**
* Deactivate spaces
*/
auto nospace() -> Logger& {
stream->space = false;
return *this;
}
/**
* Add space of activated
*/
auto maybeSpace() -> Logger& {
if (stream->space) {
stream->buffer << ' ';
}
return *this;
}
/**
* Default function to add messages
*/
template <typename T>
auto operator<<(const T& data) -> Logger& {
if constexpr (std::is_invocable_r_v<Logger&, T, Logger&>) {
return std::invoke(data, *this);
} else if constexpr (std::is_same_v<T, std::string>) {
stream->buffer << '"' << data << '"';
return maybeSpace();
} else if constexpr (CanOutput<T>::Value) {
stream->buffer << data;
return maybeSpace();
} else if constexpr (IsIterable<T>::Value) {
nospace() << '[';
auto it = std::begin(data);
if (it != std::end(data)) {
*this << *it;
++it;
}
for (; it != std::end(data); ++it) {
*this << ", " << *it;
}
*this << ']';
return space();
} else if constexpr (IsGettable<T>::Value) {
nospace() << '{';
printTuple<T, 0>(*this, data);
*this << '}';
return space();
} else {
// https://stackoverflow.com/questions/38304847/how-does-a-failed-static-assert-work-in-an-if-constexpr-false-block#comment119622305_64354296
static_assert(sizeof(T) == 0, "Output for the given type not implemented.");
}
}
/**
* Operator to add functions like std::endl
*/
auto operator<<(std::ostream& (*func)(std::ostream&)) -> Logger& {
stream->buffer << func;
return *this; // No space in this case
}
};
/**
* Function to activate automatic spacing
*
* Example:
* <code>logInfo() << nospace() << x << ":";</code>
*
* @relates utils::Logger
*/
inline auto space(Logger& logger) -> Logger& { return logger.space(); }
/**
* Function to deactivate automatic spacing
*
* @see space()
* @relates utils::Logger
*/
inline auto nospace(Logger& logger) -> Logger& { return logger.nospace(); }
/**
* Dummy Logger class, does nothing
*/
class NoLogger {
public:
NoLogger() = default;
~NoLogger() = default;
/**
* Do nothing with the message
*/
template <typename T>
auto operator<<(const T& /*unused*/) -> NoLogger& {
return *this;
}
/**
* Operator to add functions like std::endl
*/
auto operator<<(std::ostream& (*func)(std::ostream&)) -> NoLogger& { return *this; }
/**
* Operator for enabling/disabling automatic spacing
* (the operator itself is ignored)
*/
auto operator<<(Logger& (*func)(Logger&)) -> NoLogger& { return *this; }
};
} // namespace utils
// Define global functions
/**
* Create error message and exit
*
* @relates utils::Logger
*/
inline auto logError(bool broadcast = true) -> utils::Logger {
return {utils::Logger::DebugType::LogError, broadcast};
}
#if LOG_LEVEL >= 1
/**
* Create a warning message if enabled
*
* @relates utils::Logger
*/
inline auto logWarning(bool broadcast = false) -> utils::Logger {
return {utils::Logger::DebugType::LogWarning, broadcast};
}
#else // LOG_LEVEL >= 1
/**
* Create a dummy warning message if disabled
*
* @relates utils::NoLogger
*/
inline utils::NoLogger logWarning(bool broadcast = false) { return utils::NoLogger(); }
#endif // LOG_LEVEL >= 1
#if LOG_LEVEL >= 2
/**
* Create a info message if enabled
*
* @relates utils::Logger
*/
inline auto logInfo(bool broadcast = false) -> utils::Logger {
return {utils::Logger::DebugType::LogInfo, broadcast};
}
#else // LOG_LEVEL >= 2
/**
* Create a dummy info message if disabled
*
* @relates utils::NoLogger
*/
inline utils::NoLogger logInfo(bool broadcast = false) { return utils::NoLogger(); }
#endif // LOG_LEVEL >= 2
#if LOG_LEVEL >= 3
/**
* Create a debug message if enabled
*
* @relates utils::Logger
*/
inline auto logDebug(bool broadcast = false) -> utils::Logger {
return {utils::Logger::DebugType::LogDebug, broadcast};
}
#else // LOG_LEVEL >= 3
/**
* Create a dummy debug message if disabled
*
* @relates utils::NoLogger
*/
inline utils::NoLogger logDebug(bool broadcast = false) { return utils::NoLogger(); }
#endif // LOG_LEVEL >= 3
// Use for variables unused when compiling with NDEBUG
#ifdef NDEBUG
#define NDBG_UNUSED(x) ((void)x)
#else // NDEBUG
#define NDBG_UNUSED(x)
#endif // NDEBUG
#endif // UTILS_LOGGER_H_