vector/api/schema/events/
log.rs

1use std::borrow::Cow;
2
3use async_graphql::Object;
4use chrono::{DateTime, Utc};
5use vector_lib::encode_logfmt;
6use vector_lib::event;
7use vector_lib::tap::topology::TapOutput;
8use vrl::event_path;
9
10use super::EventEncodingType;
11
12#[derive(Debug, Clone)]
13pub struct Log {
14    output: TapOutput,
15    event: event::LogEvent,
16}
17
18impl Log {
19    pub const fn new(output: TapOutput, event: event::LogEvent) -> Self {
20        Self { output, event }
21    }
22
23    pub fn get_message(&self) -> Option<Cow<'_, str>> {
24        Some(self.event.get(event_path!("message"))?.to_string_lossy())
25    }
26
27    pub fn get_timestamp(&self) -> Option<&DateTime<Utc>> {
28        self.event.get(event_path!("timestamp"))?.as_timestamp()
29    }
30}
31
32#[Object]
33/// Log event with fields for querying log data
34impl Log {
35    /// Id of the component associated with the log event
36    async fn component_id(&self) -> &str {
37        self.output.output_id.component.id()
38    }
39
40    /// Type of component associated with the log event
41    async fn component_type(&self) -> &str {
42        self.output.component_type.as_ref()
43    }
44
45    /// Kind of component associated with the log event
46    async fn component_kind(&self) -> &str {
47        self.output.component_kind
48    }
49
50    /// Log message
51    async fn message(&self) -> Option<String> {
52        self.get_message().map(Into::into)
53    }
54
55    /// Log timestamp
56    async fn timestamp(&self) -> Option<&DateTime<Utc>> {
57        self.get_timestamp()
58    }
59
60    /// Log event as an encoded string format
61    async fn string(&self, encoding: EventEncodingType) -> String {
62        match encoding {
63            EventEncodingType::Json => serde_json::to_string(&self.event)
64                .expect("JSON serialization of log event failed. Please report."),
65            EventEncodingType::Yaml => serde_yaml::to_string(&self.event)
66                .expect("YAML serialization of log event failed. Please report."),
67            EventEncodingType::Logfmt => encode_logfmt::encode_value(self.event.value())
68                .expect("logfmt serialization of log event failed. Please report."),
69        }
70    }
71
72    /// Get JSON field data on the log event, by field name
73    async fn json(&self, field: String) -> Option<String> {
74        self.event.get(event_path!(field.as_str())).map(|field| {
75            serde_json::to_string(field)
76                .expect("JSON serialization of trace event field failed. Please report.")
77        })
78    }
79}