github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/prober/logger/adapter.go (about)

     1  package logger
     2  
     3  import (
     4  	"context"
     5  	"log/slog"
     6  	"time"
     7  )
     8  
     9  // ToSlog creates a new *slog.Logger that adapts the given Logger to the slog interface
    10  func ToSlog(logger Logger) *slog.Logger {
    11  	return slog.New(slogHandler{logger: logger})
    12  }
    13  
    14  // slogHandler is an adapter that converts Logger to slog.Handler
    15  type slogHandler struct {
    16  	logger Logger
    17  }
    18  
    19  func (h slogHandler) Enabled(ctx context.Context, level slog.Level) bool {
    20  	return true
    21  }
    22  
    23  func (h slogHandler) Handle(ctx context.Context, r slog.Record) error {
    24  	// Convert slog.Record to key-value pairs for logger.Logger
    25  	attrs := make([]any, 0)
    26  	attrs = append(attrs, "level", r.Level.String())
    27  	attrs = append(attrs, "msg", r.Message)
    28  	attrs = append(attrs, "time", r.Time.Format(time.RFC3339Nano))
    29  
    30  	r.Attrs(func(attr slog.Attr) bool {
    31  		attrs = append(attrs, attr.Key, attr.Value.String())
    32  		return true
    33  	})
    34  
    35  	return h.logger.Log(attrs...)
    36  }
    37  
    38  func (h slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
    39  	// This method is required by the slog.Handler interface but we can return the handler itself
    40  	// since our Logger interface doesn't support structured logging with persistent attributes.
    41  	// In a more complete implementation, we would create a new handler that combines
    42  	// these attributes with any attributes added in future logging calls.
    43  	return h
    44  }
    45  
    46  func (h slogHandler) WithGroup(name string) slog.Handler {
    47  	// This method is required by the slog.Handler interface but we can return the handler itself
    48  	// since our Logger interface doesn't support attribute grouping.
    49  	// In a more complete implementation, we would track the group name and prefix attribute keys.
    50  	return h
    51  }