Skip to content

Commit

Permalink
Fallback when no logger is defined, fix default level (#255)
Browse files Browse the repository at this point in the history
Fixes #254
  • Loading branch information
sethvargo committed Nov 29, 2023
1 parent 35ec86f commit 22a0cfe
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ func main() {

rootCmd.PersistentFlags().StringVarP(&logFormat, "log-format", "f", "text",
"Format in which to log")
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "fatal",
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "warning",
"Level at which to log")
rootCmd.PersistentFlags().BoolVar(&logDebug, "log-debug", false,
"Enable verbose source debug logging")
Expand Down
2 changes: 1 addition & 1 deletion pkg/berglas/logging/levels.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func LookupLevel(name string) (slog.Level, error) {
return LevelNotice, nil
case levelWarningName, "WARN": // "WARN" maintains compat with old logger
return LevelWarning, nil
case levelErrorName, "ERR": // "ERR" maintains compat with old logger
case levelErrorName, "ERR", "FATAL": // "ERR" and "FATAL" maintains compat with old logger
return LevelError, nil
case levelEmergencyName:
return LevelEmergency, nil
Expand Down
13 changes: 12 additions & 1 deletion pkg/berglas/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import (
"io"
"log/slog"
"math"
"os"
"strings"
"sync"
"time"
)

Expand All @@ -35,6 +37,14 @@ type contextKey string
// loggerKey points to the value in the context where the logger is stored.
const loggerKey = contextKey("logger")

var defaultLoggerOnce = sync.OnceValue(func() *slog.Logger {
l, err := New(os.Stderr, "warning", "json", false)
if err != nil {
panic(fmt.Errorf("failed to create logger: %w", err))
}
return l
})

// New creates a new logger in the specified format and writes to the provided
// writer at the provided level. Use the returned leveler to dynamically change
// the level to a different value after creation.
Expand Down Expand Up @@ -107,7 +117,8 @@ func FromContext(ctx context.Context) *slog.Logger {
if logger, ok := ctx.Value(loggerKey).(*slog.Logger); ok {
return logger
}
panic("no logger in context")

return defaultLoggerOnce()
}

// cloudLoggingAttrsEncoder updates the [slog.Record] attributes to match the
Expand Down

0 comments on commit 22a0cfe

Please sign in to comment.