log.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "log.h"
  6. #include "console_server.h"
  7. #include "string_utils.h"
  8. #include "os.h"
  9. #include "string_stream.h"
  10. namespace crown
  11. {
  12. namespace log_internal
  13. {
  14. static StringStream& sanitize(StringStream& ss, const char* msg)
  15. {
  16. using namespace string_stream;
  17. const char* ch = msg;
  18. for (; *ch; ch++)
  19. {
  20. if (*ch == '"')
  21. ss << "\\";
  22. ss << *ch;
  23. }
  24. return ss;
  25. }
  26. static void console_log(const char* msg, LogSeverity::Enum severity)
  27. {
  28. if (!console_server_globals::console())
  29. return;
  30. using namespace string_stream;
  31. static const char* stt[] = { "info", "warning", "error", "debug" };
  32. // Build json message
  33. TempAllocator2048 alloc;
  34. StringStream json(alloc);
  35. json << "{\"type\":\"message\",";
  36. json << "\"severity\":\"" << stt[severity] << "\",";
  37. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  38. console_server_globals::console()->send(c_str(json));
  39. }
  40. void logx(LogSeverity::Enum sev, const char* msg, va_list args)
  41. {
  42. char buf[2048];
  43. int len = vsnprintf(buf, sizeof(buf), msg, args);
  44. if (len > (int)sizeof(buf))
  45. len = sizeof(buf) - 1;
  46. buf[len] = '\0';
  47. console_log(buf, sev);
  48. os::log(buf);
  49. }
  50. void logx(LogSeverity::Enum sev, const char* msg, ...)
  51. {
  52. va_list args;
  53. va_start(args, msg);
  54. logx(sev, msg, args);
  55. va_end(args);
  56. }
  57. } // namespace log
  58. } // namespace crown