Skip to content

Commit

Permalink
feat: retrieve specific log stream of a container
Browse files Browse the repository at this point in the history
Signed-off-by: Jian Zeng <[email protected]>
  • Loading branch information
knight42 committed Dec 14, 2024
1 parent 67afd48 commit 6f2b8be
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion cmd/crictl/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
Expand All @@ -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",
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 fmt.Errorf("--tail and --stream are mutually exclusive")

Check failure on line 129 in cmd/crictl/logs.go

View workflow job for this annotation

GitHub Actions / verify / lint

fmt.Errorf can be replaced with errors.New (perfsprint)
}

logOptions := logs.NewLogOptions(&v1.PodLogOptions{
Follow: c.Bool("follow"),
TailLines: &tailLines,
Expand Down Expand Up @@ -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)
},
}

Expand Down

0 comments on commit 6f2b8be

Please sign in to comment.