-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlocalstack-logs-analysis.ts
More file actions
365 lines (305 loc) · 11.7 KB
/
localstack-logs-analysis.ts
File metadata and controls
365 lines (305 loc) · 11.7 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import { z } from "zod";
import { type ToolMetadata, type InferSchema } from "xmcp";
import { ensureLocalStackCli } from "../lib/localstack/localstack.utils";
import { LocalStackLogRetriever, type LogEntry } from "../lib/logs/log-retriever";
import { runPreflights, requireLocalStackCli } from "../core/preflight";
import { ResponseBuilder } from "../core/response-builder";
export const schema = {
analysisType: z
.enum(["summary", "errors", "requests", "logs"])
.default("summary")
.describe(
"The analysis to perform: 'summary' (default), 'errors', 'requests', or 'logs' for raw output."
),
lines: z
.number()
.int()
.positive()
.default(2000)
.describe("Number of recent log lines to fetch and analyze."),
service: z
.string()
.optional()
.describe(
"Filter by AWS service (e.g., 's3', 'lambda'). Used with 'errors' and 'requests' modes."
),
operation: z
.string()
.optional()
.describe(
"Filter by a specific API operation (e.g., 'CreateBucket'). Requires 'service'. Used with 'requests' mode."
),
filter: z.string().optional().describe("Raw keyword filter. Only used with 'logs' mode."),
};
export const metadata: ToolMetadata = {
name: "localstack-logs-analysis",
description:
"LocalStack log analyzer that helps developers quickly diagnose issues and understand their LocalStack interactions",
annotations: {
title: "LocalStack Logs Analysis",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
},
};
export default async function localstackLogsAnalysis({
analysisType,
lines,
service,
operation,
filter,
}: InferSchema<typeof schema>) {
const preflightError = await runPreflights([requireLocalStackCli()]);
if (preflightError) return preflightError;
const retriever = new LocalStackLogRetriever();
const retrievalFilter = analysisType === "logs" ? filter : undefined;
const logResult = await retriever.retrieveLogs(lines, retrievalFilter);
if (!logResult.success) {
return ResponseBuilder.error("Log Retrieval Failed", logResult.errorMessage || "Unknown error");
}
switch (analysisType) {
case "summary":
return await handleSummaryAnalysis(logResult.logs, logResult.totalLines);
case "errors":
return await handleErrorAnalysis(retriever, logResult.logs, service);
case "requests":
return await handleRequestAnalysis(retriever, logResult.logs, service, operation);
case "logs":
return await handleRawLogsAnalysis(
logResult.logs,
logResult.totalLines,
logResult.filteredLines,
filter
);
default:
return ResponseBuilder.error(
"Unknown analysis type",
`❌ Unknown analysis type: ${analysisType}`
);
}
}
/**
* Handle summary analysis mode - high-level dashboard
*/
async function handleSummaryAnalysis(logs: LogEntry[], totalLines: number) {
const errors = logs.filter((log) => log.isError);
const warnings = logs.filter((log) => log.isWarning);
const apiStats = new LocalStackLogRetriever().analyzeApiCalls(logs);
let result = `# 📊 LocalStack Summary\n\n`;
result += `**Lines Analyzed:** ${totalLines}\n`;
result += `**API Calls:** ${apiStats.totalCalls}\n`;
result += `**Errors:** ${errors.length} | **Warnings:** ${warnings.length}\n\n`;
// Quick health check
if (apiStats.failedCalls > 0) {
result += `## ❌ Recent Failures (${apiStats.failedCalls})\n\n`;
const recentFailures = apiStats.failedCallDetails.slice(-5).reverse();
for (const call of recentFailures) {
const service = call.service || "unknown";
const operation = call.operation || "unknown";
const status = call.statusCode || "N/A";
result += `- **${service}.${operation}** → ${status} ${call.message}\n`;
}
result += `\n💡 Use \`errors\` mode for detailed analysis\n\n`;
}
// Service breakdown if there are API calls
if (apiStats.callsByService.size > 0) {
result += `## 🔧 Service Activity\n\n`;
for (const [svc, count] of Array.from(apiStats.callsByService.entries()).sort(
(a, b) => b[1] - a[1]
)) {
const serviceErrors = apiStats.failedCallDetails.filter(
(call) => call.service === svc
).length;
const status = serviceErrors === 0 ? "✅" : "❌";
result += `- **${svc}**: ${count} calls ${status}`;
if (serviceErrors > 0) result += ` (${serviceErrors} failed)`;
result += `\n`;
}
result += `\n`;
}
if (errors.length === 0 && apiStats.failedCalls === 0) {
result += `## ✅ All Clear\n\nNo errors detected in recent LocalStack activity.\n\n`;
}
result += `**Drill down:** \`errors\` | \`requests\` | \`logs\`\n`;
return ResponseBuilder.markdown(result);
}
/**
* Handle error analysis mode - detailed error examination
*/
async function handleErrorAnalysis(
retriever: LocalStackLogRetriever,
logs: LogEntry[],
serviceFilter?: string
) {
let errorLogs = logs.filter((log) => log.isError || log.isWarning);
// Apply service filter if provided
if (serviceFilter) {
errorLogs = errorLogs.filter(
(log) => log.service?.toLowerCase() === serviceFilter.toLowerCase()
);
}
if (errorLogs.length === 0) {
const filterMsg = serviceFilter ? ` for ${serviceFilter}` : "";
return ResponseBuilder.markdown(`✅ No errors found${filterMsg} in the analyzed logs.`);
}
const errorGroups = retriever.groupLogsByError(errorLogs);
const serviceMsg = serviceFilter ? ` (${serviceFilter})` : "";
let result = `# 🚨 LocalStack Errors${serviceMsg}\n\n`;
result += `**Found:** ${errorLogs.length} issues (${errorGroups.size} unique types)\n\n`;
// Sort error groups by frequency (most common first)
const sortedErrorGroups = Array.from(errorGroups.entries()).sort(
(a, b) => b[1].length - a[1].length
);
for (const [errorPattern, instances] of sortedErrorGroups) {
const count = instances.length;
const firstInstance = instances[0];
const isApiError = firstInstance.isApiCall && firstInstance.statusCode;
result += `## ${isApiError ? "🔴" : "⚠️"} ${errorPattern}\n`;
result += `**Occurrences:** ${count}\n\n`;
// Show recent examples
const recentInstances = instances.slice(-2);
for (const instance of recentInstances) {
if (instance.timestamp) result += `**${instance.timestamp}**\n`;
result += `\`\`\`\n${instance.fullLine}\n\`\`\`\n\n`;
}
if (count > 2) {
result += `*... and ${count - 2} more occurrences*\n\n`;
}
}
// Quick suggestions
const hasApiErrors = errorLogs.some((log) => log.isApiCall);
if (hasApiErrors) {
result += `💡 **Next:** Use \`requests\` mode to analyze API call patterns\n`;
}
return ResponseBuilder.markdown(result);
}
/**
* Handle request analysis mode - API call examination
*/
async function handleRequestAnalysis(
retriever: LocalStackLogRetriever,
logs: LogEntry[],
serviceFilter?: string,
operationFilter?: string
) {
const apiStats = retriever.analyzeApiCalls(logs);
if (apiStats.totalCalls === 0) {
return ResponseBuilder.markdown(`🔍 No API calls detected in the analyzed logs.`);
}
// Case 1: Both service and operation specified - show detailed call traces
if (serviceFilter && operationFilter) {
const matchingCalls = logs.filter(
(log) =>
log.isApiCall &&
log.service?.toLowerCase() === serviceFilter.toLowerCase() &&
log.operation?.toLowerCase() === operationFilter.toLowerCase()
);
if (matchingCalls.length === 0) {
return ResponseBuilder.markdown(`🔍 No calls found for ${serviceFilter}.${operationFilter}`);
}
let result = `# 🔍 ${serviceFilter}.${operationFilter} Calls\n\n`;
result += `**Total:** ${matchingCalls.length}\n\n`;
for (let i = 0; i < Math.min(matchingCalls.length, 10); i++) {
const call = matchingCalls[i];
const status = call.statusCode ? `${call.statusCode}` : "N/A";
const statusEmoji = call.statusCode && call.statusCode >= 400 ? "❌" : "✅";
result += `### ${statusEmoji} Call ${i + 1}\n`;
if (call.timestamp) result += `**${call.timestamp}**\n`;
result += `**Status:** ${status}\n`;
result += `\`\`\`\n${call.fullLine}\n\`\`\`\n\n`;
}
if (matchingCalls.length > 10) {
result += `*... and ${matchingCalls.length - 10} more calls*\n`;
}
return ResponseBuilder.markdown(result);
}
// Case 2: Only service specified - show operations for that service
if (serviceFilter) {
const serviceCalls = logs.filter(
(log) => log.isApiCall && log.service?.toLowerCase() === serviceFilter.toLowerCase()
);
if (serviceCalls.length === 0) {
return ResponseBuilder.markdown(`🔍 No ${serviceFilter} API calls found.`);
}
const operationStats = new Map<string, { total: number; failed: number }>();
for (const call of serviceCalls) {
const op = call.operation || "Unknown";
if (!operationStats.has(op)) {
operationStats.set(op, { total: 0, failed: 0 });
}
const stats = operationStats.get(op)!;
stats.total++;
if (call.statusCode && call.statusCode >= 400) {
stats.failed++;
}
}
let result = `# 🔧 ${serviceFilter.toUpperCase()} API Calls\n\n`;
result += `**Total:** ${serviceCalls.length}\n\n`;
const sortedOps = Array.from(operationStats.entries()).sort((a, b) => b[1].total - a[1].total);
for (const [operation, stats] of sortedOps) {
const status = stats.failed === 0 ? "✅" : "❌";
result += `- **${operation}** ${status} (${stats.total} calls`;
if (stats.failed > 0) result += `, ${stats.failed} failed`;
result += `)\n`;
}
result += `\n💡 Add \`operation\` parameter to see detailed traces\n`;
return ResponseBuilder.markdown(result);
}
// Case 3: No filters - show service overview
let result = `# 🌐 API Activity\n\n`;
result += `**Total:** ${apiStats.totalCalls} calls\n`;
result += `**Failed:** ${apiStats.failedCalls}\n`;
result += `**Success Rate:** ${((apiStats.successfulCalls / apiStats.totalCalls) * 100).toFixed(1)}%\n\n`;
if (apiStats.callsByService.size > 0) {
result += `## Services\n\n`;
const sortedServices = Array.from(apiStats.callsByService.entries()).sort(
(a, b) => b[1] - a[1]
);
for (const [service, totalCalls] of sortedServices) {
const failedCalls = apiStats.failedCallDetails.filter(
(call) => call.service === service
).length;
const status = failedCalls === 0 ? "✅" : "❌";
result += `- **${service}** ${status} (${totalCalls} calls`;
if (failedCalls > 0) result += `, ${failedCalls} failed`;
result += `)\n`;
}
result += `\n💡 Add \`service\` parameter to focus on specific service\n`;
}
return ResponseBuilder.markdown(result);
}
/**
* Handle raw logs analysis mode - direct log inspection
*/
async function handleRawLogsAnalysis(
logs: LogEntry[],
totalLines: number,
filteredLines?: number,
filter?: string
) {
const displayLines = filteredLines || logs.length;
let result = `# 📜 Raw Logs\n\n`;
if (filter) {
result += `**Filter:** "${filter}" → ${displayLines}/${totalLines} lines\n\n`;
} else {
result += `**Lines:** ${displayLines}\n\n`;
}
if (logs.length === 0) {
result += `No matching logs found.\n`;
return ResponseBuilder.markdown(result);
}
result += `\`\`\`\n`;
for (const log of logs) {
result += `${log.fullLine}\n`;
}
result += `\`\`\`\n\n`;
// Quick stats
const errors = logs.filter((log) => log.isError).length;
const apiCalls = logs.filter((log) => log.isApiCall).length;
if (errors > 0 || apiCalls > 0) {
result += `**Quick stats:** ${errors} errors, ${apiCalls} API calls\n`;
}
return {
content: [{ type: "text", text: result }],
};
}