Skip to content

Commit

Permalink
Remove logrus
Browse files Browse the repository at this point in the history
  • Loading branch information
rosstimothy committed Jan 7, 2025
1 parent 3a6dea2 commit 737af4b
Show file tree
Hide file tree
Showing 21 changed files with 225 additions and 569 deletions.
2 changes: 1 addition & 1 deletion e
Submodule e updated from f00dbc to bc0a10
9 changes: 0 additions & 9 deletions integration/helpers/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import (
"github.com/gorilla/websocket"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"

Expand Down Expand Up @@ -327,10 +326,6 @@ type InstanceConfig struct {
Priv []byte
// Pub is SSH public key of the instance
Pub []byte
// Log specifies the logger
// Deprecated: Use Logger instead
// TODO(tross): Delete when e is updated
Log utils.Logger
// Logger specifies the logger
Logger *slog.Logger
// Ports is a collection of instance ports.
Expand All @@ -354,10 +349,6 @@ func NewInstance(t *testing.T, cfg InstanceConfig) *TeleInstance {
cfg.Listeners = StandardListenerSetup(t, &cfg.Fds)
}

if cfg.Log == nil {
cfg.Log = logrus.New()
}

if cfg.Logger == nil {
cfg.Logger = slog.New(logutils.DiscardHandler{})
}
Expand Down
File renamed without changes.
5 changes: 0 additions & 5 deletions lib/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ import (
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/quic-go/quic-go"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/crypto/acme"
Expand Down Expand Up @@ -992,10 +991,6 @@ func NewTeleport(cfg *servicecfg.Config) (*TeleportProcess, error) {
}

processID := fmt.Sprintf("%v", nextProcessID())
cfg.Log = utils.WrapLogger(cfg.Log.WithFields(logrus.Fields{
teleport.ComponentKey: teleport.Component(teleport.ComponentProcess, processID),
"pid": fmt.Sprintf("%v.%v", os.Getpid(), processID),
}))
cfg.Logger = cfg.Logger.With(
teleport.ComponentKey, teleport.Component(teleport.ComponentProcess, processID),
"pid", fmt.Sprintf("%v.%v", os.Getpid(), processID),
Expand Down
1 change: 0 additions & 1 deletion lib/service/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -948,7 +948,6 @@ func TestTeleportProcess_reconnectToAuth(t *testing.T) {
cfg.Testing.ConnectFailureC = make(chan time.Duration, 5)
cfg.Testing.ClientTimeout = time.Millisecond
cfg.InstanceMetadataClient = imds.NewDisabledIMDSClient()
cfg.Log = utils.NewLoggerForTests()
cfg.Logger = utils.NewSlogLoggerForTests()
process, err := NewTeleport(cfg)
require.NoError(t, err)
Expand Down
15 changes: 0 additions & 15 deletions lib/service/servicecfg/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import (
"github.com/ghodss/yaml"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"

"github.com/gravitational/teleport"
Expand All @@ -52,7 +51,6 @@ import (
"github.com/gravitational/teleport/lib/sshca"
usagereporter "github.com/gravitational/teleport/lib/usagereporter/teleport"
"github.com/gravitational/teleport/lib/utils"
logutils "github.com/gravitational/teleport/lib/utils/log"
)

// Config contains the configuration for all services that Teleport can run.
Expand Down Expand Up @@ -223,10 +221,6 @@ type Config struct {
// Kube is a Kubernetes API gateway using Teleport client identities.
Kube KubeConfig

// Log optionally specifies the logger.
// Deprecated: use Logger instead.
Log utils.Logger

// Logger outputs messages using slog. The underlying handler respects
// the user supplied logging config.
Logger *slog.Logger
Expand Down Expand Up @@ -518,10 +512,6 @@ func ApplyDefaults(cfg *Config) {

cfg.Version = defaults.TeleportConfigVersionV1

if cfg.Log == nil {
cfg.Log = utils.NewLogger()
}

if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
Expand Down Expand Up @@ -698,10 +688,6 @@ func applyDefaults(cfg *Config) {
cfg.Console = io.Discard
}

if cfg.Log == nil {
cfg.Log = logrus.StandardLogger()
}

if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
Expand Down Expand Up @@ -799,7 +785,6 @@ func verifyEnabledService(cfg *Config) error {
// If called after `config.ApplyFileConfig` or `config.Configure` it will also
// change the global loggers.
func (c *Config) SetLogLevel(level slog.Level) {
c.Log.SetLevel(logutils.SlogLevelToLogrusLevel(level))
c.LoggerLevel.Set(level)
}

Expand Down
23 changes: 6 additions & 17 deletions lib/service/servicecfg/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"testing"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"

"github.com/gravitational/teleport/api/types"
Expand Down Expand Up @@ -651,44 +650,34 @@ func TestWebPublicAddr(t *testing.T) {

func TestSetLogLevel(t *testing.T) {
for _, test := range []struct {
logLevel slog.Level
expectedLogrusLevel logrus.Level
logLevel slog.Level
}{
{
logLevel: logutils.TraceLevel,
expectedLogrusLevel: logrus.TraceLevel,
logLevel: logutils.TraceLevel,
},
{
logLevel: slog.LevelDebug,
expectedLogrusLevel: logrus.DebugLevel,
logLevel: slog.LevelDebug,
},
{
logLevel: slog.LevelInfo,
expectedLogrusLevel: logrus.InfoLevel,
logLevel: slog.LevelInfo,
},
{
logLevel: slog.LevelWarn,
expectedLogrusLevel: logrus.WarnLevel,
logLevel: slog.LevelWarn,
},
{
logLevel: slog.LevelError,
expectedLogrusLevel: logrus.ErrorLevel,
logLevel: slog.LevelError,
},
} {
t.Run(test.logLevel.String(), func(t *testing.T) {
// Create a configuration with local loggers to avoid modifying the
// global instances.
c := &Config{
Log: logrus.New(),
Logger: slog.New(logutils.NewSlogTextHandler(io.Discard, logutils.SlogTextHandlerConfig{})),
}
ApplyDefaults(c)

c.SetLogLevel(test.logLevel)
require.Equal(t, test.logLevel, c.LoggerLevel.Level())
require.IsType(t, &logrus.Logger{}, c.Log)
l, _ := c.Log.(*logrus.Logger)
require.Equal(t, test.expectedLogrusLevel, l.GetLevel())
})
}
}
Expand Down
122 changes: 10 additions & 112 deletions lib/utils/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"flag"
"fmt"
"io"
stdlog "log"
"log/slog"
"os"
"runtime"
Expand All @@ -38,7 +37,6 @@ import (

"github.com/alecthomas/kingpin/v2"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"golang.org/x/term"

"github.com/gravitational/teleport"
Expand Down Expand Up @@ -100,58 +98,34 @@ func InitLogger(purpose LoggingPurpose, level slog.Level, opts ...LoggerOption)
opt(&o)
}

logrus.StandardLogger().ReplaceHooks(make(logrus.LevelHooks))
logrus.SetLevel(logutils.SlogLevelToLogrusLevel(level))

var (
w io.Writer
enableColors bool
)
var enableColors bool
switch purpose {
case LoggingForCLI:
// If debug logging was asked for on the CLI, then write logs to stderr.
// Otherwise, discard all logs.
if level == slog.LevelDebug {
enableColors = IsTerminal(os.Stderr)
w = logutils.NewSharedWriter(os.Stderr)
} else {
w = io.Discard
enableColors = false
slog.SetDefault(slog.New(logutils.DiscardHandler{}))
return
}
case LoggingForDaemon:
enableColors = IsTerminal(os.Stderr)
w = logutils.NewSharedWriter(os.Stderr)
}

var (
formatter logrus.Formatter
handler slog.Handler
)
var handler slog.Handler
switch o.format {
case LogFormatText, "":
textFormatter := logutils.NewDefaultTextFormatter(enableColors)

// Calling CheckAndSetDefaults enables the timestamp field to
// be included in the output. The error returned is ignored
// because the default formatter cannot be invalid.
if purpose == LoggingForCLI && level == slog.LevelDebug {
_ = textFormatter.CheckAndSetDefaults()
}

formatter = textFormatter
handler = logutils.NewSlogTextHandler(w, logutils.SlogTextHandlerConfig{
handler = logutils.NewSlogTextHandler(os.Stderr, logutils.SlogTextHandlerConfig{
Level: level,
EnableColors: enableColors,
})
case LogFormatJSON:
formatter = &logutils.JSONFormatter{}
handler = logutils.NewSlogJSONHandler(w, logutils.SlogJSONHandlerConfig{
handler = logutils.NewSlogJSONHandler(os.Stderr, logutils.SlogJSONHandlerConfig{
Level: level,
})
}

logrus.SetFormatter(formatter)
logrus.SetOutput(w)
slog.SetDefault(slog.New(handler))
}

Expand All @@ -163,56 +137,21 @@ func InitLoggerForTests() {
// Parse flags to check testing.Verbose().
flag.Parse()

level := slog.LevelWarn
w := io.Discard
var handler slog.Handler = logutils.DiscardHandler{}
if testing.Verbose() {
level = slog.LevelDebug
w = os.Stderr
handler = logutils.NewSlogJSONHandler(os.Stderr, logutils.SlogJSONHandlerConfig{Level: slog.LevelDebug})
}

logger := logrus.StandardLogger()
logger.SetFormatter(logutils.NewTestJSONFormatter())
logger.SetLevel(logutils.SlogLevelToLogrusLevel(level))

output := logutils.NewSharedWriter(w)
logger.SetOutput(output)
slog.SetDefault(slog.New(logutils.NewSlogJSONHandler(output, logutils.SlogJSONHandlerConfig{Level: level})))
slog.SetDefault(slog.New(handler))
})
}

// NewLoggerForTests creates a new logrus logger for test environments.
func NewLoggerForTests() *logrus.Logger {
InitLoggerForTests()
return logrus.StandardLogger()
}

// NewSlogLoggerForTests creates a new slog logger for test environments.
func NewSlogLoggerForTests() *slog.Logger {
InitLoggerForTests()
return slog.Default()
}

// WrapLogger wraps an existing logger entry and returns
// a value satisfying the Logger interface
func WrapLogger(logger *logrus.Entry) Logger {
return &logWrapper{Entry: logger}
}

// NewLogger creates a new empty logrus logger.
func NewLogger() *logrus.Logger {
return logrus.StandardLogger()
}

// Logger describes a logger value
type Logger interface {
logrus.FieldLogger
// GetLevel specifies the level at which this logger
// value is logging
GetLevel() logrus.Level
// SetLevel sets the logger's level to the specified value
SetLevel(level logrus.Level)
}

// FatalError is for CLI front-ends: it detects gravitational/trace debugging
// information, sends it to the logger, strips it off and prints a clean message to stderr
func FatalError(err error) {
Expand All @@ -231,7 +170,7 @@ func GetIterations() int {
if err != nil {
panic(err)
}
logrus.Debugf("Starting tests with %v iterations.", iter)
slog.DebugContext(context.Background(), "Starting tests with iterations set in environment variable", "iterations", iter)
return iter
}

Expand Down Expand Up @@ -484,47 +423,6 @@ func AllowWhitespace(s string) string {
return sb.String()
}

// NewStdlogger creates a new stdlib logger that uses the specified leveled logger
// for output and the given component as a logging prefix.
func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger {
return stdlog.New(&stdlogAdapter{
log: logger,
}, component, stdlog.LstdFlags)
}

// Write writes the specified buffer p to the underlying leveled logger.
// Implements io.Writer
func (r *stdlogAdapter) Write(p []byte) (n int, err error) {
r.log(string(p))
return len(p), nil
}

// stdlogAdapter is an io.Writer that writes into an instance
// of logrus.Logger
type stdlogAdapter struct {
log LeveledOutputFunc
}

// LeveledOutputFunc describes a function that emits given
// arguments at a specific level to an underlying logger
type LeveledOutputFunc func(args ...interface{})

// GetLevel returns the level of the underlying logger
func (r *logWrapper) GetLevel() logrus.Level {
return r.Entry.Logger.GetLevel()
}

// SetLevel sets the logging level to the given value
func (r *logWrapper) SetLevel(level logrus.Level) {
r.Entry.Logger.SetLevel(level)
}

// logWrapper wraps a log entry.
// Implements Logger
type logWrapper struct {
*logrus.Entry
}

// needsQuoting returns true if any non-printable characters are found.
func needsQuoting(text string) bool {
for _, r := range text {
Expand Down
Loading

0 comments on commit 737af4b

Please sign in to comment.