Debian Codegraph @

sdk/log/example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package log_test
5
6 import (
7 "context"
8 "fmt"
9 "strings"
10
11 logapi "go.opentelemetry.io/otel/log"
12 "go.opentelemetry.io/otel/log/global"
13 "go.opentelemetry.io/otel/sdk/log"
14 )
15
16 // Initialize OpenTelemetry Logs SDK and setup logging using a log bridge.
17 func Example() {
18 // Create an exporter that will emit log records.
19 // E.g. use go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp
20 // to send logs using OTLP over HTTP:
21 // exporter, err := otlploghttp.New(ctx)
22 var exporter log.Exporter
23
24 // Create a log record processor pipeline.
25 processor := log.NewBatchProcessor(exporter)
26
27 // Create a logger provider.
28 // You can pass this instance directly when creating a log bridge.
29 provider := log.NewLoggerProvider(
30 log.WithProcessor(processor),
31 )
32
33 // Handle shutdown properly so that nothing leaks.
34 defer func() {
35 err := provider.Shutdown(context.Background())
36 if err != nil {
37 fmt.Println(err)
38 }
39 }()
40
41 // Register as global logger provider so that it can be used via global.Meter
42 // and accessed using global.GetMeterProvider.
43 // Most log bridges use the global logger provider as default.
44 // If the global logger provider is not set then a no-op implementation
45 // is used, which fails to generate data.
46 global.SetLoggerProvider(provider)
47
48 // Use a bridge so that you can emit logs using your Go logging library of preference.
49 // E.g. use go.opentelemetry.io/contrib/bridges/otelslog so that you can use log/slog:
50 // slog.SetDefault(otelslog.NewLogger("my/pkg/name", otelslog.WithLoggerProvider(provider)))
51 }
52
53 // Use a processor that filters out records based on the provided context.
54 func ExampleProcessor_contextFilter() {
55 // Existing processor that emits telemetry.
56 var processor log.Processor = log.NewBatchProcessor(nil)
57
58 // Wrap the processor so that it ignores processing log records
59 // when a context deriving from WithIgnoreLogs is passed
60 // to the logging methods.
61 processor = &ContextFilterProcessor{Processor: processor}
62
63 // The created processor can then be registered with
64 // the OpenTelemetry Logs SDK using the WithProcessor option.
65 _ = log.NewLoggerProvider(
66 log.WithProcessor(processor),
67 )
68 }
69
70 type key struct{}
71
72 var ignoreLogsKey key
73
74 // WithIgnoreLogs returns a context which is used by [ContextFilterProcessor]
75 // to filter out log records.
76 func WithIgnoreLogs(ctx context.Context) context.Context {
77 return context.WithValue(ctx, ignoreLogsKey, true)
78 }
79
80 // ContextFilterProcessor filters out logs when a context deriving from
81 // [WithIgnoreLogs] is passed to its methods.
82 type ContextFilterProcessor struct {
83 log.Processor
84 }
85
86 func (p *ContextFilterProcessor) OnEmit(ctx context.Context, record *log.Record) error {
87 if ignoreLogs(ctx) {
88 return nil
89 }
90 return p.Processor.OnEmit(ctx, record)
91 }
92
93 func (p *ContextFilterProcessor) Enabled(ctx context.Context, param log.EnabledParameters) bool {
94 return !ignoreLogs(ctx) && p.Processor.Enabled(ctx, param)
95 }
96
97 func ignoreLogs(ctx context.Context) bool {
98 _, ok := ctx.Value(ignoreLogsKey).(bool)
99 return ok
100 }
101
102 // Use a processor which sets EventName on log records having "otel.event.name" string attribute.
103 // This is useful for users of logging libraries that do not support
104 // setting the event name on log records, but do support attributes.
105 func ExampleProcessor_eventName() {
106 // Existing processor that emits telemetry.
107 var processor log.Processor = log.NewBatchProcessor(nil)
108
109 // Add a processor so that it sets EventName on log records.
110 eventNameProcessor := &EventNameProcessor{}
111
112 // The created processor can then be registered with
113 // the OpenTelemetry Logs SDK using the WithProcessor option.
114 _ = log.NewLoggerProvider(
115 // Order is important here. Set EventName before handing to the processor.
116 log.WithProcessor(eventNameProcessor),
117 log.WithProcessor(processor),
118 )
119 }
120
121 // EventNameProcessor is a [log.Processor] that sets the EventName
122 // on log records having "otel.event.name" string attribute.
123 // It is useful for logging libraries that do not support
124 // setting the event name on log records,
125 // but do support attributes.
126 type EventNameProcessor struct{}
127
128 // Enabled returns true, indicating this Processor will process all records.
129 func (*EventNameProcessor) Enabled(context.Context, log.EnabledParameters) bool {
130 return true
131 }
132
133 // OnEmit sets the EventName on log records having an "otel.event.name" string attribute.
134 // The original attribute is not removed.
135 func (*EventNameProcessor) OnEmit(_ context.Context, record *log.Record) error {
136 record.WalkAttributes(func(kv logapi.KeyValue) bool {
137 if kv.Key == "otel.event.name" && kv.Value.Kind() == logapi.KindString {
138 record.SetEventName(kv.Value.AsString())
139 }
140 return true
141 })
142 return nil
143 }
144
145 // Shutdown returns nil.
146 func (*EventNameProcessor) Shutdown(context.Context) error {
147 return nil
148 }
149
150 // ForceFlush returns nil.
151 func (*EventNameProcessor) ForceFlush(context.Context) error {
152 return nil
153 }
154
155 // Use a processor which redacts sensitive data from some attributes.
156 func ExampleProcessor_redact() {
157 // Existing processor that emits telemetry.
158 var processor log.Processor = log.NewBatchProcessor(nil)
159
160 // Add a processor so that it redacts values from token attributes.
161 redactProcessor := &RedactTokensProcessor{}
162
163 // The created processor can then be registered with
164 // the OpenTelemetry Logs SDK using the WithProcessor option.
165 _ = log.NewLoggerProvider(
166 // Order is important here. Redact before handing to the processor.
167 log.WithProcessor(redactProcessor),
168 log.WithProcessor(processor),
169 )
170 }
171
172 // RedactTokensProcessor is a [log.Processor] decorator that redacts values
173 // from attributes containing "token" in the key.
174 type RedactTokensProcessor struct{}
175
176 // Enabled returns true, indicating this Processor will process all records.
177 func (*RedactTokensProcessor) Enabled(context.Context, log.EnabledParameters) bool {
178 return true
179 }
180
181 // OnEmit redacts values from attributes containing "token" in the key
182 // by replacing them with a REDACTED value.
183 func (*RedactTokensProcessor) OnEmit(_ context.Context, record *log.Record) error {
184 record.WalkAttributes(func(kv logapi.KeyValue) bool {
185 if strings.Contains(strings.ToLower(kv.Key), "token") {
186 record.AddAttributes(logapi.String(kv.Key, "REDACTED"))
187 }
188 return true
189 })
190 return nil
191 }
192
193 // Shutdown returns nil.
194 func (*RedactTokensProcessor) Shutdown(context.Context) error {
195 return nil
196 }
197
198 // ForceFlush returns nil.
199 func (*RedactTokensProcessor) ForceFlush(context.Context) error {
200 return nil
201 }