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 <anonymousknight96@gmail.com>
  • Loading branch information
knight42 committed Dec 14, 2024
1 parent 67afd48 commit efe2ec7
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 errors.New("--tail and --stream are mutually exclusive")
}

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 efe2ec7

Please sign in to comment.