log.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2012-2026 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #include "core/memory/temp_allocator.inl"
  7. #include "core/os.h"
  8. #include "core/platform.h"
  9. #include "core/strings/string.inl"
  10. #include "core/strings/string_stream.inl"
  11. #include "core/thread/scoped_mutex.inl"
  12. #include "device/log.h"
  13. #if CROWN_LOG_TO_CONSOLE
  14. #include "device/console_server.h"
  15. #endif
  16. #include <stb_sprintf.h>
  17. namespace crown
  18. {
  19. namespace log_internal
  20. {
  21. static Mutex s_mutex;
  22. static void stdout_log(LogSeverity::Enum sev, System system, const char *format)
  23. {
  24. char buf[8192];
  25. #if CROWN_PLATFORM_POSIX && !CROWN_PLATFORM_ANDROID && !CROWN_PLATFORM_EMSCRIPTEN
  26. #define ANSI_RESET "\x1b[0m"
  27. #define ANSI_YELLOW "\x1b[33m"
  28. #define ANSI_RED "\x1b[31m"
  29. const char *stt[] = { ANSI_RESET, ANSI_YELLOW, ANSI_RED };
  30. CE_STATIC_ASSERT(countof(stt) == LogSeverity::COUNT);
  31. stbsp_snprintf(buf, sizeof(buf), "%s%s: %s\n" ANSI_RESET, stt[sev], system.name, format);
  32. #else
  33. stbsp_snprintf(buf, sizeof(buf), "%s: %s\n", system.name, format);
  34. #endif
  35. os::log(buf);
  36. }
  37. /// Sends a log message to all clients.
  38. static void console_log(LogSeverity::Enum sev, System system, const char *msg)
  39. {
  40. #if !CROWN_LOG_TO_CONSOLE
  41. CE_UNUSED_3(sev, system, msg);
  42. #else
  43. if (!console_server())
  44. return;
  45. const char *severity_map[] = { "info", "warning", "error" };
  46. CE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);
  47. TempAllocator4096 ta;
  48. StringStream ss(ta);
  49. ss << "{\"type\":\"message\",\"severity\":\"";
  50. ss << severity_map[sev];
  51. ss << "\",\"system\":\"";
  52. ss << system.name;
  53. ss << "\",\"message\":\"";
  54. // Sanitize msg
  55. const char *ch = msg;
  56. for (; *ch; ch++) {
  57. if (*ch == '"' || *ch == '\\')
  58. ss << "\\";
  59. ss << *ch;
  60. }
  61. ss << "\"}";
  62. console_server()->broadcast(string_stream::c_str(ss));
  63. #endif // if !CROWN_LOG_TO_CONSOLE
  64. }
  65. void vlogx(LogSeverity::Enum sev, System system, const char *format, va_list args)
  66. {
  67. ScopedMutex sm(s_mutex);
  68. char buf[8192];
  69. stbsp_vsnprintf(buf, sizeof(buf), format, args);
  70. stdout_log(sev, system, buf);
  71. console_log(sev, system, buf);
  72. }
  73. void logx(LogSeverity::Enum sev, System system, const char *format, ...)
  74. {
  75. va_list args;
  76. va_start(args, format);
  77. vlogx(sev, system, format, args);
  78. va_end(args);
  79. }
  80. } // namespace log
  81. } // namespace crown