knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/resource/default.go (about)

     1  /*
     2  Copyright 2025 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package resource
    18  
    19  import (
    20  	"os"
    21  
    22  	"knative.dev/pkg/changeset"
    23  	"knative.dev/pkg/observability/semconv"
    24  	"knative.dev/pkg/system"
    25  
    26  	"go.opentelemetry.io/otel/attribute"
    27  	"go.opentelemetry.io/otel/sdk/resource"
    28  )
    29  
    30  const otelServiceNameKey = "OTEL_SERVICE_NAME"
    31  
    32  // Default returns a default OpenTelemetry Resource enriched
    33  // with common Knative/Kubernetes attributes.
    34  //
    35  // It will populate:
    36  // - Namespace using system.Namespace
    37  // - PodName using system.PodName
    38  // - ServiceVersion with changeset.Get
    39  func Default(serviceName string) *resource.Resource {
    40  	// If the OTEL_SERVICE_NAME is set then let this override
    41  	// our own serviceName
    42  	if name := os.Getenv(otelServiceNameKey); name != "" {
    43  		serviceName = name
    44  	}
    45  
    46  	attrs := []attribute.KeyValue{
    47  		semconv.K8SNamespaceName(system.Namespace()),
    48  		semconv.ServiceVersion(changeset.Get()),
    49  		semconv.ServiceName(serviceName),
    50  	}
    51  
    52  	if pn := system.PodName(); pn != "" {
    53  		attrs = append(attrs, semconv.K8SPodName(pn))
    54  	}
    55  
    56  	// Ignore the error because it complains about semconv
    57  	// schema version differences
    58  	resource, err := resource.Merge(
    59  		resource.Default(),
    60  		resource.NewWithAttributes(
    61  			semconv.SchemaURL,
    62  			attrs...,
    63  		),
    64  	)
    65  	if err != nil {
    66  		panic(err)
    67  	}
    68  	return resource
    69  }