Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow users to set json log output #1026

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 (txt 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()
NoUseFreak marked this conversation as resolved.
Show resolved Hide resolved
stderr = log.Default()
}
}

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