Branch data Line data Source code
1 : : #include <hpactor/tracing/json_exporter.hpp>
2 : : #include <hpactor/tracing/trace_context_parser.hpp>
3 : :
4 : : #include <sstream>
5 : :
6 : : namespace hpactor::tracing {
7 : :
8 : : namespace {
9 : :
10 : 1 : std::string trace_id_hex(const TraceId& id) {
11 : 1 : TraceContext ctx;
12 : 1 : ctx.trace_id = id;
13 : 1 : ctx.span_id.bytes[7] = 1;
14 : 1 : std::string tp = format_traceparent(ctx);
15 : 1 : return tp.substr(3, 32);
16 : 1 : }
17 : :
18 : 1 : std::string span_id_hex(const SpanId& id) {
19 : 1 : TraceContext ctx;
20 : 1 : ctx.trace_id.bytes[15] = 1;
21 : 1 : ctx.span_id = id;
22 : 1 : std::string tp = format_traceparent(ctx);
23 : 1 : return tp.substr(36, 16);
24 : 1 : }
25 : :
26 : : } // namespace
27 : :
28 : 1 : JsonFileExporter::JsonFileExporter(std::string path)
29 : 1 : : path_(std::move(path)), out_(path_, std::ios::app) {}
30 : :
31 : 1 : std::string span_record_to_json(const SpanRecord& record) {
32 : 1 : std::ostringstream os;
33 : 1 : os << R"({"trace_id":")" << trace_id_hex(record.trace_id)
34 : 3 : << R"(","span_id":")" << span_id_hex(record.span_id) << R"(","actor_id":)"
35 : 1 : << record.actor_id.value() << R"(,"type_tag":)" << record.type_tag
36 : 1 : << R"(,"start_ns":)" << record.start_ns << R"(,"end_ns":)"
37 : 1 : << record.end_ns << R"(,"kind":)" << static_cast<int>(record.kind)
38 : 1 : << R"(,"status":)" << static_cast<int>(record.status) << '}';
39 : 1 : return os.str();
40 : 1 : }
41 : :
42 : : result<void>
43 : 1 : JsonFileExporter::export_batch(std::span<const SpanRecord> batch) noexcept {
44 : 1 : std::lock_guard<std::mutex> lock(mutex_);
45 : 1 : if (!out_.is_open()) {
46 : 0 : return result<void>::make(error(errors::unknown, "trace json file not "
47 : 0 : "open"));
48 : : }
49 : 2 : for (const auto& record : batch) {
50 : 1 : out_ << span_record_to_json(record) << '\n';
51 : : }
52 : 1 : out_.flush();
53 : 1 : return result<void>::make();
54 : 1 : }
55 : :
56 : 1 : void JsonFileExporter::shutdown() noexcept {
57 : 1 : std::lock_guard<std::mutex> lock(mutex_);
58 : 1 : if (out_.is_open()) {
59 : 1 : out_.flush();
60 : 1 : out_.close();
61 : : }
62 : 1 : }
63 : :
64 : : } // namespace hpactor::tracing
|