WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
Log.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2015. All Rights Reserved. */
3 /* Open Source Software - may be modified and shared by FRC teams. The code */
4 /* must be accompanied by the FIRST BSD license file in the root directory of */
5 /* the project. */
6 /*----------------------------------------------------------------------------*/
7 
8 #ifndef NT_LOG_H_
9 #define NT_LOG_H_
10 
11 #include <functional>
12 #include <sstream>
13 #include <string>
14 
15 #include "atomic_static.h"
16 #include "ntcore_c.h"
17 
18 namespace nt {
19 
20 class Logger {
21  public:
22  static Logger& GetInstance() {
23  ATOMIC_STATIC(Logger, instance);
24  return instance;
25  }
26  ~Logger();
27 
28  typedef std::function<void(unsigned int level, const char* file,
29  unsigned int line, const char* msg)> LogFunc;
30 
31  void SetLogger(LogFunc func) { m_func = func; }
32 
33  void set_min_level(unsigned int level) { m_min_level = level; }
34  unsigned int min_level() const { return m_min_level; }
35 
36  void Log(unsigned int level, const char* file, unsigned int line,
37  const char* msg) {
38  if (!m_func || level < m_min_level) return;
39  m_func(level, file, line, msg);
40  }
41 
42  bool HasLogger() const { return m_func != nullptr; }
43 
44  private:
45  Logger();
46 
47  LogFunc m_func;
48  unsigned int m_min_level = 20;
49 
50  ATOMIC_STATIC_DECL(Logger)
51 };
52 
53 #define LOG(level, x) \
54  do { \
55  nt::Logger& logger = nt::Logger::GetInstance(); \
56  if (logger.min_level() <= level && logger.HasLogger()) { \
57  std::ostringstream oss; \
58  oss << x; \
59  logger.Log(level, __FILE__, __LINE__, oss.str().c_str()); \
60  } \
61  } while (0)
62 
63 #undef ERROR
64 #define ERROR(x) LOG(NT_LOG_ERROR, x)
65 #define WARNING(x) LOG(NT_LOG_WARNING, x)
66 #define INFO(x) LOG(NT_LOG_INFO, x)
67 
68 #ifdef NDEBUG
69 #define DEBUG(x) do {} while (0)
70 #define DEBUG1(x) do {} while (0)
71 #define DEBUG2(x) do {} while (0)
72 #define DEBUG3(x) do {} while (0)
73 #define DEBUG4(x) do {} while (0)
74 #else
75 #define DEBUG(x) LOG(NT_LOG_DEBUG, x)
76 #define DEBUG1(x) LOG(NT_LOG_DEBUG1, x)
77 #define DEBUG2(x) LOG(NT_LOG_DEBUG2, x)
78 #define DEBUG3(x) LOG(NT_LOG_DEBUG3, x)
79 #define DEBUG4(x) LOG(NT_LOG_DEBUG4, x)
80 #endif
81 
82 } // namespace nt
83 
84 #endif // NT_LOG_H_
Definition: Log.hpp:17
Definition: Log.h:20