RhythmGame 1.4.3
Loading...
Searching...
No Matches
QtSink.h
Go to the documentation of this file.
1//
2// Created by PC on 14/08/2025.
3//
4
5#ifndef RHYTHMGAME_QTSINK_H
6#define RHYTHMGAME_QTSINK_H
7
8#include <QObject>
9#include <mutex>
10#include <spdlog/logger.h>
11#include <spdlog/sinks/base_sink.h>
12#include <spdlog/details/log_msg.h>
13#include <spdlog/details/synchronous_factory.h>
14
15namespace support {
16
17template <typename Mutex>
18class QtSink : public spdlog::sinks::base_sink<Mutex> {
19public:
20 QtSink(QObject *qt_object, std::string meta_method)
21 : qt_object_(qt_object),
22 meta_method_(std::move(meta_method)) {
23 if (!qt_object_) {
24 spdlog::throw_spdlog_ex("qt_sink: qt_object is null");
25 }
26 }
27
28 ~QtSink() override { QtSink::flush_(); }
29
30protected:
31 void sink_it_(const spdlog::details::log_msg &msg) override {
32 spdlog::memory_buf_t formatted;
33 spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
34 const auto str = spdlog::string_view_t(formatted.data(), formatted.size());
35 QMetaObject::invokeMethod(
36 qt_object_, meta_method_.c_str(), Qt::AutoConnection,
37 Q_ARG(QString, QString::fromUtf8(str.data(), static_cast<int>(str.size())).trimmed()));
38 }
39
40 void flush_() override {}
41
42private:
43 QObject *qt_object_ = nullptr;
44 std::string meta_method_;
45};
46
48
49template <typename Factory = spdlog::synchronous_factory>
50inline std::shared_ptr<spdlog::logger> qtLoggerMt(const std::string &logger_name,
51 QObject *qt_object,
52 const std::string &meta_method) {
53 return Factory::template create<QtSinkMt>(logger_name, qt_object, meta_method);
54}
55
56} // namespace support
57
58#endif // RHYTHMGAME_QTSINK_H
Definition QtSink.h:18
~QtSink() override
Definition QtSink.h:28
void sink_it_(const spdlog::details::log_msg &msg) override
Definition QtSink.h:31
void flush_() override
Definition QtSink.h:40
QtSink(QObject *qt_object, std::string meta_method)
Definition QtSink.h:20
Contains various helper classes and functions.
Definition Capitalize.h:9
std::shared_ptr< spdlog::logger > qtLoggerMt(const std::string &logger_name, QObject *qt_object, const std::string &meta_method)
Definition QtSink.h:50