SILICON
Loading...
Searching...
No Matches
logger.cpp
Go to the documentation of this file.
1#include "logger.hpp"
2
3#include <atomic>
4#include <map>
5#include <mutex>
6#include <ostream>
7#include <string>
8#include <string_view>
9#include <utility>
10
11#include <boost/core/null_deleter.hpp>
12#include <boost/log/attributes/current_thread_id.hpp>
13#include <boost/log/attributes/value_extraction.hpp>
14#include <boost/log/core.hpp>
15#include <boost/log/expressions.hpp>
16#include <boost/log/keywords/channel.hpp>
17#include <boost/log/sinks/basic_sink_backend.hpp>
18#include <boost/log/sinks/sync_frontend.hpp>
19#include <boost/log/sinks/text_ostream_backend.hpp>
20#include <boost/log/sources/record_ostream.hpp>
21#include <boost/log/sources/severity_channel_logger.hpp>
22#include <boost/log/support/date_time.hpp>
23#include <boost/log/trivial.hpp>
24#include <boost/log/utility/setup/common_attributes.hpp>
25#include <boost/make_shared.hpp>
26
28
29namespace logging = boost::log;
30namespace sinks = boost::log::sinks;
31namespace src = boost::log::sources;
32namespace expr = boost::log::expressions;
33namespace attrs = boost::log::attributes;
34namespace keywords = boost::log::keywords;
35
36namespace {
37
38 using Severity = logging::trivial::severity_level;
39 using ChannelLogger = src::severity_channel_logger_mt<Severity, std::string>;
40 using ConsoleSink = sinks::synchronous_sink<sinks::text_ostream_backend>;
41
42 LogLevel fromBoostSeverity(Severity level);
43
44 class CallbackSinkBackend
45 : public sinks::basic_formatted_sink_backend<char, sinks::synchronized_feeding> {
46 public:
47 explicit CallbackSinkBackend(Logger::CallbackSink callback)
48 : callback(std::move(callback))
49 {
50 }
51
52 void consume(const logging::record_view& rec, const string_type& formatted)
53 {
54 if (!callback)
55 return;
56
57 const auto severityRef = rec[logging::trivial::severity];
58 const auto channelRef = rec.attribute_values()["Channel"].extract<std::string>();
59 const auto rawMessageRef = rec.attribute_values()["Message"].extract<std::string>();
60
61 const LogMessage logMessage{
62 .level = severityRef ? fromBoostSeverity(*severityRef) : LogLevel::Info,
63 .category = channelRef ? *channelRef : std::string{},
64 .message = rawMessageRef ? *rawMessageRef : formatted,
65 .formatted = formatted,
66 };
67
68 callback(logMessage);
69 }
70
71 private:
72 Logger::CallbackSink callback;
73 };
74
75 using CallbackFrontendSink = sinks::synchronous_sink<CallbackSinkBackend>;
76
77 Severity toBoostSeverity(const LogLevel level)
78 {
79 switch (level) {
80 case LogLevel::Trace: return logging::trivial::trace;
81 case LogLevel::Debug: return logging::trivial::debug;
82 case LogLevel::Info: return logging::trivial::info;
83 case LogLevel::Warning: return logging::trivial::warning;
84 case LogLevel::Error: return logging::trivial::error;
85 case LogLevel::Critical: return logging::trivial::fatal;
86 }
87
88 return logging::trivial::info;
89 }
90
91 LogLevel fromBoostSeverity(const Severity level)
92 {
93 switch (level) {
94 case logging::trivial::trace: return LogLevel::Trace;
95 case logging::trivial::debug: return LogLevel::Debug;
96 case logging::trivial::info: return LogLevel::Info;
97 case logging::trivial::warning: return LogLevel::Warning;
98 case logging::trivial::error: return LogLevel::Error;
99 case logging::trivial::fatal: return LogLevel::Critical;
100 }
101
102 return LogLevel::Info;
103 }
104
105 struct LoggingState {
106 std::mutex mutex;
107 bool initialized = false;
108 bool commonAttrsAdded = false;
109 LogLevel minimumLevel = LogLevel::Info;
110 boost::shared_ptr<ConsoleSink> consoleSink;
111 std::map<Logger::SinkHandle, boost::shared_ptr<logging::sinks::sink>> callbackSinks;
112 std::atomic<Logger::SinkHandle> nextSinkHandle{1};
113 };
114
115 LoggingState& state()
116 {
117 static LoggingState value;
118 return value;
119 }
120
121 const char* toLevelString(const LogLevel level)
122 {
123 switch (level) {
124 case LogLevel::Trace: return "TRACE";
125 case LogLevel::Debug: return "DEBUG";
126 case LogLevel::Info: return "INFO";
127 case LogLevel::Warning: return "WARNING";
128 case LogLevel::Error: return "ERROR";
129 case LogLevel::Critical: return "CRITICAL";
130 }
131
132 return "INFO";
133 }
134
135 auto makeFormatter()
136 {
137 return expr::stream << "["
138 << expr::format_date_time<boost::posix_time::ptime>(
139 "TimeStamp", "%Y-%m-%d %H:%M:%S.%f")
140 << "]" << " [" << logging::trivial::severity << "]" << " ["
141 << expr::attr<std::string>("Channel") << "] " << expr::smessage;
142 }
143
144 void applyFilter()
145 {
146 logging::core::get()->set_filter(logging::trivial::severity
147 >= toBoostSeverity(state().minimumLevel));
148 }
149
150 void ensureInitializedLocked(LoggingState& loggingState)
151 {
152 if (loggingState.initialized)
153 return;
154
155 if (!loggingState.commonAttrsAdded) {
156 logging::add_common_attributes();
157 loggingState.commonAttrsAdded = true;
158 }
159
160 applyFilter();
161 loggingState.initialized = true;
162 }
163
164 void writeRecord(const LogLevel level, std::string_view category,
165 std::string_view message)
166 {
167 ChannelLogger logger(keywords::channel = std::string(category));
168 BOOST_LOG_SEV(logger, toBoostSeverity(level)) << message;
169 }
170
171} // namespace
172
173std::ostream& operator<<(std::ostream& stream, const LogLevel level)
174{
175 return stream << toLevelString(level);
176}
177
178Logger::Logger(std::string category) : category(std::move(category)) {}
179
181{
182 auto& loggingState = state();
183 const std::lock_guard lock(loggingState.mutex);
184 ensureInitializedLocked(loggingState);
185}
186
188{
189 auto& loggingState = state();
190 const std::lock_guard lock(loggingState.mutex);
191
192 auto& core = *logging::core::get();
193 if (loggingState.consoleSink) {
194 core.remove_sink(loggingState.consoleSink);
195 loggingState.consoleSink->flush();
196 loggingState.consoleSink.reset();
197 }
198
199 for (auto& [handle, sink] : loggingState.callbackSinks) {
200 (void)handle;
201 core.remove_sink(sink);
202 sink->flush();
203 }
204 loggingState.callbackSinks.clear();
205 loggingState.initialized = false;
206}
207
208void Logger::addConsoleSink(std::ostream& stream)
209{
210 auto& loggingState = state();
211 const std::lock_guard lock(loggingState.mutex);
212 ensureInitializedLocked(loggingState);
213
214 auto& core = *logging::core::get();
215 if (loggingState.consoleSink) {
216 core.remove_sink(loggingState.consoleSink);
217 loggingState.consoleSink->flush();
218 loggingState.consoleSink.reset();
219 }
220
221 auto backend = boost::make_shared<sinks::text_ostream_backend>();
222 backend->add_stream(boost::shared_ptr<std::ostream>(&stream, boost::null_deleter{}));
223 backend->auto_flush(true);
224
225 auto sink = boost::make_shared<ConsoleSink>(backend);
226 sink->set_formatter(makeFormatter());
227 core.add_sink(sink);
228 loggingState.consoleSink = sink;
229}
230
232{
233 auto& loggingState = state();
234 const std::lock_guard lock(loggingState.mutex);
235 loggingState.minimumLevel = level;
236 ensureInitializedLocked(loggingState);
237 applyFilter();
238}
239
241{
242 auto& loggingState = state();
243 const std::lock_guard lock(loggingState.mutex);
244 ensureInitializedLocked(loggingState);
245
246 auto backend = boost::make_shared<CallbackSinkBackend>(std::move(callback));
247 auto sink = boost::make_shared<CallbackFrontendSink>(backend);
248 sink->set_formatter(makeFormatter());
249
250 logging::core::get()->add_sink(sink);
251
252 const SinkHandle handle =
253 loggingState.nextSinkHandle.fetch_add(1, std::memory_order_relaxed);
254 loggingState.callbackSinks.emplace(handle, sink);
255 return handle;
256}
257
259{
260 auto& loggingState = state();
261 const std::lock_guard lock(loggingState.mutex);
262
263 const auto it = loggingState.callbackSinks.find(handle);
264 if (it == loggingState.callbackSinks.end())
265 return;
266
267 logging::core::get()->remove_sink(it->second);
268 it->second->flush();
269 loggingState.callbackSinks.erase(it);
270}
271
272void Logger::trace(std::string_view category, std::string_view message)
273{
274 log(LogLevel::Trace, category, message);
275}
276
277void Logger::debug(std::string_view category, std::string_view message)
278{
279 log(LogLevel::Debug, category, message);
280}
281
282void Logger::info(std::string_view category, std::string_view message)
283{
284 log(LogLevel::Info, category, message);
285}
286
287void Logger::warning(std::string_view category, std::string_view message)
288{
289 log(LogLevel::Warning, category, message);
290}
291
292void Logger::error(std::string_view category, std::string_view message)
293{
294 log(LogLevel::Error, category, message);
295}
296
297void Logger::critical(std::string_view category, std::string_view message)
298{
300}
301
302void Logger::trace(std::string_view message) const
303{
304 log(LogLevel::Trace, category, message);
305}
306
307void Logger::debug(std::string_view message) const
308{
309 log(LogLevel::Debug, category, message);
310}
311
312void Logger::info(std::string_view message) const
313{
314 log(LogLevel::Info, category, message);
315}
316
317void Logger::warning(std::string_view message) const
318{
319 log(LogLevel::Warning, category, message);
320}
321
322void Logger::error(const std::string_view message) const
323{
324 log(LogLevel::Error, category, message);
325}
326
327void Logger::critical(const std::string_view message) const
328{
330}
331
332void Logger::log(const LogLevel level, std::string_view category,
333 std::string_view message)
334{
335 initialize();
336 writeRecord(level, category, message);
337}
338
339} // namespace SILICON::logging
static void error(std::string_view category, std::string_view message)
Definition logger.cpp:292
static void initialize()
Definition logger.cpp:180
static SinkHandle addCallbackSink(CallbackSink callback)
Definition logger.cpp:240
static void setMinimumLevel(LogLevel level)
Definition logger.cpp:231
std::size_t SinkHandle
Definition logger.hpp:28
static void removeSink(SinkHandle handle)
Definition logger.cpp:258
static void warning(std::string_view category, std::string_view message)
Definition logger.cpp:287
static void trace(std::string_view category, std::string_view message)
Definition logger.cpp:272
static void shutdown()
Definition logger.cpp:187
static void critical(std::string_view category, std::string_view message)
Definition logger.cpp:297
Logger(std::string category)
Definition logger.cpp:178
static void debug(std::string_view category, std::string_view message)
Definition logger.cpp:277
static void info(std::string_view category, std::string_view message)
Definition logger.cpp:282
std::function< void(const LogMessage &)> CallbackSink
Definition logger.hpp:29
static void addConsoleSink(std::ostream &stream)
Definition logger.cpp:208
static void log(LogLevel level, std::string_view category, std::string_view message)
Definition logger.cpp:332
std::ostream & operator<<(std::ostream &stream, const LogLevel level)
Definition logger.cpp:173