From efe2ec793a784be9b048bac40d06e63227ec83ad Mon Sep 17 00:00:00 2001 From: Jian Zeng Date: Fri, 13 Dec 2024 12:47:40 +0800 Subject: [PATCH] feat: retrieve specific log stream of a container Signed-off-by: Jian Zeng --- cmd/crictl/logs.go | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/cmd/crictl/logs.go b/cmd/crictl/logs.go index 5b296bcaa8..bda4065815 100644 --- a/cmd/crictl/logs.go +++ b/cmd/crictl/logs.go @@ -20,6 +20,7 @@ import ( "context" "errors" "fmt" + "io" "os" "strconv" "strings" @@ -35,6 +36,11 @@ import ( "k8s.io/klog/v2" ) +const ( + streamStdout = "stdout" + streamStderr = "stderr" +) + var logsCommand = &cli.Command{ Name: "logs", Usage: "Fetch the logs of a container", @@ -75,6 +81,10 @@ var logsCommand = &cli.Command{ Aliases: []string{"t"}, Usage: "Show timestamps", }, + &cli.StringFlag{ + Name: "stream", + Usage: "Show specified stream (stdout or stderr). Defaults to both.", + }, }, Action: func(c *cli.Context) (retErr error) { containerID := c.Args().First() @@ -108,6 +118,17 @@ var logsCommand = &cli.Command{ } timestamp := c.Bool("timestamps") previous := c.Bool("previous") + stream := c.String("stream") + + switch stream { + case streamStdout, streamStderr, "": + default: + return fmt.Errorf(`invalid stream %q, must be "stdout" or "stderr"`, stream) + } + if c.IsSet("tail") && c.IsSet("stream") { + return errors.New("--tail and --stream are mutually exclusive") + } + logOptions := logs.NewLogOptions(&v1.PodLogOptions{ Follow: c.Bool("follow"), TailLines: &tailLines, @@ -153,7 +174,19 @@ var logsCommand = &cli.Command{ cancelFn() }() logger := klog.Background() - return logs.ReadLogs(readLogCtx, &logger, logPath, status.GetStatus().GetId(), logOptions, runtimeService, os.Stdout, os.Stderr) + + var ( + stdoutStream io.Writer = os.Stdout + stderrStream io.Writer = os.Stderr + ) + switch stream { + case streamStdout: + stderrStream = nil + case streamStderr: + stdoutStream = nil + } + + return logs.ReadLogs(readLogCtx, &logger, logPath, status.GetStatus().GetId(), logOptions, runtimeService, stdoutStream, stderrStream) }, }