/
logs.go
84 lines (75 loc) 路 2.48 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
package api
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
cloudwatchlogsTypes "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
"github.com/aws/aws-sdk-go-v2/service/ecs/types"
)
// Equivalent to
// latest_log_stream=$(aws logs describe-log-streams \
// --log-group-name "$log_group" \
// --limit 1 \
// --order-by "LastEventTime" \
// --descending \
// --query "logStreams[0].logStreamName" \
// --output text)
// # Get the latest 10 log events from the log stream
//
// aws logs get-log-events \
// --log-group-name "$log_group" \
// --log-stream-name "$latest_log_stream" \
// --limit 10 \
// --query "events[*].[timestamp,message]" \
// --output table
func (store *Store) GetLogs(tdArn *string) ([]cloudwatchlogsTypes.OutputLogEvent, error) {
store.initCloudwatchlogsClient()
td, err := store.DescribeTaskDefinition(tdArn)
if err != nil {
logger.Warnf("Failed to run aws api to describe task definition, err: %v", err)
return nil, err
}
logs := []cloudwatchlogsTypes.OutputLogEvent{}
logGroupNames := make(map[string]bool)
for _, c := range td.ContainerDefinitions {
if c.LogConfiguration == nil {
continue
}
if c.LogConfiguration.LogDriver != types.LogDriverAwslogs {
continue
}
groupName := c.LogConfiguration.Options["awslogs-group"]
if groupName == "" {
continue
}
// avoid the same log group for different containers
if _, ok := logGroupNames[groupName]; ok {
continue
}
logGroupNames[groupName] = true
describeLogStreamsInput := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: &groupName,
Limit: aws.Int32(1),
OrderBy: cloudwatchlogsTypes.OrderByLastEventTime,
Descending: aws.Bool(true),
}
describeLogStreamsOutput, err := store.cloudwatchlogs.DescribeLogStreams(context.Background(), describeLogStreamsInput)
if err != nil {
logger.Warnf("Failed to run aws api to describe log stream, err: %v", err)
continue
}
streamName := describeLogStreamsOutput.LogStreams[0].LogStreamName
getLogEventsInput := &cloudwatchlogs.GetLogEventsInput{
LogGroupName: &groupName,
LogStreamName: streamName,
Limit: aws.Int32(100),
}
getLogEventsOutput, err := store.cloudwatchlogs.GetLogEvents(context.Background(), getLogEventsInput)
if err != nil {
logger.Warnf("Failed to run aws api to get log events, err: %v", err)
continue
}
logs = append(logs, getLogEventsOutput.Events...)
}
return logs, nil
}