statlog.cc 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #ifndef _GNU_SOURCE
  2. #define _GNU_SOURCE
  3. #endif
  4. #include "common/statlog.h"
  5. #include "common/util.h"
  6. #include <stdio.h>
  7. #include <mutex>
  8. #include <zmq.h>
  9. class StatlogState : public LogState {
  10. public:
  11. StatlogState() : LogState("ipc:///tmp/stats") {}
  12. };
  13. static StatlogState s = {};
  14. static void log(const char* metric_type, const char* metric, const char* fmt, ...) {
  15. std::lock_guard lk(s.lock);
  16. if (!s.initialized) s.initialize();
  17. char* value_buf = nullptr;
  18. va_list args;
  19. va_start(args, fmt);
  20. int ret = vasprintf(&value_buf, fmt, args);
  21. va_end(args);
  22. if (ret > 0 && value_buf) {
  23. char* line_buf = nullptr;
  24. ret = asprintf(&line_buf, "%s:%s|%s", metric, value_buf, metric_type);
  25. if (ret > 0 && line_buf) {
  26. zmq_send(s.sock, line_buf, ret, ZMQ_NOBLOCK);
  27. free(line_buf);
  28. }
  29. free(value_buf);
  30. }
  31. }
  32. void statlog_log(const char* metric_type, const char* metric, int value) {
  33. log(metric_type, metric, "%d", value);
  34. }
  35. void statlog_log(const char* metric_type, const char* metric, float value) {
  36. log(metric_type, metric, "%f", value);
  37. }