knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/config.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 observability
    18  
    19  import (
    20  	"context"
    21  
    22  	"knative.dev/pkg/observability/metrics"
    23  	"knative.dev/pkg/observability/runtime"
    24  	"knative.dev/pkg/observability/tracing"
    25  )
    26  
    27  type (
    28  	TracingConfig = tracing.Config
    29  	MetricsConfig = metrics.Config
    30  	RuntimeConfig = runtime.Config
    31  )
    32  
    33  type Config struct {
    34  	Tracing TracingConfig `json:"tracing"`
    35  	Metrics MetricsConfig `json:"metrics"`
    36  	Runtime RuntimeConfig `json:"runtime"`
    37  }
    38  
    39  func DefaultConfig() *Config {
    40  	return &Config{
    41  		Tracing: tracing.DefaultConfig(),
    42  		Metrics: metrics.DefaultConfig(),
    43  		Runtime: runtime.DefaultConfig(),
    44  	}
    45  }
    46  
    47  func NewFromMap(m map[string]string) (*Config, error) {
    48  	var err error
    49  	c := DefaultConfig()
    50  
    51  	if c.Tracing, err = tracing.NewFromMap(m); err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	if c.Metrics, err = metrics.NewFromMap(m); err != nil {
    56  		return nil, err
    57  	}
    58  	if c.Runtime, err = runtime.NewFromMap(m); err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return c, nil
    63  }
    64  
    65  type cfgKey struct{}
    66  
    67  // WithConfig associates a observability configuration with the context.
    68  func WithConfig(ctx context.Context, cfg *Config) context.Context {
    69  	return context.WithValue(ctx, cfgKey{}, cfg)
    70  }
    71  
    72  // GetConfig gets the observability config from the provided context.
    73  func GetConfig(ctx context.Context) *Config {
    74  	untyped := ctx.Value(cfgKey{})
    75  	if untyped == nil {
    76  		return nil
    77  	}
    78  	return untyped.(*Config)
    79  }