forked from AliyunContainerService/pouch
/
logs.go
94 lines (76 loc) · 2.14 KB
/
logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"context"
"fmt"
"github.com/alibaba/pouch/apis/types"
"github.com/spf13/cobra"
)
var validDrivers = map[string]bool{
"json-file": true,
"journald": true,
}
// logsDescription is used to describe logs command in detail and auto generate command doc.
var logsDescription = ""
// LogsCommand use to implement 'logs' command, it is used to print a container's logs
type LogsCommand struct {
baseCommand
details bool
follow bool
since string
tail string
timestamps bool
}
// Init initialize logs command.
func (lc *LogsCommand) Init(c *Cli) {
lc.cli = c
lc.cmd = &cobra.Command{
Use: "logs [OPTIONS] CONTAINER",
Short: "Print a container's logs",
Long: logsDescription,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return lc.runLogs(args)
},
Example: logsExample(),
}
lc.addFlags()
}
// addFlags adds flags for specific command.
func (lc *LogsCommand) addFlags() {
flagSet := lc.cmd.Flags()
flagSet.BoolVarP(&lc.details, "details", "", false, "Show extra provided to logs")
flagSet.BoolVarP(&lc.follow, "follow", "f", false, "Follow log output")
flagSet.StringVarP(&lc.since, "since", "", "", "Show logs since timestamp")
flagSet.StringVarP(&lc.tail, "tail", "", "all", "Number of lines to show from the end of the logs default \"all\"")
flagSet.BoolVarP(&lc.timestamps, "timestamps", "t", false, "Show timestamps")
}
// runLogs is the entry of LogsCommand command.
func (lc *LogsCommand) runLogs(args []string) error {
// TODO
containerName := args[0]
ctx := context.Background()
apiClient := lc.cli.Client()
opts := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Since: lc.since,
Timestamps: lc.timestamps,
Follow: lc.follow,
Tail: lc.tail,
Details: lc.details,
}
resp, err := apiClient.ContainerLogs(ctx, containerName, opts)
if err != nil {
return err
}
defer resp.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp)
fmt.Printf(buf.String())
return nil
}
// logsExample shows examples in logs command, and is used in auto-generated cli docs.
func logsExample() string {
return ``
}