Skip to main content

otel_init/
resource.rs

1use opentelemetry::KeyValue;
2use opentelemetry_sdk::Resource;
3
4/// Creates a resource with the given service name and attributes.
5///
6/// This function builds an OpenTelemetry resource that identifies your service
7/// and includes any additional attributes you want to track.
8///
9/// # Arguments
10///
11/// * `service_name` - The name of your service
12/// * `attributes` - Additional key-value pairs to include in the resource
13///
14/// # Examples
15///
16/// ```rust
17/// use otel_init::get_resource;
18/// use opentelemetry::KeyValue;
19///
20/// let resource = get_resource(
21///     "my-service",
22///     &[KeyValue::new("environment", "production")],
23/// );
24/// ```
25pub fn get_resource(service_name: &str, attributes: &[KeyValue]) -> Resource {
26    Resource::builder()
27        .with_service_name(service_name.to_string())
28        .with_attributes(attributes.to_vec())
29        .build()
30}
31
32#[cfg(test)]
33mod tests {
34    use super::get_resource;
35    use opentelemetry::KeyValue;
36
37    #[test]
38    fn test_get_resource() {
39        let service_name = "test-service";
40        let attributes = vec![
41            KeyValue::new("env", "test"),
42            KeyValue::new("version", "1.0.0"),
43        ];
44
45        let resource = get_resource(service_name, &attributes);
46
47        assert_eq!(
48            resource.get(&opentelemetry::Key::new("service.name")),
49            Some(opentelemetry::Value::String(service_name.into()))
50        );
51
52        assert_eq!(
53            resource.get(&opentelemetry::Key::new("env")),
54            Some(opentelemetry::Value::String("test".into()))
55        );
56
57        assert_eq!(
58            resource.get(&opentelemetry::Key::new("version")),
59            Some(opentelemetry::Value::String("1.0.0".into()))
60        );
61    }
62}