opentelemetry-go icon indicating copy to clipboard operation
opentelemetry-go copied to clipboard

sdk/log: Add filtering Processor example

Open pellared opened this issue 1 year ago • 5 comments

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

pellared avatar Jun 25 '24 11:06 pellared

@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)
}

pellared avatar Jun 27 '24 10:06 pellared

@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.

MrAlias avatar Jun 27 '24 14:06 MrAlias

@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 avatar Jun 27 '24 16:06 pellared

Ready for another round of reviews after rework.

pellared avatar Jun 28 '24 06:06 pellared