log.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "console_server.h"
  6. #include "device.h"
  7. #include "log.h"
  8. #include "mutex.h"
  9. #include "os.h"
  10. #include "platform.h"
  11. #include "string_stream.h"
  12. #include "string_utils.h"
  13. #include "temp_allocator.h"
  14. namespace crown
  15. {
  16. namespace log_internal
  17. {
  18. static Mutex s_mutex;
  19. void logx(LogSeverity::Enum sev, System system, const char* msg, va_list args)
  20. {
  21. ScopedMutex sm(s_mutex);
  22. char buf[8192];
  23. int len = vsnprintf(buf, sizeof(buf), msg, args);
  24. buf[len] = '\0';
  25. #if CROWN_PLATFORM_POSIX
  26. #define ANSI_RESET "\x1b[0m"
  27. #define ANSI_YELLOW "\x1b[33m"
  28. #define ANSI_RED "\x1b[31m"
  29. static const char* stt[] =
  30. {
  31. ANSI_RESET,
  32. ANSI_YELLOW,
  33. ANSI_RED,
  34. ANSI_RESET
  35. };
  36. os::log(stt[sev]);
  37. os::log(buf);
  38. os::log(ANSI_RESET);
  39. #else
  40. os::log(buf);
  41. #endif
  42. os::log("\n");
  43. if (console_server())
  44. {
  45. static const char* s_severity_map[] = { "info", "warning", "error" };
  46. CE_STATIC_ASSERT(countof(s_severity_map) == LogSeverity::COUNT);
  47. TempAllocator4096 ta;
  48. StringStream json(ta);
  49. json << "{\"type\":\"message\",";
  50. json << "\"severity\":\"";
  51. json << s_severity_map[sev];
  52. json << "\",";
  53. json << "\"system\":\"";
  54. json << system.name;
  55. json << "\",";
  56. json << "\"message\":\"";
  57. // Sanitize buf
  58. const char* ch = buf;
  59. for (; *ch; ch++)
  60. {
  61. if (*ch == '"' || *ch == '\\')
  62. json << "\\";
  63. json << *ch;
  64. }
  65. json << "\"}";
  66. console_server()->send(string_stream::c_str(json));
  67. }
  68. if (device())
  69. device()->log(buf);
  70. }
  71. void logx(LogSeverity::Enum sev, System system, const char* msg, ...)
  72. {
  73. va_list args;
  74. va_start(args, msg);
  75. logx(sev, system, msg, args);
  76. va_end(args);
  77. }
  78. } // namespace log
  79. } // namespace crown