underhill_core/get_tracing/
json_common.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Types for the JSON encoding
5
6use guid::Guid;
7use serde::Serialize;
8use serde::Serializer;
9use std::fmt::Display;
10use std::num::NonZeroU64;
11use std::time::Duration;
12
13/// A message in the format that the host expects.
14///
15/// This is generic so that different users can provide different field and
16/// level data.
17// TODO: Remove some redundant fields once the legacy notifications are deprecated.
18#[derive(serde::Serialize)]
19pub struct Message<'a, L: Display, F: Serialize> {
20    #[serde(serialize_with = "serialize_time")]
21    pub timestamp: Duration,
22    #[serde(with = "serde_helpers::as_string")]
23    pub level: L,
24    pub target: &'a str,
25    #[serde(
26        with = "serde_helpers::as_string",
27        skip_serializing_if = "Guid::is_zero"
28    )]
29    pub related_activity_id: Guid,
30    pub fields: F,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub missed_events: Option<NonZeroU64>,
33}
34
35#[derive(serde::Serialize)]
36pub struct KmsgMessage<'a, L: Display, F: Serialize> {
37    #[serde(serialize_with = "serialize_time")]
38    pub timestamp: Duration,
39    #[serde(with = "serde_helpers::as_string")]
40    pub level: L,
41    pub target: &'a str,
42    pub fields: F,
43}
44
45#[derive(serde::Serialize)]
46pub struct SpanMessage<'a, F: Serialize> {
47    #[serde(serialize_with = "serialize_time")]
48    pub timestamp: Duration,
49    pub name: &'a str,
50    pub op_code: u8,
51    pub target: &'a str,
52    pub level: &'a str,
53    #[serde(with = "serde_helpers::as_string")]
54    pub activity_id: Guid,
55    #[serde(
56        with = "serde_helpers::as_string",
57        skip_serializing_if = "Guid::is_zero"
58    )]
59    pub related_activity_id: Guid,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub fields: Option<F>,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub time_taken_ns: Option<u64>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub time_active_ns: Option<u64>,
66}
67
68fn serialize_time<S>(time: &Duration, serializer: S) -> Result<S::Ok, S::Error>
69where
70    S: Serializer,
71{
72    serializer.collect_str(&format_args!(
73        "{}.{:09}s",
74        time.as_secs(),
75        time.subsec_nanos()
76    ))
77}