Skip to content

Commit

Permalink
add log.pid to enable showing pid in log (#10722)
Browse files Browse the repository at this point in the history
* show pid in log

* add Pid to cli config
  • Loading branch information
zhiqiangxu authored Jun 4, 2024
1 parent c4226bf commit d87c88d
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion op-service/log/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const (
LevelFlagName = "log.level"
FormatFlagName = "log.format"
ColorFlagName = "log.color"
PidFlagName = "log.pid"
)

func CLIFlags(envPrefix string) []cli.Flag {
Expand Down Expand Up @@ -51,6 +52,12 @@ func CLIFlagsWithCategory(envPrefix string, category string) []cli.Flag {
EnvVars: opservice.PrefixEnvVar(envPrefix, "LOG_COLOR"),
Category: category,
},
&cli.BoolFlag{
Name: PidFlagName,
Usage: "Show pid in the log",
EnvVars: opservice.PrefixEnvVar(envPrefix, "LOG_PID"),
Category: category,
},
}
}

Expand Down Expand Up @@ -187,6 +194,7 @@ type CLIConfig struct {
Level slog.Level
Color bool
Format FormatType
Pid bool
}

// AppOut returns an io.Writer to write app output to, like logs.
Expand All @@ -208,7 +216,11 @@ func NewLogHandler(wr io.Writer, cfg CLIConfig) slog.Handler {
// The log handler of the logger is a LvlSetter, i.e. the log level can be changed as needed.
func NewLogger(wr io.Writer, cfg CLIConfig) log.Logger {
h := NewLogHandler(wr, cfg)
return log.NewLogger(h)
l := log.NewLogger(h)
if cfg.Pid {
l = l.With("pid", os.Getpid())
}
return l
}

// SetGlobalLogHandler sets the log handles as the handler of the global default logger.
Expand Down Expand Up @@ -237,5 +249,6 @@ func ReadCLIConfig(ctx *cli.Context) CLIConfig {
if ctx.IsSet(ColorFlagName) {
cfg.Color = ctx.Bool(ColorFlagName)
}
cfg.Pid = ctx.Bool(PidFlagName)
return cfg
}

0 comments on commit d87c88d

Please sign in to comment.