siplasplas
A library for C++ reflection and introspection
error_logger.hpp
1 #ifndef SIPLASPLAS_UTILITY_ERRORLOGGER_HPP
2 #define SIPLASPLAS_UTILITY_ERRORLOGGER_HPP
3 
4 #include <siplasplas/logger/logger.hpp>
5 #include <backward-cpp/backward.hpp>
6 #include <fmt/format.h>
7 #include <siplasplas/utility/export.hpp>
8 
20 namespace cpp
21 {
22 
23 namespace utility
24 {
25 
36 SIPLASPLAS_UTILITY_EXPORT spdlog::logger& errorLogger();
37 
83 template<typename Message, typename... Args>
84 void logErrorSkippingFrames(std::size_t framesToSkip, const Message& message, Args&&... args)
85 {
86  using namespace backward;
87  static constexpr std::size_t MAX_FRAMES = 32;
88  StackTrace stackTrace;
89  TraceResolver traceResolver;
90  stackTrace.load_here(MAX_FRAMES);
91  traceResolver.load_stacktrace(stackTrace);
92 
93  const std::size_t FRAMES_COUNT = stackTrace.size();
94 
95  framesToSkip += 3; // Skip this frame and the backward-cpp implementation ones
96  // (On linux these are backward::StackTraceImpl<Linux>::load_here()
97  // plus backtrace::detail::unwind())
98 
99  for(std::size_t i = 0; i < FRAMES_COUNT - framesToSkip; ++i)
100  {
101  const auto& trace = traceResolver.resolve(stackTrace[FRAMES_COUNT - i - 1]);
102 
103  errorLogger().debug(
104  "#{} \"{}\", at {}, in {}",
105  FRAMES_COUNT - framesToSkip - i,
106  trace.object_filename,
107  trace.addr,
108  trace.object_function
109  );
110 
111  }
112 
113  errorLogger().critical(fmt::format(message, std::forward<Args>(args)...));
114 }
115 
129 template<typename Message, typename... Args>
130 void logError(const Message& message, Args&&... args)
131 {
132  logErrorSkippingFrames(1, message, std::forward<Args>(args)...);
133 }
134 
135 }
136 
137 }
138 
139 #endif // SIPLASPLAS_UTILITY_ERRORLOGGER_HPP
Definition: canary_allocator.hpp:7
void logError(const Message &message, Args &&...args)
Logs an error with its backtrace. See cpp::logErrorSkippingFrames().
Definition: error_logger.hpp:130
void logErrorSkippingFrames(std::size_t framesToSkip, const Message &message, Args &&...args)
Log an error with its backtrace. Also skip the latest framesToSkip stack frames from stack trace...
Definition: error_logger.hpp:84
SIPLASPLAS_UTILITY_EXPORT spdlog::logger & errorLogger()
Isolated logger for detailed error logging.