log.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2012-2016 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. static StringStream& sanitize(StringStream& ss, const char* msg)
  20. {
  21. using namespace string_stream;
  22. const char* ch = msg;
  23. for (; *ch; ch++)
  24. {
  25. if (*ch == '"')
  26. ss << "\\";
  27. ss << *ch;
  28. }
  29. return ss;
  30. }
  31. static void console_log(const char* msg, LogSeverity::Enum sev)
  32. {
  33. if (!console_server_globals::console())
  34. return;
  35. static const char* stt[] = { "info", "warning", "error", "debug" };
  36. // Build json message
  37. using namespace string_stream;
  38. TempAllocator4096 ta;
  39. StringStream json(ta);
  40. json << "{\"type\":\"message\",";
  41. json << "\"severity\":\"" << stt[sev] << "\",";
  42. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  43. console_server_globals::console()->send(c_str(json));
  44. }
  45. void logx(LogSeverity::Enum sev, const char* msg, va_list args)
  46. {
  47. ScopedMutex sm(s_mutex);
  48. char buf[8192];
  49. int len = vsnprintf(buf, sizeof(buf), msg, args);
  50. buf[len] = '\0';
  51. #if CROWN_PLATFORM_POSIX
  52. #define ANSI_RESET "\x1b[0m"
  53. #define ANSI_YELLOW "\x1b[33m"
  54. #define ANSI_RED "\x1b[31m"
  55. static const char* stt[] =
  56. {
  57. ANSI_RESET,
  58. ANSI_YELLOW,
  59. ANSI_RED,
  60. ANSI_RESET
  61. };
  62. os::log(stt[sev]);
  63. os::log(buf);
  64. os::log(ANSI_RESET);
  65. #else
  66. os::log(buf);
  67. #endif
  68. os::log("\n");
  69. if (device())
  70. {
  71. device()->log(buf);
  72. }
  73. console_log(buf, sev);
  74. }
  75. void logx(LogSeverity::Enum sev, const char* msg, ...)
  76. {
  77. va_list args;
  78. va_start(args, msg);
  79. logx(sev, msg, args);
  80. va_end(args);
  81. }
  82. } // namespace log
  83. } // namespace crown