opentelemetry_resource_detectors/
process.rs1use opentelemetry::{KeyValue, StringValue, Value};
6use opentelemetry_sdk::resource::ResourceDetector;
7use opentelemetry_sdk::Resource;
8use std::env::args_os;
9use std::process::id;
10
11pub struct ProcessResourceDetector;
22
23impl ResourceDetector for ProcessResourceDetector {
24 fn detect(&self) -> Resource {
25 let arguments = args_os();
26 let cmd_arg_val = arguments
27 .into_iter()
28 .map(|arg| arg.to_string_lossy().into_owned().into())
29 .collect::<Vec<StringValue>>();
30 Resource::builder_empty()
31 .with_attributes(
32 vec![
33 Some(KeyValue::new(
34 opentelemetry_semantic_conventions::attribute::PROCESS_COMMAND_ARGS,
35 Value::Array(cmd_arg_val.into()),
36 )),
37 Some(KeyValue::new(
38 opentelemetry_semantic_conventions::attribute::PROCESS_PID,
39 id() as i64,
40 )),
41 Some(KeyValue::new(
42 opentelemetry_semantic_conventions::attribute::PROCESS_RUNTIME_NAME,
43 "rustc",
44 )),
45 option_env!("RUSTC_VERSION").map(|rustc_version| {
47 KeyValue::new(
48 opentelemetry_semantic_conventions::attribute::PROCESS_RUNTIME_VERSION,
49 rustc_version,
50 )
51 }),
52 option_env!("RUSTC_VERSION_DESCRIPTION").map(|rustc_version_desc| {
54 KeyValue::new(
55 opentelemetry_semantic_conventions::attribute::PROCESS_RUNTIME_DESCRIPTION,
56 rustc_version_desc,
57 )
58 }),
59 ]
60 .into_iter()
61 .flatten(),
62 )
63 .build()
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::ProcessResourceDetector;
70 use opentelemetry_sdk::resource::ResourceDetector;
71 use opentelemetry_semantic_conventions::resource::PROCESS_RUNTIME_DESCRIPTION;
72
73 #[cfg(target_os = "linux")]
74 #[test]
75 fn test_processor_resource_detector() {
76 let resource = ProcessResourceDetector.detect();
77 assert_eq!(resource.len(), 5); }
79
80 #[test]
81 fn test_processor_resource_detector_runtime() {
82 use opentelemetry_semantic_conventions::attribute::{
83 PROCESS_RUNTIME_NAME, PROCESS_RUNTIME_VERSION,
84 };
85
86 let resource = ProcessResourceDetector.detect();
87
88 assert_eq!(
89 resource.get(&PROCESS_RUNTIME_NAME.into()),
90 Some("rustc".into())
91 );
92
93 assert_eq!(
94 resource.get(&PROCESS_RUNTIME_VERSION.into()),
95 Some(env!("RUSTC_VERSION").into())
96 );
97
98 assert_eq!(
99 resource.get(&PROCESS_RUNTIME_DESCRIPTION.into()),
100 Some(env!("RUSTC_VERSION_DESCRIPTION").into())
101 );
102 }
103}