-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathLogsSection.tsx
More file actions
270 lines (238 loc) · 8.35 KB
/
LogsSection.tsx
File metadata and controls
270 lines (238 loc) · 8.35 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
import { observer } from "mobx-react";
import { useState, useEffect, useRef } from "react";
import {
LogsResponseSchema,
type LogEntry,
type LogsResponse,
} from "../types/eval-protocol";
import { getApiUrl } from "../config";
import Select from "./Select";
import Button from "./Button";
const haveLogsChanged = (prevLogs: LogEntry[], nextLogs: LogEntry[]) => {
return prevLogs.length !== nextLogs.length;
};
interface LogsSectionProps {
rolloutId?: string;
}
export const LogsSection = observer(({ rolloutId }: LogsSectionProps) => {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedLevel, setSelectedLevel] = useState<string>("");
const scrollContainerRef = useRef<HTMLDivElement | null>(null);
const isAtBottomRef = useRef(true);
const shouldAutoScrollRef = useRef(false);
const fetchLogs = async (isInitialLoad = false) => {
if (!rolloutId) return;
// Only show loading on initial load, not during polling
if (isInitialLoad) {
setLoading(true);
}
setError(null);
try {
const apiUrl = getApiUrl();
console.log("API URL:", apiUrl);
const params = new URLSearchParams();
if (selectedLevel) {
params.append("level", selectedLevel);
}
// max is 10,000 so I set it to 10,000: https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search#operation-search-size
params.append("limit", "10000");
const fullUrl = `${apiUrl}/api/logs/${rolloutId}?${params}`;
console.log("Attempting to fetch logs from:", fullUrl);
let response;
try {
response = await fetch(fullUrl);
console.log("Fetch completed, response:", response);
} catch (fetchError) {
console.error("Fetch failed with network error:", fetchError);
setError(
`Network error: ${
fetchError instanceof Error ? fetchError.message : "Unknown error"
}`
);
return;
}
if (!response.ok) {
if (response.status === 503) {
setError("Elasticsearch is not configured");
return;
}
if (response.status === 404) {
// Check if we got HTML (server not running) vs JSON (no logs found)
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("text/html")) {
setError(
"Logs server not running. Start the logs server to view logs."
);
return;
} else {
// 404 with JSON content-type means "no logs found" - this is valid
setLogs([]);
return;
}
}
// Check if we got HTML instead of JSON (likely a routing issue)
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("text/html")) {
setError(
`API endpoint not found. Got HTML response instead of JSON. Status: ${response.status}`
);
return;
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data: LogsResponse = LogsResponseSchema.parse(
await response.json()
);
setLogs((prevLogs) => {
const hasChanges = haveLogsChanged(prevLogs, data.logs);
if (!hasChanges) {
return prevLogs;
}
if (isAtBottomRef.current) {
shouldAutoScrollRef.current = true;
}
return data.logs;
});
} catch (err) {
if (err instanceof Error && err.message.includes("Unexpected token")) {
setError(
"API returned HTML instead of JSON. Is the logs server running on the correct port?"
);
} else {
setError(err instanceof Error ? err.message : "Failed to fetch logs");
}
} finally {
setLoading(false);
}
};
useEffect(() => {
if (rolloutId) {
fetchLogs(true); // Initial load
const interval = setInterval(() => fetchLogs(false), 5000); // Poll every 5 seconds without loading state
return () => clearInterval(interval);
}
}, [rolloutId, selectedLevel]);
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) {
isAtBottomRef.current = true;
return;
}
const handleScroll = () => {
const distanceFromBottom =
el.scrollHeight - el.scrollTop - el.clientHeight;
isAtBottomRef.current = distanceFromBottom <= 8;
};
el.addEventListener("scroll", handleScroll);
handleScroll();
return () => {
el.removeEventListener("scroll", handleScroll);
};
}, [logs.length]);
// Auto-scroll to bottom when new logs arrive and user was already at bottom
useEffect(() => {
if (!shouldAutoScrollRef.current) {
return;
}
const el = scrollContainerRef.current;
if (!el) {
shouldAutoScrollRef.current = false;
return;
}
el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
shouldAutoScrollRef.current = false;
isAtBottomRef.current = true;
}, [logs]);
if (!rolloutId) {
return null;
}
return (
<div>
{/* Content - matching MetadataSection container styling */}
<div className="border border-gray-200 p-2 max-w-[1200px] text-xs bg-white">
{/* Log level filter */}
<div className="mb-2 flex items-center gap-2">
<Select
value={selectedLevel}
onChange={(e) => setSelectedLevel(e.target.value)}
size="sm"
>
<option value="">All levels</option>
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
</Select>
<Button
onClick={() => fetchLogs(true)}
variant="primary"
size="sm"
disabled={loading}
>
{loading ? "Loading..." : "Refresh Logs"}
</Button>
</div>
{error && (
<div className="text-red-600 text-xs mb-2 px-3 py-2 bg-red-50 border border-red-200">
{error}
</div>
)}
{loading && logs.length === 0 && (
<div className="text-gray-500 text-xs">Loading logs...</div>
)}
{logs.length === 0 && !loading && !error && (
<div className="text-gray-500 text-xs">No logs found</div>
)}
{logs.length > 0 && (
<div
ref={scrollContainerRef}
className="max-h-[800px] min-h-4 overflow-auto border border-gray-200 bg-white"
>
<div className="min-w-max">
{logs.map((log, index) => (
<div
key={index}
className={`w-full text-xs px-3 py-1 border-b border-gray-200 last:border-b-0 ${
index % 2 === 0 ? "bg-white" : "bg-gray-50"
}`}
>
<div className="flex items-start gap-2">
<span
className={`font-medium text-xs flex-shrink-0 ${
log.level === "ERROR"
? "text-red-700"
: log.level === "WARNING"
? "text-yellow-700"
: log.level === "INFO"
? "text-blue-700"
: "text-gray-700"
}`}
>
{log.level}
</span>
<span className="text-gray-500 text-xs flex-shrink-0">
{new Date(log["@timestamp"]).toLocaleTimeString()}
</span>
<span className="text-gray-400 text-xs flex-shrink-0">
{log.logger_name}
</span>
<span className="text-gray-900 break-words min-w-0 flex-1">
{log.status_message && (
<span className="text-gray-500 font-mono">
Status: {log.status_message}{" "}
</span>
)}
{log.message}
</span>
</div>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
});