summaryrefslogtreecommitdiffstats
path: root/common/log.cpp
blob: 1d934046507c31b28a07bf360f26cb464bbf5a70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "log.h"

#include <QString>
#include <QIODevice>
#include <QCoreApplication>
#include <iostream>
#include <unistd.h>

class DebugStream: public QIODevice
{
public:
    QString m_location;
    DebugStream()
        : QIODevice()
    {
        open(WriteOnly);
    }
    virtual ~DebugStream(){};

    bool isSequential() const { return true; }
    qint64 readData(char *, qint64) { return 0; /* eof */ }
    qint64 readLineData(char *, qint64) { return 0; /* eof */ }
    qint64 writeData(const char *data, qint64 len)
    {
        const QByteArray buf = QByteArray::fromRawData(data, len);
        // if (!qgetenv("IMAP_TRACE").isEmpty()) {
            // qt_message_output(QtDebugMsg, buf.trimmed().constData());
            std::cout << buf.trimmed().constData() << std::endl;
        // }
        return len;
    }
private:
    Q_DISABLE_COPY(DebugStream)
};

QDebug debugStream(DebugLevel debugLevel, int line, const char* file, const char* function)
{
    static DebugStream stream;
    QDebug debug(&stream);

    static QByteArray programName;
    if (programName.isEmpty()) {
        if (QCoreApplication::instance())
            programName = QCoreApplication::instance()->applicationName().toLocal8Bit();
        else
            programName = "<unknown program name>";
    }

    QString prefix;
    switch (debugLevel) {
        case DebugLevel::Trace:
            prefix = "Trace:";
            break;
        case DebugLevel::Log:
            prefix = "Log:";
            break;
        case DebugLevel::Warning:
            prefix = "Warning:";
            break;
        case DebugLevel::Error:
            prefix = "Error:";
            break;
        default:
            break;
    };

    debug << prefix + QString(" %1(%2) %3:").arg(QString::fromLatin1(programName)).arg(unsigned(getpid())).arg(function) /* << file << ":" << line */;

    return debug;
}