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
 
267
bool TStreamError::checkFilter(int lv)
268
{
116 andreas 269
    if (!TConfig::isInitialized())
270
        return false;
271
 
14 andreas 272
    if ((mLogLevel & lv) != 0)
273
        return true;
2 andreas 274
 
14 andreas 275
    return false;
2 andreas 276
}
277
 
278
unsigned int TStreamError::_getLevel(const std::string& slv)
279
{
14 andreas 280
    if (slv.compare(SLOG_NONE) == 0)
23 andreas 281
        return HLOG_NONE;
2 andreas 282
 
14 andreas 283
    if (slv.compare(SLOG_INFO) == 0)
23 andreas 284
        return HLOG_INFO;
2 andreas 285
 
14 andreas 286
    if (slv.compare(SLOG_WARNING) == 0)
23 andreas 287
        return HLOG_WARNING;
2 andreas 288
 
14 andreas 289
    if (slv.compare(SLOG_ERROR) == 0)
23 andreas 290
        return HLOG_ERROR;
2 andreas 291
 
14 andreas 292
    if (slv.compare(SLOG_TRACE) == 0)
23 andreas 293
        return HLOG_TRACE;
2 andreas 294
 
14 andreas 295
    if (slv.compare(SLOG_DEBUG) == 0)
23 andreas 296
        return HLOG_DEBUG;
2 andreas 297
 
14 andreas 298
    if (slv.compare(SLOG_PROTOCOL) == 0)
23 andreas 299
        return HLOG_PROTOCOL;
2 andreas 300
 
14 andreas 301
    if (slv.compare(SLOG_ALL) == 0)
23 andreas 302
        return HLOG_ALL;
2 andreas 303
 
23 andreas 304
    return HLOG_NONE;
2 andreas 305
}
306
 
242 andreas 307
void TStreamError::_init(bool reinit)
2 andreas 308
{
116 andreas 309
    if (!TConfig::isInitialized() || mInitialized)
14 andreas 310
        return;
2 andreas 311
 
14 andreas 312
    mInitialized = true;
23 andreas 313
 
22 andreas 314
#if LOGPATH == LPATH_FILE
14 andreas 315
    if (!mLogfile.empty())
316
    {
23 andreas 317
        try
318
        {
319
#ifndef __ANDROID__
242 andreas 320
            if (mOfStream.is_open())
321
                mOfStream.close();
322
 
23 andreas 323
            if (mStream && mStream != &std::cout)
324
                delete mStream;
243 andreas 325
 
242 andreas 326
            if (!mBuffer)
327
            {
328
                mBuffer = new char[LOGBUFFER_SIZE];
329
                mOfStream.pubsetbuf(mBuffer, LOGBUFFER_SIZE);
330
            }
116 andreas 331
#if __cplusplus < 201402L
242 andreas 332
            mOfStream.open(mLogfile.c_str(), std::ios::out | std::ios::ate);
240 andreas 333
#else   // __cplusplus < 201402L
242 andreas 334
            mOfStream.open(mLogfile, std::ios::out | std::ios::ate);
240 andreas 335
#endif  //__cplusplus < 201402L
242 andreas 336
            mStream = new std::ostream(&mOfStream);
337
 
338
            if (!isStreamValid())
339
            {
340
                if (mOfStream.is_open())
341
                    mOfStream.close();
342
 
23 andreas 343
                mStream = &std::cout;
242 andreas 344
            }
240 andreas 345
#else   //__ANDROID__
43 andreas 346
            char *HOME = getenv("HOME");
347
            bool bigLog = false;
348
            uint logLevel = _getLevel(TConfig::getLogLevel());
349
 
350
            if ((logLevel & HLOG_TRACE) || (logLevel & HLOG_DEBUG))
351
                bigLog = true;
352
 
353
            if (HOME && !bigLog && mLogfile.find(HOME) == string::npos)
354
            {
251 andreas 355
                if (mOfStream.is_open())
356
                    mOfStream.close();
357
 
43 andreas 358
                if (mStream && mStream != &std::cout)
359
                    delete mStream;
360
 
251 andreas 361
#if __cplusplus < 201402L
362
                mOfStream.open(mLogfile.c_str(), std::ios::out | std::ios::ate);
363
#else   // __cplusplus < 201402L
364
                mOfStream.open(mLogfile, std::ios::out | std::ios::ate);
365
#endif  //__cplusplus < 201402L
366
                mStream = new std::ostream(&mOfStream);
43 andreas 367
 
251 andreas 368
                if (!isStreamValid())
43 andreas 369
                {
251 andreas 370
                    if (mOfStream.is_open())
371
                        mOfStream.close();
372
 
43 andreas 373
                    mStream = &std::cout;
374
                }
375
            }
376
            else
377
            {
378
                std::cout.rdbuf(new androidbuf);
379
                mStream = &std::cout;
380
            }
23 andreas 381
#endif  // __ANDROID__
382
        }
383
        catch (std::exception& e)
384
        {
385
#ifdef __ANDROID__
260 andreas 386
            __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::_init: %s", e.what());
240 andreas 387
#else   // __ANDROID__
23 andreas 388
            std::cerr << "ERROR: " << e.what() << std::endl;
389
#endif  // __ANDROID__
390
            mStream = &std::cout;
391
        }
14 andreas 392
    }
242 andreas 393
    else if (!isStreamValid())
23 andreas 394
    {
395
#ifdef __ANDROID__
396
        std::cout.rdbuf(new androidbuf);
240 andreas 397
#endif  // __ANDROID__
14 andreas 398
        mStream = &std::cout;
306 andreas 399
#if defined(QT_DEBUG) || defined(DEBUG)
260 andreas 400
#ifdef __ANDROID__
401
        __android_log_print(ANDROID_LOG_DEBUG, "tpanel", "TStreamError::_init: Stream wurde auf std::cout gesetzt.");
402
#else
239 andreas 403
        std::cout << "DEBUG: Stream wurde auf std::cout gesetzt." << std::endl;
306 andreas 404
#endif  // __ANDROID__
260 andreas 405
#endif
23 andreas 406
    }
116 andreas 407
#else  // LOGPATH == LPATH_FILE
408
    if (!mStream)
409
    {
410
#ifdef __ANDROID__
411
        std::cout.rdbuf(new androidbuf);
412
#endif
413
        mStream = &std::cout;
414
    }
23 andreas 415
#endif  // LOGPATH == LPATH_FILE
416
 
242 andreas 417
    if (reinit)
418
        return;
419
 
260 andreas 420
    if (mLogLevel > 0)
14 andreas 421
        *mStream << "Logfile started at " << getTime() << std::endl;
2 andreas 422
 
153 andreas 423
    *mStream << TConfig::getProgName() << " version " << VERSION_STRING() << std::endl;
260 andreas 424
    *mStream << "(C) Copyright by Andreas Theofilu <andreas@theosys.at>\n" << std::endl;
2 andreas 425
 
260 andreas 426
    if (mLogLevel > 0)
427
    {
428
        if (TConfig::isLongFormat())
304 andreas 429
            *mStream << "Timestamp           Type LNr., File name           , ThreadID Message" << std::endl;
260 andreas 430
        else
316 andreas 431
            *mStream << "Type LNr., ThreadID Message" << std::endl;
260 andreas 432
 
433
        *mStream << "-----------------------------------------------------------------" << std::endl << std::flush;
434
    }
14 andreas 435
    else
260 andreas 436
        *mStream << std::flush;
14 andreas 437
}
116 andreas 438
 
23 andreas 439
std::ostream *TStreamError::resetFlags(std::ostream *os)
22 andreas 440
{
238 andreas 441
    if (!isStreamValid(*os))
442
        return os;
443
 
23 andreas 444
    *os << std::resetiosflags(std::ios::boolalpha) <<
445
           std::resetiosflags(std::ios::showbase) <<
446
           std::resetiosflags(std::ios::showpoint) <<
447
           std::resetiosflags(std::ios::showpos) <<
448
           std::resetiosflags(std::ios::skipws) <<
449
           std::resetiosflags(std::ios::unitbuf) <<
450
           std::resetiosflags(std::ios::uppercase) <<
451
           std::resetiosflags(std::ios::dec) <<
452
           std::resetiosflags(std::ios::hex) <<
453
           std::resetiosflags(std::ios::oct) <<
454
           std::resetiosflags(std::ios::fixed) <<
455
           std::resetiosflags(std::ios::scientific) <<
456
           std::resetiosflags(std::ios::internal) <<
457
           std::resetiosflags(std::ios::left) <<
458
           std::resetiosflags(std::ios::right) <<
459
           std::setfill(' ');
460
    return os;
22 andreas 461
}
462
 
247 andreas 463
void TStreamError::resetFlags()
464
{
292 andreas 465
    std::lock_guard<mutex> guard(message_mutex);
247 andreas 466
    resetFlags(TError::Current()->getStream());
467
}
468
 
2 andreas 469
void TStreamError::decIndent()
470
{
14 andreas 471
    if (mIndent > 0)
472
        mIndent--;
2 andreas 473
}
474
 
475
string TStreamError::getTime()
476
{
14 andreas 477
    time_t rawtime;
478
    struct tm * timeinfo;
479
    char buffer[80];
2 andreas 480
 
240 andreas 481
    rawtime = time(nullptr);
14 andreas 482
    timeinfo = localtime(&rawtime);
2 andreas 483
 
240 andreas 484
    if (!timeinfo)
485
    {
260 andreas 486
#ifdef __ANDROID__
487
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getTime: Couldn't get the local time!");
488
#else
240 andreas 489
        std::cerr << "ERROR: Couldn't get the local time!" << std::endl;
260 andreas 490
#endif
240 andreas 491
        return string();
492
    }
493
 
14 andreas 494
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
495
    string str(buffer);
496
    return str;
2 andreas 497
}
498
 
242 andreas 499
std::ostream *TStreamError::getStream()
500
{
501
    try
502
    {
503
        if (!isStreamValid())
504
        {
260 andreas 505
#ifdef __ANDROID__
506
            __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Internal stream is invalid!");
507
#else
242 andreas 508
            std::cerr << "ERROR: Internal stream is invalid!" << std::endl;
260 andreas 509
#endif
242 andreas 510
            mInitialized = false;
511
            _init();
260 andreas 512
#ifdef __ANDROID__
513
            __android_log_print(ANDROID_LOG_INFO, "tpanel", "TStreamError::getStream: Reinitialized stream.");
514
#else
242 andreas 515
            std::cerr << "INFO: Reinitialized stream." << std::endl;
260 andreas 516
#endif
242 andreas 517
 
518
            if (!isStreamValid())
519
            {
260 andreas 520
#ifdef __ANDROID__
521
                __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Reinitializing of stream failed!");
522
#else
242 andreas 523
                std::cerr << "ERROR: Reinitializing of stream failed! Using \"std::cout\" to write log messages." << std::endl;
260 andreas 524
#endif
242 andreas 525
                return &std::cout;
526
            }
527
        }
528
 
529
        return mStream;
530
    }
531
    catch (std::exception& e)
532
    {
260 andreas 533
#ifdef __ANDROID__
534
        __android_log_print(ANDROID_LOG_ERROR, "tpanel", "TStreamError::getStream: Error retrieving the current stream!");
535
#else
242 andreas 536
        std::cerr << "ERROR: Error retrieving the current stream! Using \"std::cout\" instead." << std::endl;
260 andreas 537
#endif
242 andreas 538
    }
539
 
540
    return &std::cout;
541
}
542
 
2 andreas 543
std::ostream& indent(std::ostream& os)
544
{
238 andreas 545
    if (!TStreamError::isStreamValid(os))
14 andreas 546
        return os;
2 andreas 547
 
14 andreas 548
    if (TStreamError::getIndent() > 0)
549
        os << std::setw(TStreamError::getIndent()) << " ";
2 andreas 550
 
14 andreas 551
    return os;
2 andreas 552
}
553
 
238 andreas 554
bool TStreamError::isStreamValid()
555
{
556
    if (!mStream)
557
        return false;
558
 
242 andreas 559
    if (mStream->rdstate() & std::ostream::failbit)
238 andreas 560
        return false;
561
 
242 andreas 562
    if (mStream->rdstate() & std::ostream::badbit)
238 andreas 563
        return false;
564
 
565
    return true;
566
}
567
 
568
bool TStreamError::isStreamValid(std::ostream& os)
569
{
242 andreas 570
    if (os.rdstate() & std::ostream::failbit)
238 andreas 571
        return false;
572
 
242 andreas 573
    if (os.rdstate() & std::ostream::badbit)
238 andreas 574
        return false;
575
 
576
    return true;
577
}
578
 
250 andreas 579
void TStreamError::startTemporaryLogLevel(unsigned int l)
580
{
581
    if (haveTemporaryLogLevel)
582
        return;
583
 
584
    mLogLevelOld = mLogLevel;
585
    mLogLevel |= l;
586
    haveTemporaryLogLevel = true;
587
}
588
 
589
void TStreamError::endTemporaryLogLevel()
590
{
260 andreas 591
    if (!haveTemporaryLogLevel)
592
        return;
593
 
250 andreas 594
    mLogLevel = mLogLevelOld;
595
    haveTemporaryLogLevel = false;
596
}
597
 
2 andreas 598
/********************************************************************/
599
 
14 andreas 600
std::mutex tracer_mutex;
601
 
306 andreas 602
TTracer::TTracer(const std::string msg, int line, char *file, threadID_t tid)
603
    : mThreadID(tid)
2 andreas 604
{
116 andreas 605
    if (!TConfig::isInitialized() || !TStreamError::checkFilter(HLOG_TRACE))
14 andreas 606
        return;
2 andreas 607
 
292 andreas 608
    std::lock_guard<mutex> guard(tracer_mutex);
116 andreas 609
 
14 andreas 610
    mFile = file;
611
    size_t pos = mFile.find_last_of("/");
2 andreas 612
 
14 andreas 613
    if (pos != string::npos)
614
        mFile = mFile.substr(pos + 1);
2 andreas 615
 
23 andreas 616
    TError::setErrorType(TERRTRACE);
292 andreas 617
    std::lock_guard<mutex> guardm(message_mutex);
242 andreas 618
 
22 andreas 619
#if LOGPATH == LPATH_FILE
14 andreas 620
    if (!TConfig::isLongFormat())
316 andreas 621
        *TError::Current()->getStream() << "TRC " << std::setw(5) << std::right << line << ", " << _threadIDtoStr(mThreadID) << " " << indent << "{entry " << msg << std::endl;
14 andreas 622
    else
304 andreas 623
        *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 624
#else
625
    std::stringstream s;
2 andreas 626
 
22 andreas 627
    if (!TConfig::isLongFormat())
628
        s  << "TRC " << std::setw(5) << std::right << line << ", " << &indents << "{entry " << msg << std::endl;
629
    else
304 andreas 630
        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 631
 
632
    TError::Current()->logMsg(s);
633
#endif
14 andreas 634
    TError::Current()->incIndent();
635
    mHeadMsg = msg;
636
    mLine = line;
35 andreas 637
 
638
    if (TConfig::getProfiling())
639
        mTimePoint = std::chrono::steady_clock::now();
2 andreas 640
}
641
 
642
TTracer::~TTracer()
643
{
116 andreas 644
    if (!TConfig::isInitialized() || !TStreamError::checkFilter(HLOG_TRACE))
14 andreas 645
        return;
2 andreas 646
 
292 andreas 647
    std::lock_guard<mutex> guard(tracer_mutex);
23 andreas 648
    TError::setErrorType(TERRTRACE);
14 andreas 649
    TError::Current()->decIndent();
35 andreas 650
    string nanosecs;
651
 
652
    if (TConfig::getProfiling())
653
    {
654
        std::chrono::steady_clock::time_point endPoint = std::chrono::steady_clock::now();
655
        std::chrono::nanoseconds difftime = endPoint - mTimePoint;
656
        std::chrono::seconds secs = std::chrono::duration_cast<std::chrono::seconds>(difftime);
657
        std::chrono::milliseconds msecs = std::chrono::duration_cast<std::chrono::milliseconds>(difftime) - std::chrono::duration_cast<std::chrono::seconds>(secs);
658
        std::stringstream s;
659
        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";
660
        nanosecs = s.str();
661
    }
662
 
292 andreas 663
    std::lock_guard<mutex> guardm(message_mutex);
22 andreas 664
#if LOGPATH == LPATH_FILE
35 andreas 665
    if (TConfig::getProfiling())
666
    {
667
        if (!TConfig::isLongFormat())
316 andreas 668
            *TError::Current()->getStream() << "TRC      , " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << " Elapsed time: " << nanosecs << std::endl;
35 andreas 669
        else
304 andreas 670
            *TError::Current()->getStream() << TStreamError::getTime() << " TRC      , " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << " Elapsed time: " << nanosecs << std::endl;
35 andreas 671
    }
14 andreas 672
    else
35 andreas 673
    {
674
        if (!TConfig::isLongFormat())
316 andreas 675
            *TError::Current()->getStream() << "TRC      , " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << std::endl;
35 andreas 676
        else
304 andreas 677
            *TError::Current()->getStream() << TStreamError::getTime() << " TRC      , " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << indent << "}exit " << mHeadMsg << std::endl;
35 andreas 678
    }
22 andreas 679
#else
680
    std::stringstream s;
14 andreas 681
 
22 andreas 682
    if (!TConfig::isLongFormat())
35 andreas 683
        s << "TRC      , " << &indents << "}exit " << mHeadMsg;
22 andreas 684
    else
304 andreas 685
        s << TStreamError::getTime() << " TRC      , " << std::setw(20) << std::left << mFile << ", " << _threadIDtoStr(mThreadID) << " " << &indents << "}exit " << mHeadMsg;
22 andreas 686
 
35 andreas 687
    if (TConfig::getProfiling())
688
        s  << " Elapsed time: " << nanosecs << std::endl;
689
    else
690
        s << std::endl;
691
 
22 andreas 692
    TError::Current()->logMsg(s);
693
#endif
14 andreas 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
}