-
Notifications
You must be signed in to change notification settings - Fork 202
/
logs.go
78 lines (68 loc) · 1.86 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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation and Dapr Contributors.
// Licensed under the MIT License.
// ------------------------------------------------------------
package kubernetes
import (
"context"
"fmt"
"io"
"os"
corev1 "k8s.io/api/core/v1"
)
const (
daprdContainerName = "daprd"
appIDContainerArgName = "--app-id"
)
// Logs fetches Dapr sidecar logs from Kubernetes.
func Logs(appID, podName, namespace string) error {
client, err := Client()
if err != nil {
return err
}
if namespace == "" {
namespace = corev1.NamespaceDefault
}
pods, err := ListPods(client, namespace, nil)
if err != nil {
return fmt.Errorf("could not get logs %v", err)
}
if podName == "" {
// no pod name specified. in case of multiple pods, the first one will be selected
var foundDaprPod bool
for _, pod := range pods.Items {
if foundDaprPod {
break
}
for _, container := range pod.Spec.Containers {
if container.Name == daprdContainerName {
// find app ID
for i, arg := range container.Args {
if arg == appIDContainerArgName {
id := container.Args[i+1]
if id == appID {
podName = pod.Name
foundDaprPod = true
break
}
}
}
}
}
}
if !foundDaprPod {
return fmt.Errorf("could not get logs. Please check app-id (%s) and namespace (%s)", appID, namespace)
}
}
getLogsRequest := client.CoreV1().Pods(namespace).GetLogs(podName, &corev1.PodLogOptions{Container: daprdContainerName, Follow: false})
logStream, err := getLogsRequest.Stream(context.TODO())
if err != nil {
return fmt.Errorf("could not get logs. Please check pod-name (%s). Error - %v", podName, err)
}
defer logStream.Close()
_, err = io.Copy(os.Stdout, logStream)
if err != nil {
return fmt.Errorf("could not get logs %v", err)
}
return nil
}