Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sdk/log: Add altering Processor example #5550

Merged
merged 4 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions sdk/log/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package log_test

import (
"context"
"strings"

"go.opentelemetry.io/otel/log"
logsdk "go.opentelemetry.io/otel/sdk/log"
)

// Use a processor which redacts sensitive data from some attributes.
func ExampleProcessor_redact() {
// Existing processor that emits telemetry.
var processor logsdk.Processor = logsdk.NewBatchProcessor(nil)

// Wrap the processor so that it redacts values from token attributes.
processor = &RedactTokensProcessor{processor}

// The created processor can then be registered with
// the OpenTelemetry Logs SDK using the WithProcessor option.
_ = logsdk.NewLoggerProvider(
logsdk.WithProcessor(processor),
)
}

// RedactTokensProcessor is a [logsdk.Processor] decorator that redacts values
// from attributes containing "token" in the key.
type RedactTokensProcessor struct {
logsdk.Processor
}

// OnEmit redacts values from attributes containing "token" in the key
// by replacing them with a REDACTED value.
func (s *RedactTokensProcessor) OnEmit(ctx context.Context, record logsdk.Record) error {
record.WalkAttributes(func(kv log.KeyValue) bool {
if strings.Contains(strings.ToLower(kv.Key), "token") {
record.AddAttributes(log.String(kv.Key, "REDACTED"))
}
return true
})
return s.Processor.OnEmit(ctx, record)
}
1 change: 1 addition & 0 deletions sdk/log/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ func (r *Record) WalkAttributes(f func(log.KeyValue) bool) {
}

// AddAttributes adds attributes to the log record.
// Attributes in attrs will overwrite any attribute already added to r with the same key.
func (r *Record) AddAttributes(attrs ...log.KeyValue) {
n := r.AttributesLen()
if n == 0 {
Expand Down