libdisplaydevice v2026.322.2407
C++ library to modify display devices.
logging.h
Go to the documentation of this file.
1
5#pragma once
6
7// system includes
8#include <functional>
9#include <sstream>
10#include <string>
11
12namespace display_device {
21 class Logger {
22 public:
28 enum class LogLevel {
29 verbose = 0,
30 debug,
31 info,
32 warning,
33 error,
34 fatal
35 };
36
40 using Callback = std::function<void(LogLevel, std::string)>;
41
49 static Logger &get();
50
58 void setLogLevel(LogLevel log_level);
59
68 [[nodiscard]] bool isLogLevelEnabled(LogLevel log_level) const;
69
79 void setCustomCallback(Callback callback);
80
89 void write(LogLevel log_level, std::string value);
90
95 Logger(Logger const &) = delete;
96
101 void operator=(Logger const &) = delete;
102
103 private:
107 explicit Logger();
108
109 LogLevel m_enabled_log_level;
110 Callback m_custom_callback;
111 };
112
116 class LogWriter {
117 public:
122 explicit LogWriter(Logger::LogLevel log_level);
123
127 virtual ~LogWriter();
128
134 template<class T>
135 LogWriter &operator<<(T &&value) {
136 m_buffer << std::forward<T>(value);
137 return *this;
138 }
139
140 private:
141 Logger::LogLevel m_log_level;
142 std::ostringstream m_buffer;
143 };
144} // namespace display_device
145
153#define DD_LOG(level) \
154 for (bool is_enabled {display_device::Logger::get().isLogLevelEnabled(display_device::Logger::LogLevel::level)}; is_enabled; is_enabled = false) \
155 display_device::LogWriter(display_device::Logger::LogLevel::level)
A helper class for accumulating output via the stream operator and then writing it out at once.
Definition logging.h:116
virtual ~LogWriter()
Write out the accumulated output.
Definition logging.cpp:118
LogWriter & operator<<(T &&value)
Stream value to the buffer.
Definition logging.h:135
LogWriter(Logger::LogLevel log_level)
Constructor scoped writer utility.
Definition logging.cpp:115
A singleton class for logging or re-routing logs.
Definition logging.h:21
void setLogLevel(LogLevel log_level)
Set the log level for the logger.
Definition logging.cpp:39
static Logger & get()
Get the singleton instance.
Definition logging.cpp:34
void write(LogLevel log_level, std::string value)
Write the string to the output (via callback) if the log level is enabled.
Definition logging.cpp:53
Logger(Logger const &)=delete
A deleted copy constructor for singleton pattern.
std::function< void(LogLevel, std::string)> Callback
Defines the callback type for log data re-routing.
Definition logging.h:40
bool isLogLevelEnabled(LogLevel log_level) const
Check if log level is currently enabled.
Definition logging.cpp:43
LogLevel
Defines the possible log levels.
Definition logging.h:28
void setCustomCallback(Callback callback)
Set custom callback for writing the logs.
Definition logging.cpp:49
void operator=(Logger const &)=delete
A deleted assignment operator for singleton pattern.