Log.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #pragma once
  2. #include <iostream>
  3. #include <memory>
  4. #include <mutex>
  5. #include <ostream>
  6. #include <sstream>
  7. #include <vector>
  8. namespace WallpaperEngine::Logging {
  9. class Log {
  10. public:
  11. void addOutput (std::ostream* stream);
  12. void addError (std::ostream* stream);
  13. template <typename... Data> void out (const Data&... data) {
  14. std::string str = this->buildBuffer (data...);
  15. const std::lock_guard lock (this->mMutex);
  16. for (const auto cur : this->mOutputs) {
  17. *cur << str << '\n' << std::flush;
  18. }
  19. }
  20. template <typename... Data> void debug (const Data&... data) {
  21. #if (!NDEBUG) && (!ERRORONLY)
  22. std::string str = this->buildBuffer (data...);
  23. const std::lock_guard lock (this->mMutex);
  24. for (const auto cur : this->mOutputs) {
  25. *cur << str << '\n';
  26. }
  27. #endif
  28. }
  29. template <typename... Data> void debugerror (const Data&... data) {
  30. #if (!NDEBUG) && (ERRORONLY)
  31. std::string str = this->buildBuffer (data...);
  32. const std::lock_guard lock (this->mMutex);
  33. for (const auto cur : this->mOutputs) {
  34. *cur << str << '\n';
  35. }
  36. #endif
  37. }
  38. template <typename... Data> void error (const Data&... data) {
  39. std::string str = this->buildBuffer (data...);
  40. const std::lock_guard lock (this->mMutex);
  41. for (const auto cur : this->mErrors) {
  42. *cur << str << '\n' << std::flush;
  43. }
  44. }
  45. template <class EX, typename... Data> [[noreturn]] void exception (const Data&... data) {
  46. std::string str = this->buildBuffer (data...);
  47. {
  48. const std::lock_guard lock (this->mMutex);
  49. for (const auto cur : this->mErrors) {
  50. *cur << str << '\n';
  51. }
  52. }
  53. throw EX (str);
  54. }
  55. template <typename... Data> [[noreturn]] void exception (const Data&... data) {
  56. this->exception<std::runtime_error> (data...);
  57. }
  58. static Log& get ();
  59. private:
  60. Log ();
  61. template <typename... Data> std::string buildBuffer (const Data&... data) {
  62. std::stringbuf buffer;
  63. std::ostream bufferStream (&buffer);
  64. ((bufferStream << data), ...);
  65. return buffer.str ();
  66. }
  67. std::mutex mMutex;
  68. std::vector<std::ostream*> mOutputs = {};
  69. std::vector<std::ostream*> mErrors = {};
  70. static std::unique_ptr<Log> sInstance;
  71. };
  72. }
  73. #define sLog (WallpaperEngine::Logging::Log::get ())