Documentation
¶
Overview ¶
Package logfilter provides a dynamic, filter-based logging system for Go's slog.
It supports:
- Dynamic log level changes at runtime via LevelVar
- Filter-based level overrides (elevate or suppress logs based on attributes)
- Context value extraction for filtering
- Simple glob-style pattern matching (prefix*, *suffix, *contains*)
- Optional filter expiry for temporary debugging
Basic usage:
// Create a filtered logger
logger := logfilter.New(
logfilter.WithLevel(slog.LevelInfo),
logfilter.WithFormat("json"),
)
// Add filters at runtime
logfilter.SetFilters([]logfilter.LogFilter{
{Type: "job_id", Pattern: "job_abc*", Level: "debug", Enabled: true},
})
// Logs with matching attributes will use filter's level
logger.Debug("processing", "job_id", "job_abc123") // Emitted (filter matches)
logger.Debug("processing", "job_id", "job_xyz") // Suppressed (no match)
Context filtering:
// Register a context extractor
logfilter.RegisterContextExtractor("user_id", func(ctx context.Context) (string, bool) {
if v := ctx.Value(UserIDKey); v != nil {
return v.(string), true
}
return "", false
})
// Use context: prefix in filter type
logfilter.AddFilter(logfilter.LogFilter{
Type: "context:user_id", Pattern: "user_123", Level: "debug", Enabled: true,
})
Index ¶
- Constants
- func AddFilter(filter LogFilter)
- func ClearContextExtractors()
- func ClearFilters()
- func ContextExtractorKeys() []string
- func GetLevel() slog.Level
- func New(opts ...Option) *slog.Logger
- func ParseLevel(level string) slog.Level
- func RegisterContextExtractor(key string, extractor ContextExtractor)
- func RemoveFilter(filterType, pattern string)
- func SetDefault(opts ...Option) *slog.Logger
- func SetFilters(filters []LogFilter)
- func SetLevel(level slog.Level)
- func UnregisterContextExtractor(key string)
- type ContextExtractor
- type Handler
- func (h *Handler) AddFilter(filter LogFilter)
- func (h *Handler) ClearFilters()
- func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool
- func (h *Handler) GetFilters() []LogFilter
- func (h *Handler) Handle(ctx context.Context, r slog.Record) error
- func (h *Handler) RemoveFilter(filterType, pattern string)
- func (h *Handler) SetFilters(filters []LogFilter)
- func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *Handler) WithGroup(name string) slog.Handler
- type LogFilter
- func (f *LogFilter) AttributeKey() string
- func (f *LogFilter) ContextKey() string
- func (f *LogFilter) GetOutputLevel(originalLevel slog.Level) slog.Level
- func (f *LogFilter) HasOutputLevel() bool
- func (f *LogFilter) IsActive() bool
- func (f *LogFilter) IsContextFilter() bool
- func (f *LogFilter) IsExpired() bool
- func (f *LogFilter) IsSourceFileFilter() bool
- func (f *LogFilter) IsSourceFilter() bool
- func (f *LogFilter) IsSourceFunctionFilter() bool
- func (f *LogFilter) Matches(value string) bool
- type Option
Constants ¶
const ( ContextPrefix = "context:" SourceFilePrefix = "source:file" SourceFunctionPrefix = "source:function" )
Source filter type prefixes.
Variables ¶
This section is empty.
Functions ¶
func ClearContextExtractors ¶
func ClearContextExtractors()
ClearContextExtractors removes all registered context extractors. Useful for testing.
func ContextExtractorKeys ¶
func ContextExtractorKeys() []string
ContextExtractorKeys returns the keys of all registered context extractors.
func New ¶
New creates a new slog.Logger with filter support. The returned logger uses the global filter handler, so filters can be updated at runtime using SetFilters, AddFilter, etc.
func ParseLevel ¶
ParseLevel converts a level string to slog.Level.
func RegisterContextExtractor ¶
func RegisterContextExtractor(key string, extractor ContextExtractor)
RegisterContextExtractor registers a function to extract a value from context for the given key. This is used by filters with type "context:key".
Example:
logfilter.RegisterContextExtractor("job_id", func(ctx context.Context) (string, bool) {
if v := ctx.Value(JobIDKey); v != nil {
if s, ok := v.(string); ok {
return s, true
}
}
return "", false
})
func RemoveFilter ¶
func RemoveFilter(filterType, pattern string)
RemoveFilter removes filters matching the given type and pattern.
func SetDefault ¶
SetDefault creates a new logger with the given options and sets it as the default slog logger.
func SetFilters ¶
func SetFilters(filters []LogFilter)
SetFilters replaces all filters on the global handler. Filters are applied in order; first match wins.
func UnregisterContextExtractor ¶
func UnregisterContextExtractor(key string)
UnregisterContextExtractor removes a context extractor for the given key.
Types ¶
type ContextExtractor ¶
ContextExtractor is a function that extracts a string value from context. It should return the value and true if found, or empty string and false if not.
func GetContextExtractor ¶
func GetContextExtractor(key string) ContextExtractor
GetContextExtractor returns the extractor for the given key, or nil if not registered.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is an slog.Handler that supports dynamic log levels and filter-based level overrides. It wraps an inner handler and checks filters before delegating.
func GetHandler ¶
func GetHandler() *Handler
GetHandler returns the global filter handler. This can be used to wrap with additional handlers or for testing.
func NewHandler ¶
NewHandler creates a new filter-aware handler wrapping the given inner handler. The globalLevel is used as the default log level when no filters match.
func (*Handler) Enabled ¶
Enabled reports whether the handler handles records at the given level. It returns true if either: - The level is >= the global level, OR - There are active filters that might match at this level
func (*Handler) GetFilters ¶
GetFilters returns a copy of the current filters.
func (*Handler) Handle ¶
Handle processes a log record, applying filters to determine the effective level. If a matching filter has OutputLevel set, the record's level is transformed before emission.
func (*Handler) RemoveFilter ¶
RemoveFilter removes filters matching the given type and pattern.
func (*Handler) SetFilters ¶
SetFilters replaces all filters with the given list. Filters are applied in order; first match wins.
type LogFilter ¶
type LogFilter struct {
// Type is the attribute key to match (e.g., "job_id", "user_id", "package").
// Special prefixes:
// - "context:key" for context values (e.g., "context:job_id")
// - "source:file" for source file path filtering
// - "source:function" for function name filtering
Type string `json:"type"`
// Pattern for matching the attribute value.
// Supports simple glob-style patterns:
// - "value" exact match
// - "prefix*" prefix match
// - "*suffix" suffix match
// - "*contains*" contains match
Pattern string `json:"pattern"`
// Level is the minimum threshold for logs matching this filter.
// Logs below this level are suppressed, logs at or above pass through.
// Valid values: "debug", "info", "warn", "error"
Level string `json:"level"`
// OutputLevel optionally transforms the log level in the output.
// If set, matching logs are emitted at this level instead of their original level.
// This is useful for elevating debug logs to info so they appear in normal log streams.
// If empty, the original log level is preserved.
// Valid values: "", "debug", "info", "warn", "error"
OutputLevel string `json:"output_level,omitempty"`
// Enabled controls whether this filter is active.
Enabled bool `json:"enabled"`
// ExpiresAt is an optional expiry time for temporary filters.
// If nil or zero, the filter never expires.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
// contains filtered or unexported fields
}
LogFilter defines a log level override based on attribute matching.
func (*LogFilter) AttributeKey ¶
AttributeKey returns the attribute key for attribute filters. Returns the type as-is for non-context and non-source filters.
func (*LogFilter) ContextKey ¶
ContextKey returns the context key for context filters. Returns empty string if not a context filter.
func (*LogFilter) GetOutputLevel ¶
GetOutputLevel returns the parsed output level, or the original level if not set.
func (*LogFilter) HasOutputLevel ¶
HasOutputLevel returns true if this filter transforms the output level.
func (*LogFilter) IsContextFilter ¶
IsContextFilter returns true if this filter checks context values.
func (*LogFilter) IsSourceFileFilter ¶
IsSourceFileFilter returns true if this filter checks source file path.
func (*LogFilter) IsSourceFilter ¶
IsSourceFilter returns true if this filter checks source file or function.
func (*LogFilter) IsSourceFunctionFilter ¶
IsSourceFunctionFilter returns true if this filter checks function name.
type Option ¶
type Option func(*options)
Option configures the logger.
func WithFilters ¶
WithFilters sets the initial filters.
func WithFormat ¶
WithFormat sets the output format ("json" or "text").
func WithOutput ¶
WithOutput sets the output writer (default: os.Stdout).
func WithSource ¶
WithSource enables source file:line in log output.