Debian Codegraph @

processors/minsev/example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package minsev_test
5
6 import (
7 "context"
8 "encoding/json"
9 "fmt"
10 "os"
11
12 "go.opentelemetry.io/otel/log"
13 logsdk "go.opentelemetry.io/otel/sdk/log"
14
15 "go.opentelemetry.io/contrib/processors/minsev"
16 )
17
18 type EnvSeverity struct {
19 Var string
20 }
21
22 func (s EnvSeverity) Severity() log.Severity {
23 var sev minsev.Severity
24 _ = sev.UnmarshalText([]byte(os.Getenv(s.Var)))
25 return sev.Severity() // Default to SeverityInfo if not set or error.
26 }
27
28 // This example demonstrates how to use a Severitier that reads from
29 // an environment variable.
30 func ExampleSeveritier_environment() {
31 const key = "LOG_LEVEL"
32 // Mock an environmental variable setup that would be done externally.
33 _ = os.Setenv(key, "error")
34
35 // Existing processor that emits telemetry.
36 var processor logsdk.Processor = logsdk.NewBatchProcessor(nil)
37
38 // Wrap the processor so that it filters by severity level defined
39 // via environmental variable.
40 processor = minsev.NewLogProcessor(processor, EnvSeverity{key})
41 lp := logsdk.NewLoggerProvider(
42 logsdk.WithProcessor(processor),
43 )
44
45 // Show that Logs API respects the minimum severity level processor.
46 l := lp.Logger("ExampleSeveritier")
47
48 ctx := context.Background()
49 params := log.EnabledParameters{Severity: log.SeverityDebug}
50 fmt.Println(l.Enabled(ctx, params))
51
52 params.Severity = log.SeverityError
53 fmt.Println(l.Enabled(ctx, params))
54
55 // Output:
56 // false
57 // true
58 }
59
60 // This example demonstrates how to use a Severitier that reads from a JSON
61 // configuration.
62 func ExampleSeveritier_json() {
63 // Example JSON configuration that specifies the minimum severity level.
64 // This would be provided by the application user.
65 const jsonConfig = `{"log_level":"error"}`
66
67 var config struct {
68 Severity minsev.Severity `json:"log_level"`
69 }
70 if err := json.Unmarshal([]byte(jsonConfig), &config); err != nil {
71 panic(err)
72 }
73
74 // Existing processor that emits telemetry.
75 var processor logsdk.Processor = logsdk.NewBatchProcessor(nil)
76
77 // Wrap the processor so that it filters by severity level defined
78 // in the JSON configuration. Note that the severity level itself is a
79 // Severitier implementation.
80 processor = minsev.NewLogProcessor(processor, config.Severity)
81 lp := logsdk.NewLoggerProvider(logsdk.WithProcessor(processor))
82
83 // Show that Logs API respects the minimum severity level processor.
84 l := lp.Logger("ExampleSeveritier")
85
86 ctx := context.Background()
87 params := log.EnabledParameters{Severity: log.SeverityDebug}
88 fmt.Println(l.Enabled(ctx, params))
89
90 params.Severity = log.SeverityError
91 fmt.Println(l.Enabled(ctx, params))
92
93 // Output:
94 // false
95 // true
96 }