diff --git a/lib/utils/addr.go b/lib/utils/addr.go index b0ab5e4c4e258..3ed10bec068b5 100644 --- a/lib/utils/addr.go +++ b/lib/utils/addr.go @@ -19,7 +19,9 @@ package utils import ( + "context" "fmt" + "log/slog" "net" "net/url" "strconv" @@ -27,7 +29,6 @@ import ( "unicode/utf8" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" apiutils "github.com/gravitational/teleport/api/utils" ) @@ -290,7 +291,7 @@ func GuessHostIP() (ip net.IP, err error) { for _, iface := range ifaces { ifadrs, err := iface.Addrs() if err != nil { - log.Warn(err) + slog.WarnContext(context.Background(), "Unable to get addresses for interface", "interface", iface.Name, "error", err) } else { adrs = append(adrs, ifadrs...) } diff --git a/lib/utils/agentconn/agent_windows.go b/lib/utils/agentconn/agent_windows.go index d00eb81637ab2..850f791eb044a 100644 --- a/lib/utils/agentconn/agent_windows.go +++ b/lib/utils/agentconn/agent_windows.go @@ -22,8 +22,10 @@ package agentconn import ( + "context" "encoding/binary" "encoding/hex" + "log/slog" "net" "os" "os/exec" @@ -33,7 +35,6 @@ import ( "github.com/Microsoft/go-winio" "github.com/gravitational/trace" - "github.com/sirupsen/logrus" apiutils "github.com/gravitational/teleport/api/utils" ) @@ -214,7 +215,7 @@ func getCygwinUIDFromPS() (uint32, error) { // preform a successful handshake with it. Handshake details here: // https://stackoverflow.com/questions/23086038/what-mechanism-is-used-by-msys-cygwin-to-emulate-unix-domain-sockets func attemptCygwinHandshake(port, key string, uid uint32) (net.Conn, error) { - logrus.Debugf("[KEY AGENT] attempting a handshake with Cygwin ssh-agent socket; port=%s uid=%d", port, uid) + slog.DebugContext(context.Background(), "[KEY AGENT] attempting a handshake with Cygwin ssh-agent socket", "port", port, "uid", uid) conn, err := net.Dial("tcp", "localhost:"+port) if err != nil { diff --git a/lib/utils/aws/credentials.go b/lib/utils/aws/credentials.go index 257d6606d42a9..47c3105174943 100644 --- a/lib/utils/aws/credentials.go +++ b/lib/utils/aws/credentials.go @@ -20,6 +20,7 @@ package aws import ( "context" + "log/slog" "sort" "strings" "time" @@ -33,7 +34,6 @@ import ( "github.com/aws/aws-sdk-go/service/sts" "github.com/gravitational/trace" "github.com/jonboulle/clockwork" - "github.com/sirupsen/logrus" "github.com/gravitational/teleport/lib/modules" "github.com/gravitational/teleport/lib/utils" @@ -70,8 +70,11 @@ func NewCredentialsGetter() CredentialsGetter { } // Get obtains STS credentials. -func (g *credentialsGetter) Get(_ context.Context, request GetCredentialsRequest) (*credentials.Credentials, error) { - logrus.Debugf("Creating STS session %q for %q.", request.SessionName, request.RoleARN) +func (g *credentialsGetter) Get(ctx context.Context, request GetCredentialsRequest) (*credentials.Credentials, error) { + slog.DebugContext(ctx, "Creating STS session", + "session_name", request.SessionName, + "role_arn", request.RoleARN, + ) return stscreds.NewCredentials(request.Provider, request.RoleARN, func(cred *stscreds.AssumeRoleProvider) { cred.RoleSessionName = MaybeHashRoleSessionName(request.SessionName) diff --git a/lib/utils/config.go b/lib/utils/config.go index 2a68f2efdce6c..969ccb8a8508b 100644 --- a/lib/utils/config.go +++ b/lib/utils/config.go @@ -19,12 +19,13 @@ package utils import ( + "context" + "log/slog" "os" "path/filepath" "strings" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" ) // TryReadValueAsFile is a utility function to read a value @@ -44,7 +45,7 @@ func TryReadValueAsFile(value string) (string, error) { out := strings.TrimSpace(string(contents)) if out == "" { - log.Warnf("Empty config value file: %v", value) + slog.WarnContext(context.Background(), "Empty config value file", "file", value) } return out, nil } diff --git a/lib/utils/diagnostics/latency/monitor.go b/lib/utils/diagnostics/latency/monitor.go index bbd2e98fa0782..cdfe08248c1f2 100644 --- a/lib/utils/diagnostics/latency/monitor.go +++ b/lib/utils/diagnostics/latency/monitor.go @@ -20,19 +20,20 @@ package latency import ( "context" + "errors" "sync/atomic" "time" "github.com/google/uuid" "github.com/gravitational/trace" "github.com/jonboulle/clockwork" - "github.com/sirupsen/logrus" "github.com/gravitational/teleport" "github.com/gravitational/teleport/api/utils/retryutils" + logutils "github.com/gravitational/teleport/lib/utils/log" ) -var log = logrus.WithField(teleport.ComponentKey, "latency") +var logger = logutils.NewPackageLogger(teleport.ComponentKey, "latency") // Statistics contain latency measurements for both // legs of a proxied connection. @@ -188,8 +189,8 @@ func (m *Monitor) Run(ctx context.Context) { for { select { case <-m.reportTimer.Chan(): - if err := m.reporter.Report(ctx, m.GetStats()); err != nil { - log.WithError(err).Warn("failed to report latency stats") + if err := m.reporter.Report(ctx, m.GetStats()); err != nil && !errors.Is(err, context.Canceled) { + logger.WarnContext(ctx, "failed to report latency stats", "error", err) } m.reportTimer.Reset(retryutils.SeventhJitter(m.reportInterval)) case <-ctx.Done(): @@ -205,8 +206,8 @@ func (m *Monitor) pingLoop(ctx context.Context, pinger Pinger, timer clockwork.T return case <-timer.Chan(): then := m.clock.Now() - if err := pinger.Ping(ctx); err != nil { - log.WithError(err).Warn("unexpected failure sending ping") + if err := pinger.Ping(ctx); err != nil && !errors.Is(err, context.Canceled) { + logger.WarnContext(ctx, "unexpected failure sending ping", "error", err) } else { latency.Store(m.clock.Now().Sub(then).Milliseconds()) } diff --git a/lib/utils/envutils/environment.go b/lib/utils/envutils/environment.go index 19380be212f5f..ab3e34ad908cb 100644 --- a/lib/utils/envutils/environment.go +++ b/lib/utils/envutils/environment.go @@ -20,13 +20,13 @@ package envutils import ( "bufio" + "context" "fmt" "io" + "log/slog" "os" "strings" - log "github.com/sirupsen/logrus" - "github.com/gravitational/teleport" "github.com/gravitational/teleport/lib/utils" ) @@ -39,7 +39,10 @@ func ReadEnvironmentFile(filename string) ([]string, error) { // having this file for the user is optional. file, err := utils.OpenFileNoUnsafeLinks(filename) if err != nil { - log.Warnf("Unable to open environment file %v: %v, skipping", filename, err) + slog.WarnContext(context.Background(), "Unable to open environment file, skipping", + "file", filename, + "error", err, + ) return []string{}, nil } defer file.Close() @@ -51,6 +54,7 @@ func readEnvironment(r io.Reader) ([]string, error) { var lineno int env := &SafeEnv{} + ctx := context.Background() scanner := bufio.NewScanner(r) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) @@ -59,7 +63,9 @@ func readEnvironment(r io.Reader) ([]string, error) { // https://github.com/openssh/openssh-portable/blob/master/session.c#L873-L874 lineno = lineno + 1 if lineno > teleport.MaxEnvironmentFileLines { - log.Warnf("Too many lines in environment file, returning first %v lines", teleport.MaxEnvironmentFileLines) + slog.WarnContext(ctx, "Too many lines in environment file, limiting how many are consumed", + "lines_consumed", teleport.MaxEnvironmentFileLines, + ) return *env, nil } @@ -71,7 +77,7 @@ func readEnvironment(r io.Reader) ([]string, error) { // split on first =, if not found, log it and continue idx := strings.Index(line, "=") if idx == -1 { - log.Debugf("Bad line %v while reading environment file: no = separator found", lineno) + slog.DebugContext(ctx, "Bad line while reading environment file: no = separator found", "line_number", lineno) continue } @@ -79,7 +85,7 @@ func readEnvironment(r io.Reader) ([]string, error) { key := line[:idx] value := line[idx+1:] if strings.TrimSpace(key) == "" { - log.Debugf("Bad line %v while reading environment file: key without name", lineno) + slog.DebugContext(ctx, "Bad line while reading environment file: key without name", "line_number", lineno) continue } @@ -88,7 +94,7 @@ func readEnvironment(r io.Reader) ([]string, error) { } if err := scanner.Err(); err != nil { - log.Warnf("Unable to read environment file: %v", err) + slog.WarnContext(ctx, "Unable to read environment file", "error", err) return []string{}, nil } diff --git a/lib/utils/fanoutbuffer/buffer.go b/lib/utils/fanoutbuffer/buffer.go index 180ef0aa6bd4a..e7a1a600e935f 100644 --- a/lib/utils/fanoutbuffer/buffer.go +++ b/lib/utils/fanoutbuffer/buffer.go @@ -21,13 +21,13 @@ package fanoutbuffer import ( "context" "errors" + "log/slog" "runtime" "sync" "sync/atomic" "time" "github.com/jonboulle/clockwork" - log "github.com/sirupsen/logrus" ) // ErrGracePeriodExceeded is an error returned by Cursor.Read indicating that the cursor fell @@ -380,7 +380,7 @@ func finalizeCursor[T any](cursor *Cursor[T]) { } cursor.closeLocked() - log.Warn("Fanout buffer cursor was never closed. (this is a bug)") + slog.WarnContext(context.Background(), "Fanout buffer cursor was never closed. (this is a bug)") } // Close closes the cursor. Close is safe to double-call and should be called as soon as possible if diff --git a/lib/utils/host/hostusers.go b/lib/utils/host/hostusers.go index 3123d1a5d8879..de3ce20b5d69d 100644 --- a/lib/utils/host/hostusers.go +++ b/lib/utils/host/hostusers.go @@ -21,7 +21,9 @@ package host import ( "bufio" "bytes" + "context" "errors" + "log/slog" "os" "os/exec" "os/user" @@ -29,7 +31,6 @@ import ( "strings" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" ) // man GROUPADD(8), exit codes section @@ -55,7 +56,10 @@ func GroupAdd(groupname string, gid string) (exitCode int, err error) { cmd := exec.Command(groupaddBin, args...) output, err := cmd.CombinedOutput() - log.Debugf("%s output: %s", cmd.Path, string(output)) + slog.DebugContext(context.Background(), "groupadd command completed", + "command_path", cmd.Path, + "output", string(output), + ) switch code := cmd.ProcessState.ExitCode(); code { case GroupExistExit: @@ -122,7 +126,7 @@ func UserAdd(username string, groups []string, opts UserOpts) (exitCode int, err if opts.Shell != "" { if shell, err := exec.LookPath(opts.Shell); err != nil { - log.Warnf("configured shell %q not found, falling back to host default", opts.Shell) + slog.WarnContext(context.Background(), "configured shell not found, falling back to host default", "shell", opts.Shell) } else { args = append(args, "--shell", shell) } @@ -130,7 +134,10 @@ func UserAdd(username string, groups []string, opts UserOpts) (exitCode int, err cmd := exec.Command(useraddBin, args...) output, err := cmd.CombinedOutput() - log.Debugf("%s output: %s", cmd.Path, string(output)) + slog.DebugContext(context.Background(), "useradd command completed", + "command_path", cmd.Path, + "output", string(output), + ) if cmd.ProcessState.ExitCode() == UserExistExit { return cmd.ProcessState.ExitCode(), trace.AlreadyExists("user already exists") } @@ -147,7 +154,10 @@ func SetUserGroups(username string, groups []string) (exitCode int, err error) { // usermod -G (replace groups) (username) cmd := exec.Command(usermodBin, "-G", strings.Join(groups, ","), username) output, err := cmd.CombinedOutput() - log.Debugf("%s output: %s", cmd.Path, string(output)) + slog.DebugContext(context.Background(), "usermod completed", + "command_path", cmd.Path, + "output", string(output), + ) return cmd.ProcessState.ExitCode(), trace.Wrap(err) } @@ -170,7 +180,10 @@ func UserDel(username string) (exitCode int, err error) { // userdel --remove (remove home) username cmd := exec.Command(userdelBin, args...) output, err := cmd.CombinedOutput() - log.Debugf("%s output: %s", cmd.Path, string(output)) + slog.DebugContext(context.Background(), "usedel command completed", + "command_path", cmd.Path, + "output", string(output), + ) return cmd.ProcessState.ExitCode(), trace.Wrap(err) } diff --git a/lib/utils/loadbalancer.go b/lib/utils/loadbalancer.go index c201f8e60a79c..6a256e9113bbe 100644 --- a/lib/utils/loadbalancer.go +++ b/lib/utils/loadbalancer.go @@ -22,15 +22,16 @@ import ( "context" "errors" "io" + "log/slog" "math/rand/v2" "net" "sync" "time" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "github.com/gravitational/teleport" + logutils "github.com/gravitational/teleport/lib/utils/log" ) // NewLoadBalancer returns new load balancer listening on frontend @@ -58,12 +59,10 @@ func newLoadBalancer(ctx context.Context, frontend NetAddr, policy loadBalancerP policy: policy, waitCtx: waitCtx, waitCancel: waitCancel, - Entry: log.WithFields(log.Fields{ - teleport.ComponentKey: "loadbalancer", - teleport.ComponentFields: log.Fields{ - "listen": frontend.String(), - }, - }), + logger: slog.With( + teleport.ComponentKey, "loadbalancer", + "frontend_addr", frontend.FullAddress(), + ), connections: make(map[NetAddr]map[int64]net.Conn), }, nil } @@ -103,8 +102,8 @@ func randomPolicy() loadBalancerPolicy { // balancer used in tests. type LoadBalancer struct { sync.RWMutex - connID int64 - *log.Entry + connID int64 + logger *slog.Logger frontend NetAddr backends []NetAddr ctx context.Context @@ -156,7 +155,7 @@ func (l *LoadBalancer) AddBackend(b NetAddr) { l.Lock() defer l.Unlock() l.backends = append(l.backends, b) - l.Debugf("Backends %v.", l.backends) + l.logger.DebugContext(l.ctx, "Backends updated", "backends", l.backends) } // RemoveBackend removes backend @@ -205,7 +204,9 @@ func (l *LoadBalancer) Listen() error { if err != nil { return trace.ConvertSystemError(err) } - l.Debugf("created listening socket on %q", l.listener.Addr()) + l.logger.DebugContext(l.ctx, "created listening socket", + "listen_addr", logutils.StringerAttr(l.listener.Addr()), + ) return nil } @@ -231,7 +232,7 @@ func (l *LoadBalancer) Serve() error { case <-l.ctx.Done(): return trace.Wrap(net.ErrClosed, "context is closing") case <-time.After(5. * time.Second): - l.Debugf("Backoff on network error.") + l.logger.DebugContext(l.ctx, "Backoff on network error") } } else { go l.forwardConnection(conn) @@ -242,7 +243,7 @@ func (l *LoadBalancer) Serve() error { func (l *LoadBalancer) forwardConnection(conn net.Conn) { err := l.forward(conn) if err != nil { - l.Warningf("Failed to forward connection: %v.", err) + l.logger.WarnContext(l.ctx, "Failed to forward connection", "error", err) } } @@ -278,11 +279,11 @@ func (l *LoadBalancer) forward(conn net.Conn) error { backendConnID := l.trackConnection(backend, backendConn) defer l.untrackConnection(backend, backendConnID) - logger := l.WithFields(log.Fields{ - "source": conn.RemoteAddr(), - "dest": backendConn.RemoteAddr(), - }) - logger.Debugf("forward") + logger := l.logger.With( + "source_addr", logutils.StringerAttr(conn.RemoteAddr()), + "dest_addr", logutils.StringerAttr(backendConn.RemoteAddr()), + ) + logger.DebugContext(l.ctx, "forwarding data") messagesC := make(chan error, 2) @@ -305,7 +306,7 @@ func (l *LoadBalancer) forward(conn net.Conn) error { select { case err := <-messagesC: if err != nil && !errors.Is(err, io.EOF) { - logger.Warningf("connection problem: %v %T", trace.DebugReport(err), err) + logger.WarnContext(l.ctx, "connection problem", "error", err) lastErr = err } case <-l.ctx.Done(): diff --git a/lib/utils/proxy/proxy.go b/lib/utils/proxy/proxy.go index c34356dd981a5..f9995b0c12a92 100644 --- a/lib/utils/proxy/proxy.go +++ b/lib/utils/proxy/proxy.go @@ -25,18 +25,16 @@ import ( "time" "github.com/gravitational/trace" - "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" "github.com/gravitational/teleport" apiclient "github.com/gravitational/teleport/api/client" tracessh "github.com/gravitational/teleport/api/observability/tracing/ssh" apiutils "github.com/gravitational/teleport/api/utils" + logutils "github.com/gravitational/teleport/lib/utils/log" ) -var log = logrus.WithFields(logrus.Fields{ - teleport.ComponentKey: teleport.ComponentConnectProxy, -}) +var log = logutils.NewPackageLogger(teleport.ComponentKey, teleport.ComponentConnectProxy) // A Dialer is a means for a client to establish a SSH connection. type Dialer interface { @@ -194,13 +192,15 @@ func DialerFromEnvironment(addr string, opts ...DialerOptionFunc) Dialer { // If no proxy settings are in environment return regular ssh dialer, // otherwise return a proxy dialer. if proxyURL == nil { - log.Debugf("No proxy set in environment, returning direct dialer.") + log.DebugContext(context.Background(), "No proxy set in environment, returning direct dialer") return directDial{ alpnDialer: options.alpnDialer, proxyHeaderGetter: options.proxyHeaderGetter, } } - log.Debugf("Found proxy %q in environment, returning proxy dialer.", proxyURL) + log.DebugContext(context.Background(), "Found proxy in environment, returning proxy dialer", + "proxy_url", logutils.StringerAttr(proxyURL), + ) return proxyDial{ proxyURL: proxyURL, insecure: options.insecureSkipTLSVerify, diff --git a/lib/utils/proxyconn_test.go b/lib/utils/proxyconn_test.go index cf7a8a82faf35..0eae440a4f72b 100644 --- a/lib/utils/proxyconn_test.go +++ b/lib/utils/proxyconn_test.go @@ -22,6 +22,7 @@ import ( "context" "fmt" "io" + "log/slog" "net" "strings" "testing" @@ -29,7 +30,6 @@ import ( "github.com/google/uuid" "github.com/gravitational/trace" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" "github.com/gravitational/teleport" @@ -115,7 +115,7 @@ func TestProxyConnCancel(t *testing.T) { type echoServer struct { listener net.Listener - log logrus.FieldLogger + log *slog.Logger } func newEchoServer() (*echoServer, error) { @@ -125,7 +125,7 @@ func newEchoServer() (*echoServer, error) { } return &echoServer{ listener: listener, - log: logrus.WithField(teleport.ComponentKey, "echo"), + log: slog.With(teleport.ComponentKey, "echo"), }, nil } @@ -154,7 +154,7 @@ func (s *echoServer) handleConn(conn net.Conn) error { if err != nil { return trace.Wrap(err) } - s.log.Infof("Received message: %s.", b) + s.log.InfoContext(context.Background(), "Received message", "receieved_message", string(b)) _, err = conn.Write(b) if err != nil { diff --git a/lib/utils/registry/registry_windows.go b/lib/utils/registry/registry_windows.go index 9b41f3b505fbf..b34bdaa58cb3b 100644 --- a/lib/utils/registry/registry_windows.go +++ b/lib/utils/registry/registry_windows.go @@ -19,12 +19,13 @@ package registry import ( + "context" "errors" + "log/slog" "os" "strconv" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "golang.org/x/sys/windows/registry" ) @@ -34,14 +35,17 @@ func GetOrCreateRegistryKey(name string) (registry.Key, error) { reg, err := registry.OpenKey(registry.CURRENT_USER, name, registry.QUERY_VALUE|registry.CREATE_SUB_KEY|registry.SET_VALUE) switch { case errors.Is(err, os.ErrNotExist): - log.Debugf("Registry key %v doesn't exist, trying to create it", name) + slog.DebugContext(context.Background(), "Registry key doesn't exist, trying to create it", "key_name", name) reg, _, err = registry.CreateKey(registry.CURRENT_USER, name, registry.QUERY_VALUE|registry.CREATE_SUB_KEY|registry.SET_VALUE) if err != nil { - log.Debugf("Can't create registry key %v: %v", name, err) + slog.DebugContext(context.Background(), "Can't create registry key", + "key_name", name, + "error", err, + ) return reg, err } case err != nil: - log.Errorf("registry.OpenKey returned error: %v", err) + slog.ErrorContext(context.Background(), "registry.OpenKey returned error", "error", err) return reg, err default: return reg, nil @@ -53,12 +57,35 @@ func GetOrCreateRegistryKey(name string) (registry.Key, error) { func WriteDword(k registry.Key, name string, value string) error { dwordValue, err := strconv.ParseUint(value, 10, 32) if err != nil { + slog.DebugContext(context.Background(), "Failed to convert value to uint32", +<<<<<<< HEAD + "value", value, + "error", err, +||||||| parent of 3ba357996c (Convert lib/utils to slog) log.Debugf("Failed to convert value %v to uint32: %v", value, err) +======= + "value",value, + "error",err, +>>>>>>> 3ba357996c (Convert lib/utils to slog) + ) return trace.Wrap(err) } err = k.SetDWordValue(name, uint32(dwordValue)) if err != nil { + slog.DebugContext(context.Background(), "Failed to write dword to registry key", + "name", name, +<<<<<<< HEAD + "value", value, + "key_name", k, + "error", err, +||||||| parent of 3ba357996c (Convert lib/utils to slog) log.Debugf("Failed to write dword %v: %v to registry key %v: %v", name, value, k, err) +======= + "value",value, + "key_name",k, + "error",err, +>>>>>>> 3ba357996c (Convert lib/utils to slog) + ) return trace.Wrap(err) } return nil @@ -68,7 +95,12 @@ func WriteDword(k registry.Key, name string, value string) error { func WriteString(k registry.Key, name string, value string) error { err := k.SetStringValue(name, value) if err != nil { - log.Debugf("Failed to write string %v: %v to registry key %v: %v", name, value, k, err) + slog.DebugContext(context.Background(), "Failed to write string to registry key", + "name", name, + "value", value, + "key_name", k, + "error", err, + ) return trace.Wrap(err) } return nil @@ -78,7 +110,12 @@ func WriteString(k registry.Key, name string, value string) error { func WriteMultiString(k registry.Key, name string, values []string) error { err := k.SetStringsValue(name, values) if err != nil { - log.Debugf("Failed to write strings %v: %v to registry key %v: %v", name, values, k, err) + slog.DebugContext(context.Background(), "Failed to write strings to registry key", + "name", name, + "values", values, + "key_name", k, + "error", err, + ) return trace.Wrap(err) } return nil diff --git a/lib/utils/socks/socks.go b/lib/utils/socks/socks.go index 374c1a7c41659..afcd5bdacd424 100644 --- a/lib/utils/socks/socks.go +++ b/lib/utils/socks/socks.go @@ -27,15 +27,8 @@ import ( "strconv" "github.com/gravitational/trace" - "github.com/sirupsen/logrus" - - "github.com/gravitational/teleport" ) -var log = logrus.WithFields(logrus.Fields{ - teleport.ComponentKey: teleport.ComponentSOCKS, -}) - const ( socks5Version byte = 0x05 socks5Reserved byte = 0x00 diff --git a/lib/utils/socks/socks_test.go b/lib/utils/socks/socks_test.go index 4babebc5f8882..0dcc2ddcb44c1 100644 --- a/lib/utils/socks/socks_test.go +++ b/lib/utils/socks/socks_test.go @@ -19,7 +19,9 @@ package socks import ( + "context" "io" + "log/slog" "net" "os" "testing" @@ -99,7 +101,7 @@ func (d *debugServer) Serve() { for { conn, err := d.ln.Accept() if err != nil { - log.Debugf("Failed to accept connection: %v.", err) + slog.DebugContext(context.Background(), "Failed to accept connection", "error", err) break } @@ -114,17 +116,17 @@ func (d *debugServer) handle(conn net.Conn) { remoteAddr, err := Handshake(conn) if err != nil { - log.Debugf("Handshake failed: %v.", err) + slog.DebugContext(context.Background(), "Handshake failed", "error", err) return } n, err := conn.Write([]byte(remoteAddr)) if err != nil { - log.Debugf("Failed to write to connection: %v.", err) + slog.DebugContext(context.Background(), "Failed to write to connection", "error", err) return } if n != len(remoteAddr) { - log.Debugf("Short write, wrote %v wanted %v.", n, len(remoteAddr)) + slog.DebugContext(context.Background(), "Short write", "wrote", n, "wanted", len(remoteAddr)) return } } diff --git a/lib/utils/typical/cached_parser.go b/lib/utils/typical/cached_parser.go index 5a60d3724fc35..27b61defd31bf 100644 --- a/lib/utils/typical/cached_parser.go +++ b/lib/utils/typical/cached_parser.go @@ -19,13 +19,14 @@ package typical import ( + "context" + "log/slog" "os" "strconv" "sync/atomic" "github.com/gravitational/trace" lru "github.com/hashicorp/golang-lru/v2" - "github.com/sirupsen/logrus" ) const ( @@ -56,7 +57,7 @@ type CachedParser[TEnv, TResult any] struct { Parser[TEnv, TResult] cache *lru.Cache[string, Expression[TEnv, TResult]] evictedCount atomic.Uint32 - logger logger + logger *slog.Logger } // NewCachedParser creates a cached predicate expression parser with the given specification. @@ -72,7 +73,7 @@ func NewCachedParser[TEnv, TResult any](spec ParserSpec[TEnv], opts ...ParserOpt return &CachedParser[TEnv, TResult]{ Parser: *parser, cache: cache, - logger: logrus.StandardLogger(), + logger: slog.Default(), }, nil } @@ -88,12 +89,9 @@ func (c *CachedParser[TEnv, TResult]) Parse(expression string) (Expression[TEnv, return nil, trace.Wrap(err) } if evicted := c.cache.Add(expression, parsedExpr); evicted && c.evictedCount.Add(1)%logAfterEvictions == 0 { - c.logger.Infof("%d entries have been evicted from the predicate expression cache, consider increasing TELEPORT_EXPRESSION_CACHE_SIZE", - logAfterEvictions) + c.logger.InfoContext(context.Background(), "entries have been evicted from the predicate expression cache, consider increasing TELEPORT_EXPRESSION_CACHE_SIZE", + "eviticiton_count", logAfterEvictions, + ) } return parsedExpr, nil } - -type logger interface { - Infof(fmt string, args ...any) -} diff --git a/lib/utils/typical/cached_parser_test.go b/lib/utils/typical/cached_parser_test.go index 1bfb67bd7f3c3..1f15207ab3f68 100644 --- a/lib/utils/typical/cached_parser_test.go +++ b/lib/utils/typical/cached_parser_test.go @@ -25,14 +25,6 @@ import ( "github.com/stretchr/testify/require" ) -type testLogger struct { - loggedCount int -} - -func (t *testLogger) Infof(msg string, args ...any) { - t.loggedCount++ -} - func TestCachedParser(t *testing.T) { // A simple cached parser with no environment that always returns an int. p, err := NewCachedParser[struct{}, int](ParserSpec[struct{}]{ @@ -45,9 +37,6 @@ func TestCachedParser(t *testing.T) { require.NoError(t, err) require.NotNil(t, p) - var logger testLogger - p.logger = &logger - // Sanity check we still get errors. _, err = p.Parse(`"hello"`) require.Error(t, err) @@ -93,9 +82,6 @@ func TestCachedParser(t *testing.T) { // Check that each new parsed expression results in an eviction. require.Equal(t, uint32(i+1), p.evictedCount.Load()) - - // Check that no log was printed - require.Equal(t, 0, logger.loggedCount) } // Parse one more expression @@ -103,9 +89,6 @@ func TestCachedParser(t *testing.T) { _, err = p.Parse(expr) require.NoError(t, err) - // Check a log was printed once after $logAfterEvictions evictions. - require.Equal(t, 1, logger.loggedCount) - // Parse another $logAfterEvictions unique expressions to cause // another $logAfterEvictions cache evictions and one more log for i := 0; i < logAfterEvictions; i++ { @@ -113,7 +96,4 @@ func TestCachedParser(t *testing.T) { _, err := p.Parse(expr) require.NoError(t, err) } - - // Check a log was printed twice after 2*$logAfterEvictions evictions. - require.Equal(t, 2, logger.loggedCount) } diff --git a/lib/utils/unpack.go b/lib/utils/unpack.go index 14b213f08a173..e42d38283eba2 100644 --- a/lib/utils/unpack.go +++ b/lib/utils/unpack.go @@ -20,15 +20,16 @@ package utils import ( "archive/tar" + "context" "errors" "io" + "log/slog" "os" "path" "path/filepath" "strings" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "github.com/gravitational/teleport" ) @@ -140,7 +141,10 @@ func extractFile(tarball *tar.Reader, header *tar.Header, dir string, dirMode os case tar.TypeSymlink: return writeSymbolicLink(filepath.Join(dir, header.Name), header.Linkname, dirMode) default: - log.Warnf("Unsupported type flag %v for %v.", header.Typeflag, header.Name) + slog.WarnContext(context.Background(), "Unsupported type flag for taball", + "type_flag", header.Typeflag, + "header", header.Name, + ) } return nil } diff --git a/lib/utils/utils.go b/lib/utils/utils.go index 1990f39ad23e2..4008b452ba6a6 100644 --- a/lib/utils/utils.go +++ b/lib/utils/utils.go @@ -24,6 +24,7 @@ import ( "fmt" "io" "io/fs" + "log/slog" "math/rand/v2" "net" "net/url" @@ -38,7 +39,6 @@ import ( "unicode" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/validation" "github.com/gravitational/teleport" @@ -124,13 +124,17 @@ func NewTracer(description string) *Tracer { // Start logs start of the trace func (t *Tracer) Start() *Tracer { - log.Debugf("Tracer started %v.", t.Description) + slog.DebugContext(context.Background(), "Tracer started", + "trace", t.Description) return t } // Stop logs stop of the trace func (t *Tracer) Stop() *Tracer { - log.Debugf("Tracer completed %v in %v.", t.Description, time.Since(t.Started)) + slog.DebugContext(context.Background(), "Tracer completed", + "trace", t.Description, + "duration", time.Since(t.Started), + ) return t }