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