github.com/castai/kvisor@v1.7.1-0.20240516114728-b3572a2607b5/pkg/logging/export_handler.go (about)

     1  package logging
     2  
     3  import (
     4  	"context"
     5  	"log/slog"
     6  )
     7  
     8  type ExportFunc func(ctx context.Context, record slog.Record)
     9  
    10  func NewExportHandler(ctx context.Context, next slog.Handler, cfg ExportConfig) slog.Handler {
    11  	handler := &ExportHandler{
    12  		next: next,
    13  		cfg:  cfg,
    14  		ch:   make(chan slog.Record, 1000),
    15  	}
    16  	go handler.run(ctx)
    17  
    18  	return handler
    19  }
    20  
    21  type ExportHandler struct {
    22  	next slog.Handler
    23  	cfg  ExportConfig
    24  
    25  	ch chan slog.Record
    26  }
    27  
    28  func (e *ExportHandler) Enabled(ctx context.Context, level slog.Level) bool {
    29  	return e.next.Enabled(ctx, level)
    30  }
    31  
    32  func (e *ExportHandler) Handle(ctx context.Context, record slog.Record) error {
    33  	if record.Level >= e.cfg.MinLevel {
    34  		e.cfg.ExportFunc(ctx, record)
    35  	}
    36  
    37  	return e.next.Handle(ctx, record)
    38  }
    39  
    40  func (e *ExportHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
    41  	return &ExportHandler{
    42  		next: e.next.WithAttrs(attrs),
    43  		cfg:  e.cfg,
    44  		ch:   e.ch,
    45  	}
    46  }
    47  
    48  func (e *ExportHandler) WithGroup(name string) slog.Handler {
    49  	return &ExportHandler{
    50  		next: e.next.WithGroup(name),
    51  		cfg:  e.cfg,
    52  		ch:   e.ch,
    53  	}
    54  }
    55  
    56  func (e *ExportHandler) run(ctx context.Context) {
    57  	for {
    58  		select {
    59  		case <-ctx.Done():
    60  			return
    61  		case record := <-e.ch:
    62  			e.cfg.ExportFunc(ctx, record)
    63  		}
    64  	}
    65  }