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 <QTextStream>
0010 
0011 #include "app/log/logger.hpp"
0012 
0013 namespace app::log {
0014 
0015 class LogStream
0016 {
0017 public:
0018     LogStream(const QString& source, const QString& detail = "", Severity severity = Warning)
0019         : source(source), detail(detail), severity(severity)
0020     {}
0021 
0022     ~LogStream()
0023     {
0024         if ( !message.isEmpty() )
0025             Logger::instance().log({severity, source, detail, message, QDateTime::currentDateTime()});
0026     }
0027 
0028     template<class T>
0029     LogStream& operator<<(T&& item)
0030     {
0031         if ( !message.isEmpty() )
0032             str << ' ';
0033         str << std::forward<T>(item);
0034         return *this;
0035     }
0036 
0037 private:
0038     QString source;
0039     QString detail;
0040     Severity severity;
0041     QString message;
0042     QTextStream str{&message};
0043 };
0044 
0045 class Log
0046 {
0047 public:
0048     Log(const QString& source, const QString& detail="")
0049     : source(source), detail(detail)
0050     {}
0051 
0052     const Log& log(const QString& message, Severity severity = Warning) const
0053     {
0054         Logger::instance().log({severity, source, detail, message, QDateTime::currentDateTime()});
0055         return *this;
0056     }
0057 
0058     void operator()(const QString& message, Severity severity = Warning)
0059     {
0060         log(message, severity);
0061     }
0062 
0063     void set_detail(const QString& detail)
0064     {
0065         this->detail = detail;
0066     }
0067 
0068     LogStream stream(Severity severity = Warning) const
0069     {
0070         return LogStream(source, detail, severity);
0071     }
0072 
0073 private:
0074     QString source;
0075     QString detail;
0076 };
0077 
0078 } // namespace app::log