opentelemetry_spanprocessor_any/sdk/resource/
process.rs

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