Skip to content

Commit b477e34

Browse files
authored
sdk/log: Add filtering Processor example (#5543)
Towards #5065
1 parent d7e5001 commit b477e34

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

sdk/log/example_test.go

+49
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,55 @@ import (
1111
logsdk "go.opentelemetry.io/otel/sdk/log"
1212
)
1313

14+
// Use a processor that filters out records based on the provided context.
15+
func ExampleProcessor_filtering() {
16+
// Existing processor that emits telemetry.
17+
var processor logsdk.Processor = logsdk.NewBatchProcessor(nil)
18+
19+
// Wrap the processor so that it ignores processing log records
20+
// when a context deriving from WithIgnoreLogs is passed
21+
// to the logging methods.
22+
processor = &ContextFilterProcessor{processor}
23+
24+
// The created processor can then be registered with
25+
// the OpenTelemetry Logs SDK using the WithProcessor option.
26+
_ = logsdk.NewLoggerProvider(
27+
logsdk.WithProcessor(processor),
28+
)
29+
}
30+
31+
type key struct{}
32+
33+
var igoreLogsKey key
34+
35+
// WithIgnoreLogs returns a context which is used by [ContextFilterProcessor]
36+
// to filter out log records.
37+
func WithIgnoreLogs(ctx context.Context) context.Context {
38+
return context.WithValue(ctx, igoreLogsKey, true)
39+
}
40+
41+
// ContextFilterProcessor filters out logs when a context deriving from
42+
// [WithIgnoreLogs] is passed to its methods.
43+
type ContextFilterProcessor struct {
44+
logsdk.Processor
45+
}
46+
47+
func (p *ContextFilterProcessor) OnEmit(ctx context.Context, record logsdk.Record) error {
48+
if ignoreLogs(ctx) {
49+
return nil
50+
}
51+
return p.Processor.OnEmit(ctx, record)
52+
}
53+
54+
func (p *ContextFilterProcessor) Enabled(ctx context.Context, record logsdk.Record) bool {
55+
return !ignoreLogs(ctx) && p.Processor.Enabled(ctx, record)
56+
}
57+
58+
func ignoreLogs(ctx context.Context) bool {
59+
_, ok := ctx.Value(igoreLogsKey).(bool)
60+
return ok
61+
}
62+
1463
// Use a processor which redacts sensitive data from some attributes.
1564
func ExampleProcessor_redact() {
1665
// Existing processor that emits telemetry.

0 commit comments

Comments
 (0)