Logging.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #ifndef QLOW_LOGGING_H
  2. #define QLOW_LOGGING_H
  3. #include <iostream>
  4. namespace qlow
  5. {
  6. class Logger;
  7. enum class LogLevel
  8. {
  9. NONE,
  10. ERROR,
  11. WARNING,
  12. INFO,
  13. DEBUG,
  14. TRACE,
  15. OFF,
  16. };
  17. struct CodePosition;
  18. }
  19. class qlow::Logger :
  20. public std::ostream,
  21. private std::streambuf
  22. {
  23. protected:
  24. class NullStream :
  25. public std::ostream,
  26. public std::streambuf
  27. {
  28. public:
  29. NullStream(void) : std::ostream{ this } {}
  30. inline int overflow(int c) override { return c; }
  31. };
  32. enum Color {
  33. BLACK = 0,
  34. RED,
  35. GREEN,
  36. YELLOW,
  37. BLUE,
  38. MAGENTA,
  39. CYAN,
  40. WHITE
  41. };
  42. std::ostream& target;
  43. NullStream nullStream;
  44. bool firstChar;
  45. int indentVal;
  46. // type of current logging
  47. LogLevel logType = LogLevel::OFF;
  48. LogLevel logLevel = LogLevel::INFO;
  49. static Logger instance;
  50. void foreground(Color color, bool bright);
  51. void background(Color color, bool bright);
  52. void bold(void);
  53. void removeFormatting(void);
  54. public:
  55. explicit Logger(std::ostream& target);
  56. ~Logger(void) = default;
  57. void logError(const std::string& errMsg);
  58. void logError(const std::string& errMsg, const qlow::CodePosition& cp);
  59. std::ostream& operator() (LogLevel ll);
  60. inline std::ostream& none (void) { return (*this)(LogLevel::NONE); }
  61. inline std::ostream& err (void) { return (*this)(LogLevel::ERROR); }
  62. inline std::ostream& warn (void) { return (*this)(LogLevel::WARNING); }
  63. inline std::ostream& info (void) { return (*this)(LogLevel::INFO); }
  64. inline std::ostream& debug(void) { return (*this)(LogLevel::DEBUG); }
  65. inline std::ostream& trace(void) { return (*this)(LogLevel::TRACE); }
  66. inline void setLogType(LogLevel l) { logType = l; }
  67. inline static Logger& getInstance(void) { return instance; }
  68. protected:
  69. int overflow(int c) override;
  70. //virtual std::streamsize xsputn (const char* s, std::streamsize n);
  71. };
  72. std::ostream& operator << (std::ostream& o, qlow::LogLevel l);
  73. inline void shouldbe()
  74. {
  75. qlow::Logger& logger = qlow::Logger::getInstance();
  76. logger.err() << "something happened" << std::endl;
  77. }
  78. #endif // QLOW_LOGGING_H