| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package autodetect_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
"os" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel/sdk/resource" |
| 13 |
|
| 14 |
"go.opentelemetry.io/contrib/detectors/autodetect" |
| 15 |
) |
| 16 |
|
| 17 |
// This environment variable is expected to be a comma-separated list of |
| 18 |
// detectors the user wants for the purpose of the example. It can take any |
| 19 |
// form a user want to parse. |
| 20 |
const envVar = "RESOURCE_DETECTORS" |
| 21 |
|
| 22 |
func init() { |
| 23 |
id := autodetect.ID("my.env.var.detector") |
| 24 |
autodetect.Register(id, func() resource.Detector { |
| 25 |
return MyDetector{} |
| 26 |
}) |
| 27 |
|
| 28 |
_ = os.Setenv(envVar, "host,telemetry.sdk,my.env.var.detector") |
| 29 |
} |
| 30 |
|
| 31 |
func ExampleDetector_envVar() { |
| 32 |
// This example shows how to parse resource.Detectors from an environment |
| 33 |
// variable. |
| 34 |
|
| 35 |
names := strings.Split(os.Getenv(envVar), ",") |
| 36 |
ids := make([]autodetect.ID, 0, len(names)) |
| 37 |
for _, name := range names { |
| 38 |
ids = append(ids, autodetect.ID(name)) |
| 39 |
} |
| 40 |
|
| 41 |
detector, err := autodetect.Detector(ids...) |
| 42 |
if err != nil { |
| 43 |
// Handle the error if parsing fails. |
| 44 |
panic(err) |
| 45 |
} |
| 46 |
|
| 47 |
// Use the detector as needed. |
| 48 |
|
| 49 |
res, err := detector.Detect(context.Background()) |
| 50 |
if err != nil { |
| 51 |
panic(err) |
| 52 |
} |
| 53 |
fmt.Print(enc.Encode(res.Iter())) |
| 54 |
// Output: |
| 55 |
// host.name my.key telemetry.sdk.language telemetry.sdk.name telemetry.sdk.version |
| 56 |
} |