-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patholdLogStreams.mjs
More file actions
79 lines (71 loc) · 2.29 KB
/
oldLogStreams.mjs
File metadata and controls
79 lines (71 loc) · 2.29 KB
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
import {
CloudWatchLogsClient,
DescribeLogGroupsCommand,
DescribeLogStreamsCommand,
DeleteLogStreamCommand,
} from "@aws-sdk/client-cloudwatch-logs";
import { fromSSO } from "@aws-sdk/credential-providers";
import { subDays, isBefore } from "date-fns";
const awsRegion = "us-west-2";
const client = new CloudWatchLogsClient({
region: awsRegion,
credentials: fromSSO({ profile: "platform-stage" }),
});
try {
// Get all log groups
let nextTokenGroup;
let logGroups = [];
do {
const { logGroups: currentLogGroups, nextToken } = await client.send(
new DescribeLogGroupsCommand({ nextToken: nextTokenGroup }),
);
logGroups = logGroups.concat(currentLogGroups);
nextTokenGroup = nextToken;
} while (nextTokenGroup);
for (const logGroup of logGroups) {
const logGroupName = logGroup.logGroupName;
// Get log streams for each log group
let nextTokenStream;
let logStreams = [];
do {
const { logStreams: currentLogStreams, nextToken } = await client.send(
new DescribeLogStreamsCommand({
logGroupName,
nextToken: nextTokenStream,
}),
);
logStreams = logStreams.concat(currentLogStreams);
nextTokenStream = nextToken;
} while (nextTokenStream);
for (const logStream of logStreams) {
// Check if the log stream is empty (no events, or last event timestamp is very old)
// You might define "empty" based on your specific criteria,
// e.g., lastEventTimestamp is undefined or significantly old.
const isEmpty = !logStream.lastEventTimestamp;
const isVeryOld =
logStream.lastEventTimestamp &&
isBefore(
new Date(logStream.lastEventTimestamp),
subDays(new Date(), 16),
);
if (isEmpty || isVeryOld) {
console.log(
`Deleting empty log stream: ${logStream.logStreamName} in log group: ${logGroupName}`,
);
await client.send(
new DeleteLogStreamCommand({
logGroupName,
logStreamName: logStream.logStreamName,
}),
);
}
}
}
console.log("CloudWatch log stream cleanup complete.");
process.exitCode = 0;
process.exit();
} catch (error) {
console.error("Error during log stream cleanup:", error);
process.exitCode = 1;
process.exit();
}