Skip to content

Commit a33c19b

Browse files
Add deployment logs command to fetch pod logs
1 parent 9694015 commit a33c19b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

pkg/deploy/logs.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package deploy
2+
3+
import (
4+
"fmt"
5+
"os/exec"
6+
"strings"
7+
)
8+
9+
func Logs(envName string, follow bool) error {
10+
11+
environment, err := LoadEnvironment(envName)
12+
if err != nil {
13+
return err
14+
}
15+
16+
ns := environment.K8s.Namespace
17+
ctx := environment.K8s.Context
18+
19+
// Get pods
20+
args := []string{
21+
"get",
22+
"pods",
23+
"-n",
24+
ns,
25+
"-o",
26+
"name",
27+
}
28+
29+
if ctx != "" {
30+
args = append(args, "--context", ctx)
31+
}
32+
33+
cmd := exec.Command("kubectl", args...)
34+
out, err := cmd.Output()
35+
if err != nil {
36+
return fmt.Errorf("failed to fetch pods")
37+
}
38+
39+
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
40+
if len(lines) == 0 || lines[0] == "" {
41+
return fmt.Errorf("no pods found")
42+
}
43+
44+
// Take first pod
45+
pod := lines[0]
46+
47+
fmt.Println("Fetching logs for:", pod)
48+
fmt.Println()
49+
50+
logArgs := []string{
51+
"logs",
52+
pod,
53+
"-n",
54+
ns,
55+
}
56+
57+
if follow {
58+
logArgs = append(logArgs, "-f")
59+
}
60+
61+
if ctx != "" {
62+
logArgs = append(logArgs, "--context", ctx)
63+
}
64+
65+
logCmd := exec.Command("kubectl", logArgs...)
66+
logCmd.Stdout = nil
67+
logCmd.Stderr = nil
68+
69+
return logCmd.Run()
70+
}

0 commit comments

Comments
 (0)