File indexing completed on 2024-11-24 03:56:26
0001 /* 0002 * SPDX-FileCopyrightText: 2019-2023 Mattia Basaglia <dev@dragon.best> 0003 * 0004 * SPDX-License-Identifier: GPL-3.0-or-later 0005 */ 0006 0007 #pragma once 0008 0009 #include <memory> 0010 0011 #include <QObject> 0012 0013 #include "app/log/log_line.hpp" 0014 0015 namespace app::log { 0016 0017 class Logger; 0018 0019 class LogListener 0020 { 0021 public: 0022 LogListener() {} 0023 virtual ~LogListener() = default; 0024 0025 protected: 0026 virtual void on_line(const LogLine& line) = 0; 0027 0028 friend class Logger; 0029 }; 0030 0031 class Logger : public QObject 0032 { 0033 Q_OBJECT 0034 0035 public: 0036 static QString severity_name(Severity s) 0037 { 0038 switch ( s ) 0039 { 0040 case Info: 0041 return "Info"; 0042 case Warning: 0043 return "Warning"; 0044 case Error: 0045 return "Error"; 0046 default: 0047 return "?"; 0048 } 0049 } 0050 0051 static Logger& instance() 0052 { 0053 static Logger instance; 0054 return instance; 0055 } 0056 0057 template<class T, class... Args> 0058 T* add_listener(Args&&... args) 0059 { 0060 listeners.push_back(std::make_unique<T>(std::forward<Args>(args)...)); 0061 return static_cast<T*>(listeners.back().get()); 0062 } 0063 0064 public Q_SLOTS: 0065 void log(const LogLine& line) 0066 { 0067 for ( const auto& listener : listeners ) 0068 listener->on_line(line); 0069 Q_EMIT logged(line); 0070 } 0071 0072 Q_SIGNALS: 0073 void logged(const LogLine& line); 0074 0075 private: 0076 Logger() = default; 0077 ~Logger() = default; 0078 std::vector<std::unique_ptr<LogListener>> listeners; 0079 }; 0080 0081 } // namespace app::log