lambda_otel_utils/
resource.rs

1use opentelemetry::KeyValue;
2use opentelemetry_sdk::Resource;
3use std::env;
4
5/// Retrieves the Lambda resource with the service name.
6///
7/// This function attempts to retrieve the service name from the `OTEL_SERVICE_NAME` environment variable.
8/// If that variable is not set, it falls back to the `AWS_LAMBDA_FUNCTION_NAME` environment variable.
9/// If neither variable is set, it defaults to "unknown-service".
10///
11/// The function then creates a new `Resource` with the detected Lambda resource information
12/// and merges it with a new `Resource` containing the service name key-value pair.
13///
14/// # Returns
15///
16/// A `Resource` representing the Lambda resource with the service name.
17pub fn get_lambda_resource() -> Resource {
18    let mut attributes = Vec::new();
19
20    // Add standard Lambda attributes
21    if let Ok(region) = env::var("AWS_REGION") {
22        attributes.push(KeyValue::new("cloud.provider", "aws"));
23        attributes.push(KeyValue::new("cloud.region", region));
24    }
25
26    if let Ok(function_name) = env::var("AWS_LAMBDA_FUNCTION_NAME") {
27        attributes.push(KeyValue::new("faas.name", function_name.clone()));
28        // Use function name as service name if not set
29        if env::var("OTEL_SERVICE_NAME").is_err() {
30            attributes.push(KeyValue::new("service.name", function_name));
31        }
32    }
33
34    if let Ok(version) = env::var("AWS_LAMBDA_FUNCTION_VERSION") {
35        attributes.push(KeyValue::new("faas.version", version));
36    }
37
38    if let Ok(memory) = env::var("AWS_LAMBDA_FUNCTION_MEMORY_SIZE") {
39        if let Ok(memory_mb) = memory.parse::<i64>() {
40            let memory_bytes = memory_mb * 1024 * 1024;
41            attributes.push(KeyValue::new("faas.max_memory", memory_bytes));
42        }
43    }
44
45    if let Ok(log_stream) = env::var("AWS_LAMBDA_LOG_STREAM_NAME") {
46        attributes.push(KeyValue::new("faas.instance", log_stream));
47    }
48
49    // create resource with standard attributes and merge with custom attributes
50    Resource::builder().with_attributes(attributes).build()
51}