opentelemetry_resource_detectors/
process.rs

1//! Process resource detector
2//!
3//! Detect process related information like pid, executable name.
4
5use opentelemetry::{KeyValue, StringValue, Value};
6use opentelemetry_sdk::resource::ResourceDetector;
7use opentelemetry_sdk::Resource;
8use std::env::args_os;
9use std::process::id;
10
11/// Detect process information.
12///
13/// This resource detector returns the following information:
14///
15/// - process command line arguments(`process.command_args`), the full command arguments of this
16///   application.
17/// - OS assigned process id(`process.pid`).
18pub struct ProcessResourceDetector;
19
20impl ResourceDetector for ProcessResourceDetector {
21    fn detect(&self) -> Resource {
22        let arguments = args_os();
23        let cmd_arg_val = arguments
24            .into_iter()
25            .map(|arg| arg.to_string_lossy().into_owned().into())
26            .collect::<Vec<StringValue>>();
27        Resource::builder_empty()
28            .with_attributes(vec![
29                KeyValue::new(
30                    opentelemetry_semantic_conventions::attribute::PROCESS_COMMAND_ARGS,
31                    Value::Array(cmd_arg_val.into()),
32                ),
33                KeyValue::new(
34                    opentelemetry_semantic_conventions::attribute::PROCESS_PID,
35                    id() as i64,
36                ),
37            ])
38            .build()
39    }
40}
41
42#[cfg(target_os = "linux")]
43#[cfg(test)]
44mod tests {
45    use super::ProcessResourceDetector;
46    use opentelemetry_sdk::resource::ResourceDetector;
47
48    #[test]
49    fn test_processor_resource_detector() {
50        let resource = ProcessResourceDetector.detect();
51        assert_eq!(resource.len(), 2); // we cannot assert on the values because it changes along with runtime.
52    }
53}