Modern C++ Kafka API
Utility.h
1 #pragma once
2 
3 #include <kafka/Project.h>
4 
5 #include <librdkafka/rdkafka.h>
6 
7 #include <chrono>
8 #include <iomanip>
9 #include <random>
10 #include <sstream>
11 #include <string>
12 #include <time.h>
13 
14 
15 namespace KAFKA_API { namespace utility {
16 
20 inline std::string getLocalTimeString(const std::chrono::system_clock::time_point& timePoint)
21 {
22  auto time = std::chrono::system_clock::to_time_t(timePoint);
23  std::tm tmBuf = {};
24 
25 #if !defined(WIN32)
26  localtime_r(&time, &tmBuf);
27 #else
28  localtime_s(&tmBuf, &time);
29 #endif
30 
31  std::ostringstream oss;
32  oss << std::put_time(&tmBuf, "%F %T") << "." << std::setfill('0') << std::setw(6)
33  << std::chrono::duration_cast<std::chrono::microseconds>(timePoint.time_since_epoch()).count() % 1000000;
34 
35  return oss.str();
36 }
37 
41 inline std::string getCurrentTime()
42 {
43  return getLocalTimeString(std::chrono::system_clock::now());
44 }
45 
49 inline std::string getRandomString()
50 {
51  using namespace std::chrono;
52 
53  const std::uint32_t timestamp = static_cast<std::uint32_t>(duration_cast<nanoseconds>(system_clock::now().time_since_epoch()).count());
54 
55  std::random_device r;
56  std::default_random_engine e(r());
57  std::uniform_int_distribution<std::uint64_t> uniform_dist(0, 0xFFFFFFFF);
58  const std::uint64_t rand = uniform_dist(e);
59 
60  std::ostringstream oss;
61  oss << std::setfill('0') << std::setw(sizeof(std::uint32_t) * 2) << std::hex << timestamp << "-" << rand;
62  return oss.str();
63 }
64 
68 inline std::string getLibRdKafkaVersion()
69 {
70  return rd_kafka_version_str();
71 }
72 
76 inline int getLibRdKafkaThreadCount()
77 {
78  return rd_kafka_thread_cnt();
79 }
80 
81 } } // end of KAFKA_API::utility
82