diff --git a/cmd/flags.go b/cmd/flags.go index 019b2a3ea800..7a5c8d6876f0 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -47,6 +47,10 @@ func globalFlags() []cli.Flag { Usage: "set log level (trace, debug, info, warn, error, fatal, panic)", Hidden: true, }, + &cli.StringFlag{ + Name: "log-id", + Usage: "append the given log id in log, use \"random\" to use random uuid", + }, &cli.BoolFlag{ Name: "no-agent", Usage: "disable pprof (:6060) agent", diff --git a/cmd/main.go b/cmd/main.go index eb3f9bbee0d4..19deba0c3319 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -27,6 +27,7 @@ import ( "syscall" "github.com/erikdubbelboer/gspt" + "github.com/google/uuid" "github.com/juicedata/juicefs/pkg/utils" "github.com/juicedata/juicefs/pkg/version" "github.com/pyroscope-io/client/pyroscope" @@ -197,6 +198,9 @@ func reorderOptions(app *cli.App, args []string) []string { newArgs = append(newArgs, option) if hasValue { i++ + if i >= len(args) { + logger.Fatalf("option %s requires value", option) + } newArgs = append(newArgs, args[i]) } } else { @@ -283,6 +287,14 @@ func setup(c *cli.Context, n int) { undo() } + logID := c.String("log-id") + if logID != "" { + if logID == "random" { + logID = uuid.New().String() + } + utils.SetLogID(logID + " ") + } + if !c.Bool("no-agent") { go debugAgentOnce.Do(func() { for port := 6060; port < 6100; port++ { diff --git a/pkg/utils/logger.go b/pkg/utils/logger.go index 838683e3ec92..7a0f7f521829 100644 --- a/pkg/utils/logger.go +++ b/pkg/utils/logger.go @@ -34,6 +34,7 @@ type logHandle struct { logrus.Logger name string + logid string lvl *logrus.Level colorful bool } @@ -60,8 +61,9 @@ func (l *logHandle) Format(e *logrus.Entry) ([]byte, error) { } const timeFormat = "2006/01/02 15:04:05.000000" timestamp := e.Time.Format(timeFormat) - str := fmt.Sprintf("%v %s[%d] <%v>: %v [%s:%d]", + str := fmt.Sprintf("%v %s%s[%d] <%v>: %v [%s:%d]", timestamp, + l.logid, l.name, os.Getpid(), lvlStr, @@ -143,3 +145,11 @@ func SetOutput(w io.Writer) { logger.SetOutput(w) } } + +func SetLogID(id string) { + mu.Lock() + defer mu.Unlock() + for _, logger := range loggers { + logger.logid = id + } +} diff --git a/pkg/utils/logger_test.go b/pkg/utils/logger_test.go index d5abc736620f..87439a6a2a42 100644 --- a/pkg/utils/logger_test.go +++ b/pkg/utils/logger_test.go @@ -34,6 +34,7 @@ func TestLogger(t *testing.T) { SetOutFile("") // invalid SetOutFile(f.Name()) InitLoggers(true) + SetLogID("testid") SetLogLevel(logrus.TraceLevel) SetLogLevel(logrus.DebugLevel) @@ -53,5 +54,7 @@ func TestLogger(t *testing.T) { t.Fatalf("info/debug should not be logged: %s", s) } else if !strings.Contains(s, "warn level") || !strings.Contains(s, "error level") { t.Fatalf("warn/error should be logged: %s", s) + } else if !strings.Contains(s, "testid") { + t.Fatalf("logid \"testid\" should be logged: %s", s) } }