Logger.cppm 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. export module Core.Logger;
  2. import Core.TerminalConstants;
  3. import Core.Meta;
  4. import Core.ToString;
  5. import Core.Std;
  6. #define SOURCE const std::source_location& sl = std::source_location::current()
  7. export namespace Core {
  8. enum class LogLevel { NONE, ERROR, WARNING, INFO, DEBUG };
  9. extern LogLevel logLevel;
  10. using ReportHandler = void (*)(
  11. LogLevel l, const std::source_location& sl, void* data,
  12. const char* message);
  13. void callReportHandler(LogLevel l, const char* report, SOURCE);
  14. void setReportHandler(ReportHandler h, void* data);
  15. struct FormatLocation final {
  16. const char* format;
  17. std::source_location location;
  18. FormatLocation(const char* f, SOURCE) : format(f), location(sl) {
  19. }
  20. };
  21. template<typename... Args>
  22. void report(LogLevel l, const FormatLocation& format, Args&&... args) {
  23. String<512> s;
  24. s.addFormat(format.format, Core::forward<Args>(args)...);
  25. callReportHandler(l, s, format.location);
  26. }
  27. const char* getShortFileName(const char* s);
  28. template<typename... Args>
  29. void log(
  30. LogLevel l, const char* prefix, const FormatLocation& format,
  31. Args&&... args) {
  32. if(logLevel < l) {
  33. return;
  34. }
  35. const char* file = getShortFileName(format.location.file_name());
  36. fputs(prefix, stdout);
  37. print("{}:{} | ", file, format.location.line());
  38. String<512> s;
  39. s.addFormat(format.format, Core::forward<Args>(args)...);
  40. s.print();
  41. puts(Terminal::RESET);
  42. }
  43. template<typename... Args>
  44. void logError(const FormatLocation& format, Args&&... args) {
  45. if constexpr(LOG_LEVEL >= 1) {
  46. String<32> s;
  47. s.addFormat("{}[ERROR] ", Terminal::FG_RED);
  48. log(LogLevel::ERROR, s, format, forward<Args>(args)...);
  49. }
  50. }
  51. template<typename... Args>
  52. void logWarning(const FormatLocation& format, Args&&... args) {
  53. if constexpr(LOG_LEVEL >= 2) {
  54. String<32> s;
  55. s.addFormat("{}[WARNING] ", Terminal::FG_BRIGHT_YELLOW);
  56. log(LogLevel::WARNING, s, format, forward<Args>(args)...);
  57. }
  58. }
  59. template<typename... Args>
  60. void logInfo(const FormatLocation& format, Args&&... args) {
  61. if constexpr(LOG_LEVEL >= 3) {
  62. String<32> s;
  63. s.addFormat("{}[INFO] ", Terminal::BOLD);
  64. log(LogLevel::INFO, s, format, forward<Args>(args)...);
  65. }
  66. }
  67. template<typename... Args>
  68. void logDebug(const FormatLocation& format, Args&&... args) {
  69. if constexpr(LOG_LEVEL >= 4) {
  70. String<32> s;
  71. s.addFormat(
  72. "{}{}[DEBUG] ", Terminal::BOLD, Terminal::FG_BRIGHT_BLACK);
  73. log(LogLevel::DEBUG, s, format, forward<Args>(args)...);
  74. }
  75. }
  76. }