Add independent log level control for stderr and OTLP loggers. Both can be configured via environment variables or programmatically at runtime. - Add SetLevel() and SetOTLPLevel() for runtime control - Add ParseLevel() to convert strings to slog.Level - Support LOG_LEVEL and OTLP_LOG_LEVEL env vars - Maintain backward compatibility with DEBUG env var - Add comprehensive test coverage
49 lines
1.4 KiB
Go
49 lines
1.4 KiB
Go
package logger
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
)
|
|
|
|
// otlpLevelHandler is a wrapper that enforces level checking for OTLP handlers.
|
|
// This allows independent level control for OTLP output separate from stderr logging.
|
|
type otlpLevelHandler struct {
|
|
next slog.Handler
|
|
}
|
|
|
|
// newOTLPLevelHandler creates a new OTLP level wrapper handler.
|
|
func newOTLPLevelHandler(next slog.Handler) slog.Handler {
|
|
return &otlpLevelHandler{
|
|
next: next,
|
|
}
|
|
}
|
|
|
|
// Enabled checks if the log level should be processed by the OTLP handler.
|
|
// It uses the OTLPLevel variable to determine if the record should be processed.
|
|
func (h *otlpLevelHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
return level >= OTLPLevel.Level()
|
|
}
|
|
|
|
// Handle processes the log record if the level is enabled.
|
|
// If disabled by level checking, the record is silently dropped.
|
|
func (h *otlpLevelHandler) Handle(ctx context.Context, r slog.Record) error {
|
|
if !h.Enabled(ctx, r.Level) {
|
|
return nil
|
|
}
|
|
return h.next.Handle(ctx, r)
|
|
}
|
|
|
|
// WithAttrs returns a new handler with the specified attributes added.
|
|
func (h *otlpLevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
return &otlpLevelHandler{
|
|
next: h.next.WithAttrs(attrs),
|
|
}
|
|
}
|
|
|
|
// WithGroup returns a new handler with the specified group name.
|
|
func (h *otlpLevelHandler) WithGroup(name string) slog.Handler {
|
|
return &otlpLevelHandler{
|
|
next: h.next.WithGroup(name),
|
|
}
|
|
}
|