Skip to content

Commit

Permalink
chore: true up logger comments and minor refactors (#3215)
Browse files Browse the repository at this point in the history
Signed-off-by: Kit Patella <kit@defenseunicorns.com>
  • Loading branch information
mkcp authored Nov 8, 2024
1 parent 9bee4b1 commit 4a88d52
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,6 @@ func ConfigDefault() Config {

// New takes a Config and returns a validated logger.
func New(cfg Config) (*slog.Logger, error) {
var handler slog.Handler
opts := slog.HandlerOptions{}

// Use default destination if none
if cfg.Destination == nil {
cfg.Destination = DestinationDefault
Expand All @@ -167,8 +164,12 @@ func New(cfg Config) (*slog.Logger, error) {
if !validLevels[cfg.Level] {
return nil, fmt.Errorf("unsupported log level: %d", cfg.Level)
}
opts.Level = slog.Level(cfg.Level)

opts := slog.HandlerOptions{
Level: slog.Level(cfg.Level),
}

var handler slog.Handler
switch cfg.Format.ToLower() {
case FormatText:
handler = console.NewHandler(cfg.Destination, &console.HandlerOptions{
Expand All @@ -195,14 +196,13 @@ func New(cfg Config) (*slog.Logger, error) {
return nil, fmt.Errorf("unsupported log format: %s", cfg.Format)
}

log := slog.New(handler)
return log, nil
return slog.New(handler), nil
}

// ctxKey provides a location to store a logger in a context.
type ctxKey struct{}

// defaultCtxKey provides a default key if one is not passed into From.
// defaultCtxKey provides a key instance to get a logger from context
var defaultCtxKey = ctxKey{}

// WithContext takes a context.Context and a *slog.Logger, storing it on the key
Expand Down Expand Up @@ -239,12 +239,12 @@ func Enabled(ctx context.Context) bool {
func From(ctx context.Context) *slog.Logger {
// Check that we have a ctx
if ctx == nil {
return newEmpty()
return newDiscard()
}
// Grab value from key
log := ctx.Value(defaultCtxKey)
if log == nil {
return newEmpty()
return newDiscard()
}

// Ensure our value is a *slog.Logger before we cast.
Expand All @@ -258,7 +258,7 @@ func From(ctx context.Context) *slog.Logger {
}

// newDiscard returns a logger without any settings that goes to io.Discard
func newEmpty() *slog.Logger {
func newDiscard() *slog.Logger {
h := slog.NewTextHandler(DestinationNone, &slog.HandlerOptions{})
return slog.New(h)
}
Expand Down

0 comments on commit 4a88d52

Please sign in to comment.