github.com/adevinta/lava@v0.7.2/internal/engine/agentlogger.go (about)

     1  // Copyright 2023 Adevinta
     2  
     3  package engine
     4  
     5  import (
     6  	"context"
     7  	"fmt"
     8  	"log/slog"
     9  	"runtime"
    10  	"time"
    11  )
    12  
    13  // agentLogger wraps [slog] to implement
    14  // [github.com/adevinta/vulcan-agent/log.Logger].
    15  type agentLogger struct {
    16  	logger *slog.Logger
    17  }
    18  
    19  // newAgentLogger creates a new [agentLogger].
    20  func newAgentLogger(l *slog.Logger) agentLogger {
    21  	return agentLogger{logger: l}
    22  }
    23  
    24  // Debugf formats according to a format specifier and logs at
    25  // [slog.LevelDebug].
    26  func (l agentLogger) Debugf(format string, args ...any) {
    27  	l.log(slog.LevelDebug, format, args...)
    28  }
    29  
    30  // Infof formats according to a format specifier and logs at
    31  // [slog.LevelInfo].
    32  func (l agentLogger) Infof(format string, args ...any) {
    33  	l.log(slog.LevelInfo, format, args...)
    34  }
    35  
    36  // Errorf formats according to a format specifier and logs at
    37  // [slog.LevelError].
    38  func (l agentLogger) Errorf(format string, args ...any) {
    39  	l.log(slog.LevelError, format, args...)
    40  }
    41  
    42  // log formats according to a format specifier and logs at the
    43  // specified [slog.Level].
    44  func (l agentLogger) log(level slog.Level, format string, args ...any) {
    45  	if !l.logger.Enabled(context.Background(), level) {
    46  		return
    47  	}
    48  	var pcs [1]uintptr
    49  	runtime.Callers(3, pcs[:]) // skip [Callers, agentLogger.log, agentLogger.Levelf]
    50  	r := slog.NewRecord(time.Now(), level, fmt.Sprintf(format, args...), pcs[0])
    51  	_ = l.logger.Handler().Handle(context.Background(), r)
    52  }