Skip to content

Commit

Permalink
cli: Add option to use JSON format for logging
Browse files Browse the repository at this point in the history
Squashed commit of the following:

commit bab0f8e0c12326265612f8067f16151adf47b0a2
Author: Marius Kleidl <[email protected]>
Date:   Tue Dec 5 12:07:25 2023 +0100

    Correct flag description

commit 56576ca
Author: Dries De Peuter <[email protected]>
Date:   Sat Nov 4 11:18:27 2023 +0100

    feat: Allow users to set json log output
  • Loading branch information
Acconut committed Dec 5, 2023
1 parent 8045335 commit 9b6ada9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
2 changes: 2 additions & 0 deletions cmd/tusd/cli/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ var Flags struct {
PprofMutexProfileRate int
BehindProxy bool
VerboseOutput bool
LogFormat string
S3TransferAcceleration bool
TLSCertFile string
TLSKeyFile string
Expand Down Expand Up @@ -178,6 +179,7 @@ func ParseFlags() {
f.BoolVar(&Flags.ShowGreeting, "show-greeting", true, "Show the greeting message")
f.BoolVar(&Flags.ShowVersion, "version", false, "Print tusd version information")
f.BoolVar(&Flags.VerboseOutput, "verbose", true, "Enable verbose logging output")
f.StringVar(&Flags.LogFormat, "log-format", "text", "Logging format (text or json)")
})

fs.AddGroup("Timeout options", func(f *flag.FlagSet) {
Expand Down
46 changes: 31 additions & 15 deletions cmd/tusd/cli/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,38 @@ func SetupStructuredLogger() {
level = slog.LevelDebug
}

slogger := slog.New(
slog.NewTextHandler(logWriter{stdout}, &slog.HandlerOptions{
replaceAttrFunc := func(groups []string, a slog.Attr) slog.Attr {
// Remove time attribute, because that is handled by the logger
if a.Key == slog.TimeKey {
return slog.Attr{}
}
// Rename `msg` to `event`
if a.Key == slog.MessageKey {
a.Key = "event"
}
return a
}

var handler slog.Handler
switch Flags.LogFormat {
case "json":
handler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Remove time attribute, because that is handled by the logger
if a.Key == slog.TimeKey {
return slog.Attr{}
}
// Rename `msg` to `event`
if a.Key == slog.MessageKey {
a.Key = "event"
}
return a
},
}))
slog.SetDefault(slogger)
})
default:
handler = slog.NewTextHandler(logWriter{log.New(os.Stdout, "", log.LstdFlags|log.Lmicroseconds)}, &slog.HandlerOptions{
Level: level,
ReplaceAttr: replaceAttrFunc,
})
}

slog.SetDefault(slog.New(handler))

if Flags.LogFormat == "json" {
// stdout and stderr helpers need to be overwritten to use slog
stdout = log.Default()
stderr = log.Default()
}
}

// logWriter is an io.Writer that forwards all input to the given log.Logger,
Expand Down

0 comments on commit 9b6ada9

Please sign in to comment.