log.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 "log.h"
  7. #include "os.h"
  8. #include "platform.h"
  9. #include "string_stream.h"
  10. #include "string_utils.h"
  11. namespace crown
  12. {
  13. namespace log_internal
  14. {
  15. static StringStream& sanitize(StringStream& ss, const char* msg)
  16. {
  17. using namespace string_stream;
  18. const char* ch = msg;
  19. for (; *ch; ch++)
  20. {
  21. if (*ch == '"')
  22. ss << "\\";
  23. ss << *ch;
  24. }
  25. return ss;
  26. }
  27. static void console_log(const char* msg, LogSeverity::Enum sev)
  28. {
  29. if (!console_server_globals::console())
  30. return;
  31. static const char* stt[] = { "info", "warning", "error", "debug" };
  32. // Build json message
  33. using namespace string_stream;
  34. TempAllocator4096 ta;
  35. StringStream json(ta);
  36. json << "{\"type\":\"message\",";
  37. json << "\"severity\":\"" << stt[sev] << "\",";
  38. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  39. console_server_globals::console()->send(c_str(json));
  40. }
  41. void logx(LogSeverity::Enum sev, const char* msg, va_list args)
  42. {
  43. char buf[8192];
  44. int len = vsnprintf(buf, sizeof(buf), msg, args);
  45. buf[len] = '\0';
  46. #if CROWN_PLATFORM_POSIX
  47. #define ANSI_RESET "\x1b[0m"
  48. #define ANSI_YELLOW "\x1b[33m"
  49. #define ANSI_RED "\x1b[31m"
  50. static const char* stt[] =
  51. {
  52. ANSI_RESET,
  53. ANSI_YELLOW,
  54. ANSI_RED,
  55. ANSI_RESET
  56. };
  57. os::log(stt[sev]);
  58. os::log(buf);
  59. os::log(ANSI_RESET);
  60. #else
  61. os::log(buf);
  62. #endif
  63. os::log("\n");
  64. console_log(buf, sev);
  65. }
  66. void logx(LogSeverity::Enum sev, const char* msg, ...)
  67. {
  68. va_list args;
  69. va_start(args, msg);
  70. logx(sev, msg, args);
  71. va_end(args);
  72. }
  73. } // namespace log
  74. } // namespace crown