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