I have asked on thread, but seems no good solutions. And I know limitations of current way. But, I wanna try once more here.
Please note I'm using spdlog for logging.
I meet a problem when I logging to qt widget QTextEdit
with different color.
Sequence of logs are wrong.
Here my logs within QTextEdit
[I][7738][2023/06/06 07:55:14:907][device] Parse information.
[E][7731][2023/06/06 07:55:14:908] [device] Add pack wrong!
[E][7731][2023/06/06 07:55:14:909] [device] error!
[I][7738][2023/06/06 07:55:14:906][device] Receive from tcp server.
But within logged file ( same within std::out):
[I][7738][2023/06/06 07:55:14:906][device] Receive from tcp server.
[I][7738][2023/06/06 07:55:14:907][device] Parse information.
[E][7731][2023/06/06 07:55:14:908] [device] Add pack wrong!
[E][7731][2023/06/06 07:55:14:909] [device] error!
We can learn from logs( by timestamp) that the order of logs within QTextEditor
is wrong.
Here is my implement of qt_sink
:
template <typename Mutex>
class QtSink: public spdlog::sinks::qt_sink<Mutex>
{
public:
QtSink(QTextEdit *object = nullptr, const std::string &meta_method = ""):
spdlog::sinks::qt_sink<Mutex>(object, meta_method),
_editor(object)
{}
~QtSink() = default;
protected:
void sink_it_(const spdlog::details::log_msg &msg) override {
if(!_editor) return;
spdlog::level::level_enum level = msg.level;
switch(level)
{
case spdlog::level::trace:
_editor->setTextColor(Qt::darkGray);
break;
case spdlog::level::debug:
_editor->setTextColor(Qt::lightGray);
break;
case spdlog::level::info:
_editor->setTextColor(Qt::green);
break;
case spdlog::level::warn:
_editor->setTextColor(Qt::yellow);
break;
case spdlog::level::err:
_editor->setTextColor(Qt::red);
break;
case spdlog::level::critical:
_editor->setTextColor(Qt::darkRed);
break;
default:
break;
}
spdlog::sinks::qt_sink<Mutex>::sink_it_(msg);
}
private:
QTextEdit * _editor;
};
using QtSinkMt = QtSink<std::mutex>;
typedef std::shared_ptr<QtSinkMt> QtSinkMtPtr;
And here I instant that sink:
_qtSink = std::make_shared<QtSinkMt>(view,"append");
_qtSink->set_pattern(pattern.c_str());
_qtSink->set_level(spdlog::level::debug);
_sysLogger->sinks().push_back(_qtSink);
_sysLogger->info("Log Viewer Init Done!");
So, what wrong with that codes.