Line data Source code
1 : /////////////////////////////////////////////////////////////////////////// 2 : // Spetabaru - Berenger Bramas MPCDF - 2017 3 : // Under LGPL Licence, please you must read the LICENCE file. 4 : /////////////////////////////////////////////////////////////////////////// 5 : #ifndef SPDEBUG_HPP 6 : #define SPDEBUG_HPP 7 : 8 : #include <mutex> 9 : #include <sstream> 10 : #include <iostream> 11 : #include <cstring> 12 : 13 : /** 14 : * This class should be used to print debug info. 15 : * The environment variable SPETABARU_DEBUG_PRINT allow to disable/enable 16 : * the output at runtime. 17 : */ 18 : class SpDebug { 19 : const bool hasBeenEnabled; 20 : std::mutex outputMutex; 21 : const bool toFile; 22 : 23 23 : SpDebug() 24 23 : : hasBeenEnabled(getenv("SPETABARU_DEBUG_PRINT") && strcmp(getenv("SPETABARU_DEBUG_PRINT"),"TRUE") == 0?true:false), 25 23 : toFile(false){ 26 23 : } 27 : 28 : SpDebug(const SpDebug&) = delete; 29 : SpDebug(SpDebug&&) = delete; 30 : SpDebug& operator=(const SpDebug&) = delete; 31 : SpDebug& operator=(SpDebug&&) = delete; 32 : 33 : public: 34 : static SpDebug Controller; 35 : 36 : class Printer { 37 : SpDebug& master; 38 : 39 : std::stringstream buffer; 40 : 41 79861 : explicit Printer(SpDebug& inMaster) : master(inMaster){ 42 79938 : if(master.isEnable()){ 43 0 : buffer << "[THREAD-" << master.getThreadId() << "] "; 44 : } 45 79913 : } 46 : 47 : public: 48 79536 : ~Printer(){ 49 79611 : if(master.isEnable()){ 50 0 : buffer << "\n"; 51 0 : const std::string toOutput = buffer.str(); 52 0 : if(master.toFile){ 53 : 54 : } 55 : else{ 56 0 : master.outputMutex.lock(); 57 0 : std::cout << toOutput; 58 0 : master.outputMutex.unlock(); 59 : } 60 : } 61 79894 : } 62 : 63 : Printer(const Printer&) = delete; 64 : Printer(Printer&&) = default; 65 : Printer& operator=(const Printer&) = delete; 66 : Printer& operator=(Printer&&) = delete; 67 : 68 : template <class Param> 69 335094 : Printer& operator<<(Param&& toOutput){ 70 335094 : if(master.isEnable()){ 71 0 : buffer << toOutput; 72 : } 73 335035 : return *this; 74 : } 75 : 76 : void lineBreak(){ 77 : if(master.isEnable()){ 78 : buffer << '\n' << "[THREAD-" << master.getThreadId() << "] "; 79 : } 80 : } 81 : 82 : friend SpDebug; 83 : }; 84 : 85 79878 : Printer getPrinter(){ 86 79878 : return Printer(*this); 87 : } 88 : 89 490794 : bool isEnable() const{ 90 490794 : return hasBeenEnabled; 91 : } 92 : 93 : long int getThreadId() const; 94 : 95 : friend Printer; 96 : }; 97 : 98 : 99 79886 : inline SpDebug::Printer SpDebugPrint(){ 100 79886 : return SpDebug::Controller.getPrinter(); 101 : } 102 : 103 : 104 : #endif