SILICON
Loading...
Searching...
No Matches
graphicalLogStream.cpp
Go to the documentation of this file.
2
3#include <mutex>
4#include <string>
5
6#include <QMetaObject>
7#include <QString>
8
9#include <boost/log/attributes/value_extraction.hpp>
10#include <boost/log/core.hpp>
11#include <boost/log/expressions.hpp>
12#include <boost/log/sinks/basic_sink_backend.hpp>
13#include <boost/log/sinks/sync_frontend.hpp>
14#include <boost/log/support/date_time.hpp>
15#include <boost/log/trivial.hpp>
16#include <boost/make_shared.hpp>
17
18
19namespace SILICON::ui {
20
21namespace logging = boost::log;
22namespace expr = boost::log::expressions;
23
24namespace {
25
26class GraphicalLogBackend : public boost::log::sinks::basic_formatted_sink_backend<
27 char, boost::log::sinks::synchronized_feeding> {
28public:
29 explicit GraphicalLogBackend(GraphicalLogStream* owner) : owner(owner) {}
30
31 void disconnect()
32 {
33 const std::lock_guard lock(mutex);
34 owner = nullptr;
35 }
36
37 void consume(const logging::record_view&, const string_type& formatted)
38 {
39 GraphicalLogStream* owner = nullptr;
40 {
41 const std::lock_guard lock(mutex);
42 owner = this->owner;
43 }
44
45 if (!owner)
46 return;
47
48 const auto line =
49 QString::fromUtf8(formatted.c_str(), static_cast<qsizetype>(formatted.size()));
50 QMetaObject::invokeMethod(
51 owner, [owner, line] { emit owner->lineReceived(line); }, Qt::QueuedConnection);
52 }
53
54private:
55 std::mutex mutex;
56 GraphicalLogStream* owner;
57};
58
59using GraphicalSink = boost::log::sinks::synchronous_sink<GraphicalLogBackend>;
60
61auto makeFormatter()
62{
63 return expr::stream << "["
64 << expr::format_date_time<boost::posix_time::ptime>(
65 "TimeStamp", "%Y-%m-%d %H:%M:%S")
66 << "]" << " [" << logging::trivial::severity << "]" << " ["
67 << expr::attr<std::string>("Channel") << "] " << expr::smessage;
68}
69
70} // namespace
71
72GraphicalLogStream::GraphicalLogStream(QObject* parent) : QObject(parent) {}
73
78
80{
81 if (sink)
82 return;
83
84 auto backend = boost::make_shared<GraphicalLogBackend>(this);
85 auto sinkPtr = boost::make_shared<GraphicalSink>(backend);
86 sinkPtr->set_formatter(makeFormatter());
87 logging::core::get()->add_sink(sinkPtr);
88 sink = sinkPtr;
89}
90
92{
93 if (!sink)
94 return;
95
96 logging::core::get()->remove_sink(sink);
97
98 if (const auto typedSink = boost::dynamic_pointer_cast<GraphicalSink>(sink)) {
99 typedSink->locked_backend()->disconnect();
100 typedSink->flush();
101 }
102
103 sink.reset();
104}
105
106} // namespace SILICON::ui
boost::shared_ptr< boost::log::sinks::sink > sink
GraphicalLogStream(QObject *parent=nullptr)