Subversion Repositories tpanel

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 andreas 1
/*
21 andreas 2
 * Copyright (C) 2020, 2021 by Andreas Theofilu <andreas@theosys.at>
2 andreas 3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program; if not, write to the Free Software Foundation,
16
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
17
 */
18
#include <iostream>
19
#include <fstream>
20
#include <sstream>
21
#include <ios>
22
#include <time.h>
14 andreas 23
#include <mutex>
289 andreas 24
#include <thread>
306 andreas 25
//#ifdef __APPLE__
26
//#include <unistd.h>
27
//#include <sys/syscall.h>
28
//#endif
14 andreas 29
 
386 andreas 30
#include <QMessageBox>
31
#include <QTimer>
32
 
2 andreas 33
#include "terror.h"
34
#include "tconfig.h"
35
 
406 andreas 36
#if __cplusplus < 201402L
37
#   error "This module requires at least C++ 14 standard!"
38
#else
39
#   if __cplusplus < 201703L
40
#       include <experimental/filesystem>
41
namespace fs = std::experimental::filesystem;
42
#       warning "Support for C++14 and experimental filesystem will be removed in a future version!"
43
#   else
44
#       include <filesystem>
45
#       ifdef __ANDROID__
46
namespace fs = std::__fs::filesystem;
47
#       else
48
namespace fs = std::filesystem;
49
#       endif
50
#   endif
51
#endif
235 andreas 52
 
23 andreas 53
#if LOGPATH == LPATH_SYSLOG || defined(__ANDROID__)
22 andreas 54
#   ifdef __ANDROID__
55
#       include <android/log.h>
56
#   else
57
#       include <syslog.h>
386 andreas 58
#       ifdef __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__
59
#           include "ios/QASettings.h"
60
#       endif
22 andreas 61
#   endif
62
#endif
63
 
242 andreas 64
#define LOGBUFFER_SIZE      4096
65
 
2 andreas 66
using std::string;
292 andreas 67
using std::mutex;
68
 
14 andreas 69
std::mutex message_mutex;
305 andreas 70
std::mutex _macro_mutex;
2 andreas 71
 
242 andreas 72
bool TError::mHaveError{false};
73
terrtype_t TError::mErrType{TERRNONE};
74
TStreamError *TError::mCurrent{nullptr};
2 andreas 75
std::string TError::msError;
315 andreas 76
#ifdef __ANDROID__
77
threadID_t TError::mThreadID;
78
#else
306 andreas 79
threadID_t TError::mThreadID{0};
315 andreas 80
#endif
2 andreas 81
 
242 andreas 82
int TStreamError::mIndent{1};
83
std::ostream *TStreamError::mStream{nullptr};
84
std::filebuf TStreamError::mOfStream;
85
char *TStreamError::mBuffer{nullptr};
2 andreas 86
std::string TStreamError::mLogfile;
242 andreas 87
bool TStreamError::mInitialized{false};
88
unsigned int TStreamError::mLogLevel{HLOG_PROTOCOL};
250 andreas 89
unsigned int TStreamError::mLogLevelOld{HLOG_NONE};
90
bool TStreamError::haveTemporaryLogLevel{false};
385 andreas 91
#ifdef __ANDROID__
92
bool TStreamError::mLogFileEnabled{false};
93
#else
94
bool TStreamError::mLogFileEnabled{true};
95
#endif
2 andreas 96
 
306 andreas 97
string _threadIDtoStr(threadID_t tid)
304 andreas 98
{
99
    std::stringstream s;
100
    s << std::hex << std::setw(8) << std::setfill('0') << tid;
101
    return s.str();
102
}
103
 
306 andreas 104
threadID_t _getThreadID()
105
{
106
#ifdef __APPLE__
107
//    threadID_t tid;
108
//    return pthread_threadid_np(NULL, &tid);
109
    return pthread_mach_thread_np(pthread_self());
110
//    return syscall(SYS_thread_selfid);
111
#else
112
    return std::this_thread::get_id();
113
#endif
114
}
115
 
305 andreas 116
void _lock()
117
{
118
    _macro_mutex.lock();
119
}
120
 
121
void _unlock()
122
{
123
    _macro_mutex.unlock();
124
}
125
 
23 andreas 126
#if LOGPATH == LPATH_SYSLOG || defined(__ANDROID__)
127
class androidbuf : public std::streambuf
128
{
129
    public:
142 andreas 130
        enum { bufsize = 1024 };
23 andreas 131
        androidbuf() { this->setp(buffer, buffer + bufsize - 1); }
132
 
133
    private:
134
        int overflow(int c)
135
        {
136
            if (c == traits_type::eof())
137
            {
138
                *this->pptr() = traits_type::to_char_type(c);
139
                this->sbumpc();
140
            }
141
 
142
            return this->sync()? traits_type::eof(): traits_type::not_eof(c);
143
        }
144
 
145
        int sync()
146
        {
147
            int rc = 0;
148
 
149
            if (this->pbase() != this->pptr())
150
            {
151
                char writebuf[bufsize+1];
152
                memcpy(writebuf, this->pbase(), this->pptr() - this->pbase());
153
                writebuf[this->pptr() - this->pbase()] = '\0';
154
                int eType;
155
#ifdef __ANDROID__
156
                switch(TError::getErrorType())
157
                {
158
                    case TERRINFO:      eType = ANDROID_LOG_INFO; break;
159
                    case TERRWARNING:   eType = ANDROID_LOG_WARN; break;
160
                    case TERRERROR:     eType = ANDROID_LOG_ERROR; break;
161
                    case TERRTRACE:     eType = ANDROID_LOG_VERBOSE; break;
162
                    case TERRDEBUG:     eType = ANDROID_LOG_DEBUG; break;
26 andreas 163
                    case TERRNONE:      eType = ANDROID_LOG_INFO; break;
23 andreas 164
                }
165
 
166
                rc = __android_log_print(eType, "tpanel", "%s", writebuf) > 0;
167
#else
386 andreas 168
#ifdef Q_OS_IOS
169
                QASettings::writeLog(TError::getErrorType(), writebuf);
170
#else
23 andreas 171
                switch(TError::getErrorType())
172
                {
173
                    case TERRINFO:      eType = LOG_INFO; break;
386 andreas 174
                    case TERRWARNING:   eType = LOG_WARNING; break;
175
                    case TERRERROR:     eType = LOG_ERR; break;
23 andreas 176
                    case TERRTRACE:     eType = LOG_INFO; break;
177
                    case TERRDEBUG:     eType = LOG_DEBUG; break;
178
                    case TERRNONE:      eType = LOG_INFO; break;
179
                }
180
 
386 andreas 181
                syslog(eType, "(tpanel) %s", writebuf);
26 andreas 182
                rc = 1;
386 andreas 183
#endif  // Q_OS_IOS
184
#endif  // __ANDROID__
23 andreas 185
                this->setp(buffer, buffer + bufsize - 1);
186
            }
22 andreas 187
 
23 andreas 188
            return rc;
189
        }
190
 
191
        char buffer[bufsize];
192
};
193
#endif
194
 
2 andreas 195
TStreamError::TStreamError(const string& logFile, const std::string& logLevel)
196
{
116 andreas 197
    if (!TConfig::isInitialized())
198
        return;
199
 
14 andreas 200
    if (!logFile.empty())
23 andreas 201
        mLogfile = logFile;
14 andreas 202
    else if (!TConfig::getLogFile().empty())
23 andreas 203
        mLogfile = TConfig::getLogFile();
2 andreas 204
 
14 andreas 205
    if (!logLevel.empty())
206
        setLogLevel(logLevel);
207
    else if (!TConfig::getLogLevel().empty())
414 andreas 208
        setLogLevel(TConfig::getLogLevel());
2 andreas 209
 
14 andreas 210
    _init();
2 andreas 211
}
212
 
213
TStreamError::~TStreamError()
214
{
242 andreas 215
    if (mOfStream.is_open())
216
        mOfStream.close();
243 andreas 217
 
242 andreas 218
    if (mStream)
14 andreas 219
    {
220
        delete mStream;
221
        mStream = nullptr;
222
    }
242 andreas 223
 
224
    if (mBuffer)
225
        delete mBuffer;
226
 
227
    mInitialized = false;
2 andreas 228
}
229
 
23 andreas 230
void TStreamError::setLogFile(const std::string &lf)
231
{
239 andreas 232
#ifdef Q_OS_IOS
233
    if (!lf.empty())
234
    {
243 andreas 235
        if ((!mLogfile.empty() && mLogfile != lf) || mLogfile.empty())
239 andreas 236
            mLogfile = lf;
237
    }
238
 
239
    if (!mInitialized)
240
        _init();
241
#else
383 andreas 242
#ifndef __ANDROID__
116 andreas 243
    if (mInitialized && mLogfile.compare(lf) == 0)
23 andreas 244
        return;
383 andreas 245
#endif
23 andreas 246
    mLogfile = lf;
247
    mInitialized = false;
248
    _init();
239 andreas 249
#endif
23 andreas 250
}
251
 
2 andreas 252
void TStreamError::setLogLevel(const std::string& slv)
253
{
14 andreas 254
    size_t pos = slv.find("|");
255
    size_t start = 0;
256
    string lv;
257
    mLogLevel = 0;
2 andreas 258
 
14 andreas 259
    while (pos != string::npos)
260
    {
261
        lv = slv.substr(start, pos - start);
262
        start = pos + 1;
263
        mLogLevel |= _getLevel(lv);
264
        pos = slv.find("|", start);
265
    }
2 andreas 266
 
14 andreas 267
    mLogLevel |= _getLevel(slv.substr(start));
260 andreas 268
#ifdef __ANDROID__
269
    __android_log_print(ANDROID_LOG_INFO, "tpanel", "TStreamError::setLogLevel: New loglevel: %s", slv.c_str());
270
#else
414 andreas 271
    if (mInitialized && mStream)
272
        *mStream << TError::append(HLOG_INFO) << "New loglevel: " << slv << std::endl;
261 andreas 273
    else
274
        std::cout << TError::append(HLOG_INFO) << "New loglevel: " << slv << std::endl;
260 andreas 275
#endif
2 andreas 276
}
277
 
278
bool TStreamError::checkFilter(terrtype_t err)
279
{
116 andreas 280
    if (!TConfig::isInitialized())
281
        return false;
282
 
23 andreas 283
    if (err == TERRINFO && (mLogLevel & HLOG_INFO) != 0)
14 andreas 284
        return true;
23 andreas 285
    else if (err == TERRWARNING && (mLogLevel & HLOG_WARNING) != 0)
14 andreas 286
        return true;
23 andreas 287
    else if (err == TERRERROR && (mLogLevel & HLOG_ERROR) != 0)
14 andreas 288
        return true;
23 andreas 289
    else if (err == TERRTRACE && (mLogLevel & HLOG_TRACE) != 0)
14 andreas 290
        return true;
23 andreas 291
    else if (err == TERRDEBUG && (mLogLevel & HLOG_DEBUG) != 0)
14 andreas 292
        return true;
2 andreas 293
 
14 andreas 294
    return false;
2 andreas 295
}
296
 
369 andreas 297
bool TStreamError::checkFilter(unsigned int lv)
2 andreas 298
{
116 andreas 299
    if (!TConfig::isInitialized())
300
        return false;
301
 
369 andreas 302
    if ((mLogLevel & HLOG_INFO) != 0 &&
303
        (mLogLevel & HLOG_WARNING) != 0 &&
304
        (mLogLevel & HLOG_ERROR) != 0 &&
305
        lv == HLOG_PROTOCOL)
14 andreas 306
        return true;
2 andreas 307
 
369 andreas 308
    if ((mLogLevel & lv) != 0 && lv != HLOG_PROTOCOL)
309
        return true;
310
 
14 andreas 311
    return false;
2 andreas 312
}
313
 
314
unsigned int TStreamError::_getLevel(const std::string& slv)
315
{
14 andreas 316
    if (slv.compare(SLOG_NONE) == 0)
23 andreas 317
        return HLOG_NONE;
2 andreas 318
 
14 andreas 319
    if (slv.compare(SLOG_INFO) == 0)
23 andreas 320
        return HLOG_INFO;
2 andreas 321
 
14 andreas 322
    if (slv.compare(SLOG_WARNING) == 0)
23 andreas 323
        return HLOG_WARNING;
2 andreas 324
 
14 andreas 325
    if (slv.compare(SLOG_ERROR) == 0)
23 andreas 326
        return HLOG_ERROR;
2 andreas 327
 
14 andreas 328
    if (slv.compare(SLOG_TRACE) == 0)
23 andreas 329
        return HLOG_TRACE;
2 andreas 330
 
14 andreas 331
    if (slv.compare(SLOG_DEBUG) == 0)
23 andreas 332
        return HLOG_DEBUG;
2 andreas 333
 
14 andreas 334
    if (slv.compare(SLOG_PROTOCOL) == 0)
23 andreas 335
        return HLOG_PROTOCOL;
2 andreas 336
 
14 andreas 337
    if (slv.compare(SLOG_ALL) == 0)
23 andreas 338
        return HLOG_ALL;
2 andreas 339
 
23 andreas 340
    return HLOG_NONE;
2 andreas 341
}
342
 
242 andreas 343
void TStreamError::_init(bool reinit)
2 andreas 344
{
116 andreas 345
    if (!TConfig::isInitialized() || mInitialized)
14 andreas 346
        return;
2 andreas 347
 
14 andreas 348
    mInitialized = true;
23 andreas 349
 
383 andreas 350
#ifdef __ANDROID__
385 andreas 351
    __android_log_print(ANDROID_LOG_DEBUG, "tpanel", "TStreamError::_init: Logfile is %s", (mLogFileEnabled ? "ENABLED" : "DISABLED"));
383 andreas 352
#endif
392 andreas 353
 
22 andreas 354
#if LOGPATH == LPATH_FILE
385 andreas 355
    if (mLogFileEnabled && !mLogfile.empty())
14 andreas 356
    {
23 andreas 357
        try
358
        {
359
#ifndef __ANDROID__
242 andreas 360
            if (mOfStream.is_open())
361
                mOfStream.close();
362
 
23 andreas 363
            if (mStream && mStream != &std::cout)
364
                delete mStream;
243 andreas 365
 
242 andreas 366
            if (!mBuffer)
367
            {
368
                mBuffer = new char[LOGBUFFER_SIZE];
369
                mOfStream.pubsetbuf(mBuffer, LOGBUFFER_SIZE);
370
            }
116 andreas 371
#if __cplusplus < 201402L
242 andreas 372
            mOfStream.open(mLogfile.c_str(), std::ios::out | std::ios::ate);
240 andreas 373
#else   // __cplusplus < 201402L
242 andreas 374
            mOfStream.open(mLogfile, std::ios::out | std::ios::ate);
240 andreas 375
#endif  //__cplusplus < 201402L
242 andreas 376
            mStream = new std::ostream(&mOfStream);
377
 
378
            if (!isStreamValid())
379
            {
380
                if (mOfStream.is_open())
381
                    mOfStream.close();
382
 
414 andreas 383
                delete mStream;
23 andreas 384
                mStream = &std::cout;
242 andreas 385
            }
240 andreas 386
#else   //__ANDROID__
43 andreas 387
            char *HOME = getenv("HOME");
388
            bool bigLog = false;
389
            uint logLevel = _getLevel(TConfig::getLogLevel());
390
 
391
            if ((logLevel & HLOG_TRACE) || (logLevel & HLOG_DEBUG))
392
                bigLog = true;
393
 
394
            if (HOME && !bigLog && mLogfile.find(HOME) == string::npos)
395
            {
251 andreas 396
                if (mOfStream.is_open())
397
                    mOfStream.close();
398
 
43 andreas 399
                if (mStream && mStream != &std::cout)
400
                    delete mStream;
401
 
406 andreas 402
                __android_log_print(ANDROID_LOG_DEBUG, "tpanel", "TStreamError::_init: Opening logfile: \"%s\"", mLogfile.c_str());
43 andreas 403
 
406 andreas 404
                if (!mOfStream.open(mLogfile, std::ios::out | std::ios::trunc))
43 andreas 405
                {
406 andreas 406
                    __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::_init: Could not open logfile!");
407
                    std::cout.rdbuf(new androidbuf);
43 andreas 408
                    mStream = &std::cout;
406 andreas 409
                    mLogFileEnabled = false;
43 andreas 410
                }
406 andreas 411
                else
412
                {
413
                    mStream = new std::ostream(&mOfStream);
414
 
415
                    if (!isStreamValid())
416
                    {
417
                        delete mStream;
418
 
419
                        if (mOfStream.is_open())
420
                            mOfStream.close();
421
 
422
                        std::cout.rdbuf(new androidbuf);
423
                        mStream = &std::cout;
424
                        mLogFileEnabled = false;
425
                    }
426
                }
43 andreas 427
            }
428
            else
429
            {
430
                std::cout.rdbuf(new androidbuf);
431
                mStream = &std::cout;
432
            }
23 andreas 433
#endif  // __ANDROID__
434
        }
435
        catch (std::exception& e)
436
        {
437
#ifdef __ANDROID__
260 andreas 438
            __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::_init: %s", e.what());
240 andreas 439
#else   // __ANDROID__
23 andreas 440
            std::cerr << "ERROR: " << e.what() << std::endl;
441
#endif  // __ANDROID__
442
            mStream = &std::cout;
443
        }
14 andreas 444
    }
242 andreas 445
    else if (!isStreamValid())
23 andreas 446
    {
447
#ifdef __ANDROID__
448
        std::cout.rdbuf(new androidbuf);
240 andreas 449
#endif  // __ANDROID__
14 andreas 450
        mStream = &std::cout;
306 andreas 451
#if defined(QT_DEBUG) || defined(DEBUG)
260 andreas 452
#ifdef __ANDROID__
453
        __android_log_print(ANDROID_LOG_DEBUG, "tpanel", "TStreamError::_init: Stream wurde auf std::cout gesetzt.");
454
#else
239 andreas 455
        std::cout << "DEBUG: Stream wurde auf std::cout gesetzt." << std::endl;
306 andreas 456
#endif  // __ANDROID__
414 andreas 457
#endif  // defined(QT_DEBUG) || defined(DEBUG)
23 andreas 458
    }
116 andreas 459
#else  // LOGPATH == LPATH_FILE
460
    if (!mStream)
461
    {
392 andreas 462
#if defined(__ANDROID__) || defined(__IOS_AVAILABLE)
116 andreas 463
        std::cout.rdbuf(new androidbuf);
464
#endif
465
        mStream = &std::cout;
466
    }
23 andreas 467
#endif  // LOGPATH == LPATH_FILE
468
 
242 andreas 469
    if (reinit)
470
        return;
471
 
260 andreas 472
    if (mLogLevel > 0)
14 andreas 473
        *mStream << "Logfile started at " << getTime() << std::endl;
2 andreas 474
 
153 andreas 475
    *mStream << TConfig::getProgName() << " version " << VERSION_STRING() << std::endl;
260 andreas 476
    *mStream << "(C) Copyright by Andreas Theofilu <andreas@theosys.at>\n" << std::endl;
2 andreas 477
 
260 andreas 478
    if (mLogLevel > 0)
479
    {
480
        if (TConfig::isLongFormat())
304 andreas 481
            *mStream << "Timestamp           Type LNr., File name           , ThreadID Message" << std::endl;
260 andreas 482
        else
316 andreas 483
            *mStream << "Type LNr., ThreadID Message" << std::endl;
260 andreas 484
 
485
        *mStream << "-----------------------------------------------------------------" << std::endl << std::flush;
486
    }
14 andreas 487
    else
260 andreas 488
        *mStream << std::flush;
14 andreas 489
}
116 andreas 490
 
23 andreas 491
std::ostream *TStreamError::resetFlags(std::ostream *os)
22 andreas 492
{
238 andreas 493
    if (!isStreamValid(*os))
494
        return os;
495
 
23 andreas 496
    *os << std::resetiosflags(std::ios::boolalpha) <<
497
           std::resetiosflags(std::ios::showbase) <<
498
           std::resetiosflags(std::ios::showpoint) <<
499
           std::resetiosflags(std::ios::showpos) <<
500
           std::resetiosflags(std::ios::skipws) <<
501
           std::resetiosflags(std::ios::unitbuf) <<
502
           std::resetiosflags(std::ios::uppercase) <<
503
           std::resetiosflags(std::ios::dec) <<
504
           std::resetiosflags(std::ios::hex) <<
505
           std::resetiosflags(std::ios::oct) <<
506
           std::resetiosflags(std::ios::fixed) <<
507
           std::resetiosflags(std::ios::scientific) <<
508
           std::resetiosflags(std::ios::internal) <<
509
           std::resetiosflags(std::ios::left) <<
510
           std::resetiosflags(std::ios::right) <<
511
           std::setfill(' ');
512
    return os;
22 andreas 513
}
514
 
247 andreas 515
void TStreamError::resetFlags()
516
{
292 andreas 517
    std::lock_guard<mutex> guard(message_mutex);
247 andreas 518
    resetFlags(TError::Current()->getStream());
519
}
520
 
2 andreas 521
void TStreamError::decIndent()
522
{
14 andreas 523
    if (mIndent > 0)
524
        mIndent--;
2 andreas 525
}
526
 
527
string TStreamError::getTime()
528
{
14 andreas 529
    time_t rawtime;
530
    struct tm * timeinfo;
531
    char buffer[80];
2 andreas 532
 
240 andreas 533
    rawtime = time(nullptr);
14 andreas 534
    timeinfo = localtime(&rawtime);
2 andreas 535
 
240 andreas 536
    if (!timeinfo)
537
    {
260 andreas 538
#ifdef __ANDROID__
539
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getTime: Couldn't get the local time!");
540
#else
240 andreas 541
        std::cerr << "ERROR: Couldn't get the local time!" << std::endl;
260 andreas 542
#endif
240 andreas 543
        return string();
544
    }
545
 
14 andreas 546
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
547
    string str(buffer);
548
    return str;
2 andreas 549
}
550
 
242 andreas 551
std::ostream *TStreamError::getStream()
552
{
553
    try
554
    {
555
        if (!isStreamValid())
556
        {
260 andreas 557
#ifdef __ANDROID__
558
            __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Internal stream is invalid!");
559
#else
242 andreas 560
            std::cerr << "ERROR: Internal stream is invalid!" << std::endl;
260 andreas 561
#endif
242 andreas 562
            mInitialized = false;
563
            _init();
260 andreas 564
#ifdef __ANDROID__
565
            __android_log_print(ANDROID_LOG_INFO, "tpanel", "TStreamError::getStream: Reinitialized stream.");
566
#else
242 andreas 567
            std::cerr << "INFO: Reinitialized stream." << std::endl;
260 andreas 568
#endif
242 andreas 569
 
570
            if (!isStreamValid())
571
            {
260 andreas 572
#ifdef __ANDROID__
573
                __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Reinitializing of stream failed!");
574
#else
242 andreas 575
                std::cerr << "ERROR: Reinitializing of stream failed! Using \"std::cout\" to write log messages." << std::endl;
260 andreas 576
#endif
242 andreas 577
                return &std::cout;
578
            }
579
        }
580
 
581
        return mStream;
582
    }
583
    catch (std::exception& e)
584
    {
260 andreas 585
#ifdef __ANDROID__
586
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Error retrieving the current stream!");
587
#else
242 andreas 588
        std::cerr << "ERROR: Error retrieving the current stream! Using \"std::cout\" instead." << std::endl;
260 andreas 589
#endif
242 andreas 590
    }
591
 
592
    return &std::cout;
593
}
594
 
2 andreas 595
std::ostream& indent(std::ostream& os)
596
{
238 andreas 597
    if (!TStreamError::isStreamValid(os))
14 andreas 598
        return os;
2 andreas 599
 
14 andreas 600
    if (TStreamError::getIndent() > 0)
601
        os << std::setw(TStreamError::getIndent()) << " ";
2 andreas 602
 
14 andreas 603
    return os;
2 andreas 604
}
605
 
238 andreas 606
bool TStreamError::isStreamValid()
607
{
608
    if (!mStream)
406 andreas 609
    {
610
#ifdef __ANDROID__
611
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::isStreamValid: Stream is nullptr!");
612
#else
613
        std::cerr << "ERROR: TStreamError::isStreamValid: Stream is nullptr!" << std::endl;
614
#endif
238 andreas 615
        return false;
406 andreas 616
    }
238 andreas 617
 
242 andreas 618
    if (mStream->rdstate() & std::ostream::failbit)
406 andreas 619
    {
620
#ifdef __ANDROID__
621
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::isStreamValid: Stream has failbit set!");
622
#else
623
        std::cerr << "ERROR: TStreamError::isStreamValid: Stream has failbit set!" << std::endl;
624
#endif
238 andreas 625
        return false;
406 andreas 626
    }
238 andreas 627
 
242 andreas 628
    if (mStream->rdstate() & std::ostream::badbit)
406 andreas 629
    {
630
#ifdef __ANDROID__
631
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::isStreamValid: Stream has badbit set!");
632
#else
633
        std::cerr << "ERROR: TStreamError::isStreamValid: Stream has badbit set!" << std::endl;
634
#endif
238 andreas 635
        return false;
406 andreas 636
    }
238 andreas 637
 
638
    return true;
639
}
640
 
641
bool TStreamError::isStreamValid(std::ostream& os)
642
{
242 andreas 643
    if (os.rdstate() & std::ostream::failbit)
238 andreas 644
        return false;
645
 
242 andreas 646
    if (os.rdstate() & std::ostream::badbit)
238 andreas 647
        return false;
648
 
649
    return true;
650
}
651
 
250 andreas 652
void TStreamError::startTemporaryLogLevel(unsigned int l)
653
{
654
    if (haveTemporaryLogLevel)
655
        return;
656
 
657
    mLogLevelOld = mLogLevel;
658
    mLogLevel |= l;
659
    haveTemporaryLogLevel = true;
660
}
661
 
662
void TStreamError::endTemporaryLogLevel()
663
{
260 andreas 664
    if (!haveTemporaryLogLevel)
665
        return;
666
 
250 andreas 667
    mLogLevel = mLogLevelOld;
668
    haveTemporaryLogLevel = false;
669
}
670
 
2 andreas 671
/********************************************************************/
672
 
14 andreas 673
std::mutex tracer_mutex;
674
 
398 andreas 675
TTracer::TTracer(const std::string& msg, int line, const char *file, threadID_t tid)
306 andreas 676
    : mThreadID(tid)
2 andreas 677
{
116 andreas 678
    if (!TConfig::isInitialized() || !TStreamError::checkFilter(HLOG_TRACE))
14 andreas 679
        return;
2 andreas 680
 
292 andreas 681
    std::lock_guard<mutex> guard(tracer_mutex);
116 andreas 682
 
14 andreas 683
    mFile = file;
684
    size_t pos = mFile.find_last_of("/");
2 andreas 685
 
14 andreas 686
    if (pos != string::npos)
687
        mFile = mFile.substr(pos + 1);
2 andreas 688
 
23 andreas 689
    TError::setErrorType(TERRTRACE);
292 andreas 690
    std::lock_guard<mutex> guardm(message_mutex);
242 andreas 691
 
14 andreas 692
    if (!TConfig::isLongFormat())
316 andreas 693
        *TError::Current()->getStream() << "TRC " << std::setw(5) << std::right << line << ", " << _threadIDtoStr(mThreadID) << " " << indent << "{entry " << msg << std::endl;
14 andreas 694
    else
304 andreas 695
        *TError::Current()->getStream() << TStreamError::getTime() <<  " TRC " << std::setw(5) << std::right << line << ", " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << indent << "{entry " << msg << std::endl;
2 andreas 696
 
14 andreas 697
    TError::Current()->incIndent();
698
    mHeadMsg = msg;
699
    mLine = line;
35 andreas 700
 
701
    if (TConfig::getProfiling())
702
        mTimePoint = std::chrono::steady_clock::now();
2 andreas 703
}
704
 
705
TTracer::~TTracer()
706
{
116 andreas 707
    if (!TConfig::isInitialized() || !TStreamError::checkFilter(HLOG_TRACE))
14 andreas 708
        return;
2 andreas 709
 
292 andreas 710
    std::lock_guard<mutex> guard(tracer_mutex);
23 andreas 711
    TError::setErrorType(TERRTRACE);
14 andreas 712
    TError::Current()->decIndent();
35 andreas 713
    string nanosecs;
714
 
715
    if (TConfig::getProfiling())
716
    {
717
        std::chrono::steady_clock::time_point endPoint = std::chrono::steady_clock::now();
718
        std::chrono::nanoseconds difftime = endPoint - mTimePoint;
719
        std::chrono::seconds secs = std::chrono::duration_cast<std::chrono::seconds>(difftime);
720
        std::chrono::milliseconds msecs = std::chrono::duration_cast<std::chrono::milliseconds>(difftime) - std::chrono::duration_cast<std::chrono::seconds>(secs);
721
        std::stringstream s;
722
        s << std::chrono::duration_cast<std::chrono::nanoseconds> (difftime).count() << "[ns]" << " --> " << std::chrono::duration_cast<std::chrono::seconds>(secs).count() << "s " << std::chrono::duration_cast<std::chrono::milliseconds>(msecs).count() << "ms";
723
        nanosecs = s.str();
724
    }
725
 
292 andreas 726
    std::lock_guard<mutex> guardm(message_mutex);
386 andreas 727
 
35 andreas 728
    if (TConfig::getProfiling())
729
    {
730
        if (!TConfig::isLongFormat())
316 andreas 731
            *TError::Current()->getStream() << "TRC      , " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << " Elapsed time: " << nanosecs << std::endl;
35 andreas 732
        else
304 andreas 733
            *TError::Current()->getStream() << TStreamError::getTime() << " TRC      , " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << " Elapsed time: " << nanosecs << std::endl;
35 andreas 734
    }
14 andreas 735
    else
35 andreas 736
    {
737
        if (!TConfig::isLongFormat())
316 andreas 738
            *TError::Current()->getStream() << "TRC      , " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << std::endl;
35 andreas 739
        else
304 andreas 740
            *TError::Current()->getStream() << TStreamError::getTime() << " TRC      , " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << std::endl;
35 andreas 741
    }
14 andreas 742
 
743
    mHeadMsg.clear();
2 andreas 744
}
745
 
746
/********************************************************************/
747
 
748
TError::~TError()
749
{
14 andreas 750
    if (mCurrent)
751
    {
752
        delete mCurrent;
753
        mCurrent = nullptr;
754
    }
2 andreas 755
}
14 andreas 756
 
2 andreas 757
TStreamError* TError::Current()
758
{
14 andreas 759
    if (!mCurrent)
760
        mCurrent = new TStreamError(TConfig::getLogFile(), TConfig::getLogLevel());
2 andreas 761
 
14 andreas 762
    return mCurrent;
2 andreas 763
}
764
 
306 andreas 765
TStreamError *TError::Current(threadID_t tid)
304 andreas 766
{
767
    mThreadID = tid;
768
    return Current();
769
}
770
 
5 andreas 771
void TError::logHex(char* str, size_t size)
772
{
773
    if (!str || !size)
774
        return;
775
 
116 andreas 776
    if (!Current())
290 andreas 777
        return;
289 andreas 778
 
5 andreas 779
    // Print out the message
780
    std::ostream *stream = mCurrent->getStream();
21 andreas 781
    *stream << strToHex(str, size, 16, true, 12) << std::endl;
23 andreas 782
    *stream << mCurrent->resetFlags(stream);
21 andreas 783
}
5 andreas 784
 
21 andreas 785
string TError::toHex(int num, int width)
786
{
787
    string ret;
788
    std::stringstream stream;
789
    stream << std::setfill ('0') << std::setw(width) << std::hex << num;
790
    ret = stream.str();
791
    return ret;
792
}
793
 
794
string TError::strToHex(const char *str, size_t size, int width, bool format, int indent)
795
{
796
    int len = 0, pos = 0, old = 0;
797
    int w = (format) ? 1 : width;
798
    string out, left, right;
799
    string ind;
800
 
801
    if (indent > 0)
802
    {
803
        for (int j = 0; j < indent; j++)
804
            ind.append(" ");
805
    }
806
 
5 andreas 807
    for (size_t i = 0; i < size; i++)
808
    {
21 andreas 809
        if (len >= w)
810
        {
811
            left.append(" ");
812
            len = 0;
813
        }
5 andreas 814
 
21 andreas 815
        if (format && i > 0 && (pos % width) == 0)
5 andreas 816
        {
21 andreas 817
            out += ind + toHex(old, 4) + ": " + left + " | " + right + "\n";
818
            left.clear();
819
            right.clear();
820
            old = pos;
5 andreas 821
        }
21 andreas 822
 
823
        int c = *(str+i) & 0x000000ff;
824
        left.append(toHex(c, 2));
825
 
826
        if (format)
827
        {
828
            if (std::isprint(c))
829
                right.push_back(c);
830
            else
831
                right.push_back('.');
832
        }
833
 
834
        len++;
835
        pos++;
5 andreas 836
    }
837
 
21 andreas 838
    if (!format)
839
        return left;
840
    else if (pos > 0)
841
    {
842
        if ((pos % width) != 0)
843
        {
844
            for (int i = 0; i < (width - (pos % width)); i++)
845
                left.append("   ");
846
        }
847
 
848
        out += ind + toHex(old, 4)+": "+left + "  | " + right;
849
    }
850
 
851
    return out;
5 andreas 852
}
853
 
2 andreas 854
void TError::setErrorMsg(const std::string& msg)
855
{
14 andreas 856
    if (msg.empty())
857
        return;
2 andreas 858
 
14 andreas 859
    msError = msg;
860
    mHaveError = true;
861
    mErrType = TERRERROR;
2 andreas 862
}
863
 
864
void TError::setErrorMsg(terrtype_t t, const std::string& msg)
865
{
14 andreas 866
    if (msg.empty())
867
        return;
2 andreas 868
 
14 andreas 869
    msError = msg;
870
    mHaveError = true;
871
    mErrType = t;
2 andreas 872
}
873
 
874
std::ostream & TError::append(int lv, std::ostream& os)
875
{
14 andreas 876
    Current();
2 andreas 877
 
242 andreas 878
    if (!TConfig::isInitialized() && (lv == HLOG_ERROR || lv == HLOG_WARNING))
879
    {
880
        std::cerr << append(lv);
881
        return std::cerr;
882
    }
883
 
884
    return os << append(lv);
885
}
886
 
887
std::string TError::append(int lv)
888
{
292 andreas 889
    std::lock_guard<mutex> guard(message_mutex);
242 andreas 890
    std::string prefix, out;
891
 
14 andreas 892
    switch (lv)
893
    {
94 andreas 894
        case HLOG_PROTOCOL: prefix = "PRT    ++, "; mErrType = TERRINFO; break;
23 andreas 895
        case HLOG_INFO:     prefix = "INF    >>, "; mErrType = TERRINFO; break;
896
        case HLOG_WARNING:  prefix = "WRN    !!, "; mErrType = TERRWARNING; break;
897
        case HLOG_ERROR:    prefix = "ERR *****, "; mErrType = TERRERROR; break;
898
        case HLOG_TRACE:    prefix = "TRC      , "; mErrType = TERRTRACE; break;
899
        case HLOG_DEBUG:    prefix = "DBG    --, "; mErrType = TERRDEBUG; break;
14 andreas 900
 
901
        default:
22 andreas 902
            prefix = "           ";
23 andreas 903
            mErrType = TERRNONE;
14 andreas 904
    }
905
 
242 andreas 906
    if (!TConfig::isLongFormat())
316 andreas 907
        out = prefix + _threadIDtoStr(mThreadID) + " ";
242 andreas 908
    else
116 andreas 909
    {
242 andreas 910
        std::stringstream s;
304 andreas 911
        s << TStreamError::getTime() << " " << prefix << std::setw(20) << " " << ", " << _threadIDtoStr(mThreadID) << " ";
242 andreas 912
        out = s.str();
116 andreas 913
    }
914
 
242 andreas 915
    return out;
2 andreas 916
}
22 andreas 917
 
918
void TError::displayMessage(const std::string& msg)
919
{
920
    QMessageBox m;
921
    m.setText(msg.c_str());
922
 
923
    int cnt = 10;
924
 
925
    QTimer cntDown;
926
    QObject::connect(&cntDown, &QTimer::timeout, [&m, &cnt, &cntDown]()->void
927
        {
928
            if (--cnt < 0)
929
            {
930
                cntDown.stop();
931
                m.close();
932
            }
933
        });
934
 
239 andreas 935
    cntDown.start(1000);
936
    m.exec();
22 andreas 937
}