-
Notifications
You must be signed in to change notification settings - Fork 4
/
logging_policy.h
63 lines (49 loc) · 2.24 KB
/
logging_policy.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
// Logging-related utilities for configuring spdlog the way we like it
// (see github.com/gabime/spdlog).
#pragma once
#include <stdexcept>
#include <string>
#include <fmt/core.h>
#include <spdlog/cfg/helpers.h>
#include <spdlog/spdlog.h>
namespace pivid {
// Convenience aliases
namespace log = ::spdlog;
using log_level = ::spdlog::level::level_enum;
// Logs a trace message; does not evaluate args if trace logging is not enabled
#define TRACE(l, ...) \
[&]{ if (l->should_log(log_level::trace)) l->trace(__VA_ARGS__); }()
// Logs a debug message; does not evaluate args if debug logging is not enabled
#define DEBUG(l, ...) \
[&]{ if (l->should_log(log_level::debug)) l->debug(__VA_ARGS__); }()
// Throws std::logic_error if the condition is false
#define ASSERT(f) \
[&]{ if (!(f)) throw std::logic_error("ASSERT fail (" FILELINE ") " #f); }()
// Throws std::invalid_argument if the condition is false, using fmt args
#define CHECK_ARG(f, ...) \
[&]{ if (!(f)) throw std::invalid_argument(fmt::format(__VA_ARGS__)); }()
// Throws std::runtime_error if the condition is false, using fmt args
#define CHECK_RUNTIME(f, ...) \
[&]{ if (!(f)) throw std::runtime_error(fmt::format(__VA_ARGS__)); }()
// File and line number used by ASSERT
#define FILELINE __FILE__ ":" STRINGIFY(__LINE__)
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x
// Configures the logger output format with our preferred pattern.
// Sets log levels based on a string, typically a command line --log arg,
// to allow "--log=info,display=trace,media=debug" type parameters.
inline void configure_logging(std::string config) {
auto const utc = spdlog::pattern_time_type::utc;
spdlog::set_pattern("%H:%M:%S.%e %6iu %^%L [%n] %v%$", utc);
spdlog::cfg::helpers::load_levels(config);
}
// Creates a new logger that shares the same "sinks" as the default logger.
// Used to create named loggers for subcomponents that can have their
// log levels adjusted separately but all write in the same output stream.
inline std::shared_ptr<spdlog::logger> make_logger(char const* name) {
auto const& s = spdlog::default_logger()->sinks();
auto logger = std::make_shared<spdlog::logger>(name, s.begin(), s.end());
spdlog::initialize_logger(logger);
return logger;
}
}