open-telemetry / opentelemetry-go

OpenTelemetry Go API and SDK
https://opentelemetry.io/
Apache License 2.0
4.99k stars 1.01k forks source link

sdk/log: Add filtering Processor example #5543

Closed pellared closed 2 days ago

pellared commented 1 week ago

Towards https://github.com/open-telemetry/opentelemetry-go/issues/5065

pellared commented 6 days ago

@MrAlias, do you think it makes sense to add MinSeverityProcessor as an example? I feel uncertain as I would personally would prefer to have it as part of the SDK. However, I am not sure when it happens and this looks like a good example before we can add it.

The alternative, I consider is something like the following:

func ExampleProcessor_filtering() {
    var processor logsdk.Processor = logsdk.NewBatchProcessor(nil)

    processor = &ContextIgnoringProcessor{processor}

    _ = logsdk.NewLoggerProvider(
        logsdk.WithProcessor(processor),
    )
}

type key struct{}

var igoreLogsKey key

// WithIgnoreLogs returns a context which is used by [ContextIgnoringProcessor]
// to filter out logs so that one does not want to process.
func WithIgnoreLogs(ctx context.Context) context.Context {
    return context.WithValue(ctx, igoreLogsKey, true)
}

func ignoreLogs(ctx context.Context) bool {
    _, ok := ctx.Value(igoreLogsKey).(bool)
    return ok
}

// ContextIgnoringProcessor filters out logs when a context deriving from
// [WithIgnoreLogs] is passed to its methods.
type ContextIgnoringProcessor struct {
    logsdk.Processor
}

func (p *ContextIgnoringProcessor) OnEmit(ctx context.Context, record logsdk.Record) error {
    if ignoreLogs(ctx) {
        return nil
    }
    return p.Processor.OnEmit(ctx, record)
}

func (p *ContextIgnoringProcessor) Enabled(ctx context.Context, record logsdk.Record) bool {
    return !ignoreLogs(ctx) && p.Enabled(ctx, record)
}
MrAlias commented 6 days ago

@MrAlias, do you think it makes sense to add MinSeverityProcessor as an example?

I was planning to add it to contrib. That way it can be used by users and when we want to stabilize it we can move it to the core repo.

pellared commented 5 days ago

@MrAlias, I plan to update the example to https://github.com/open-telemetry/opentelemetry-go/pull/5543#issuecomment-2194334650. Let me know if you have a better example proposal if you have any other suggestion.

pellared commented 5 days ago

Ready for another round of reviews after rework.