feat: refine request log

This commit is contained in:
2025-12-06 21:49:51 +08:00
parent 1941e6bcaf
commit 8be7af6815
7 changed files with 248 additions and 87 deletions

View File

@@ -106,7 +106,15 @@ export const authApi = {
// Logs API
export const logsApi = {
list: () => request<RequestLog[]>('/logs'),
list: (params?: { method?: string; search?: string }) => {
const query = new URLSearchParams();
if (params?.method) {
query.set('method', params.method);
}
if (params?.search) {
query.set('search', params.search);
}
const queryString = query.toString();
return request<RequestLog[]>(`/logs${queryString ? `?${queryString}` : ''}`);
},
};
export const fetchLogs = logsApi.list;

View File

@@ -64,7 +64,7 @@ const ChangePassword: Component<ChangePasswordProps> = (props) => {
return (
<Modal>
<ModalContent>
<ModalContent class="max-w-md">
<CardHeader>
<h3 class="text-lg font-medium text-gray-900">Change Password</h3>
</CardHeader>

View File

@@ -1,47 +1,103 @@
import { Component, createSignal, For } from 'solid-js';
import { Component, createSignal, For, Show } from 'solid-js';
import type { RequestLog } from '../types';
import { Card } from './ui/Card';
import { Button } from './ui/Button';
import { CardContent, CardFooter, CardHeader } from './ui/Card';
import { Modal, ModalContent } from './ui/Modal';
const TreeView: Component<{ data: any; name: string }> = (props) => {
const [isOpen, setIsOpen] = createSignal(true);
interface TreeViewProps {
data: any;
name: string;
isRoot?: boolean;
}
const TreeView: Component<TreeViewProps> = (props) => {
const [isOpen, setIsOpen] = createSignal(props.isRoot ?? false);
const isObject = typeof props.data === 'object' && props.data !== null;
const renderValue = (value: any) => {
switch (typeof value) {
case 'string':
return <span class="text-green-600">"{value}"</span>;
case 'number':
return <span class="text-blue-600">{value}</span>;
case 'boolean':
return <span class="text-purple-600">{String(value)}</span>;
case 'object':
if (value === null) return <span class="text-gray-500">null</span>;
// This case is handled by recursive TreeView
default:
return <span class="text-gray-500">{String(value)}</span>;
}
};
return (
<div class="ml-4 my-1">
<div class="flex items-center">
<span class="cursor-pointer" onClick={() => setIsOpen(!isOpen())}>
<div class="font-mono text-sm">
<div
class="flex items-center cursor-pointer hover:bg-gray-100 rounded px-1"
onClick={() => setIsOpen(!isOpen())}
>
<span class="w-4 inline-block text-gray-500">
{isObject ? (isOpen() ? '▼' : '►') : ''}
</span>
<span class="font-semibold ml-2">{props.name}</span>
<span class="font-semibold text-gray-800">{props.name}:</span>
<Show when={!isObject}>
<span class="ml-2">{renderValue(props.data)}</span>
</Show>
</div>
{isOpen() && isObject && (
<div class="pl-4 border-l-2 border-gray-200">
<Show when={isOpen() && isObject}>
<div class="pl-4 border-l border-gray-200 ml-3">
<For each={Object.entries(props.data)}>
{([key, value]) => {
if (typeof value === 'object' && value !== null && 'modified' in value && 'value' in value) {
return <TreeView name={key} data={value.value} />
}
return <TreeView name={key} data={value} />
}}
{([key, value]) => <TreeView name={key} data={value} />}
</For>
</div>
)}
{isOpen() && !isObject && <div class="pl-6 text-gray-700">{JSON.stringify(props.data)}</div>}
</Show>
</div>
);
};
const RequestDetails: Component<{ log: RequestLog }> = (props) => {
interface RequestDetailsProps {
log: RequestLog;
onClose: () => void;
}
const RequestDetails: Component<RequestDetailsProps> = (props) => {
return (
<Card class="p-4">
<h2 class="text-xl font-bold mb-4">Request Details</h2>
{/* TODO: interception method */}
<Modal>
<ModalContent class="max-w-3xl h-auto max-h-[90vh]">
<CardHeader>
<h3 class="text-lg font-medium text-gray-900">Request Details</h3>
<p class="text-sm text-gray-500">{props.log.method} at {new Date(props.log.created_at).toLocaleString()}</p>
</CardHeader>
<CardContent class="max-h-[70vh] overflow-y-auto">
<div class="grid grid-cols-1 gap-4">
<div>
<TreeView name="Request" data={props.log.request_body} />
<TreeView name="Response" data={props.log.response_body} />
<h4 class="font-semibold mb-2">Request</h4>
<div class="bg-gray-50 p-3 rounded overflow-x-auto">
<TreeView name="body" data={props.log.request_body} isRoot={true} />
</div>
</Card>
</div>
<div>
<h4 class="font-semibold mb-2">Response</h4>
<div class="bg-gray-50 p-3 rounded overflow-x-auto">
<TreeView name="body" data={props.log.response_body} isRoot={true} />
</div>
</div>
</div>
</CardContent>
<CardFooter class="flex justify-end pt-4">
<Button
type="button"
variant="secondary"
onClick={props.onClose}
>
Close
</Button>
</CardFooter>
</ModalContent>
</Modal>
);
};

View File

@@ -1,57 +1,111 @@
import { Component, createSignal, onMount, For, Show } from 'solid-js';
import { fetchLogs } from '../api/client';
import { Component, createMemo, createResource, createSignal, For, Show } from 'solid-js';
import { logsApi } from '../api/client';
import type { RequestLog as RequestLogType } from '../types';
import RequestDetails from './RequestDetails';
import { Card } from './ui/Card';
import { Input } from './ui/Input';
import { Select } from './ui/Select';
import RequestDetails from './RequestDetails';
const RequestLog: Component = () => {
const [logs, setLogs] = createSignal<RequestLogType[]>([]);
const [search, setSearch] = createSignal('');
const [method, setMethod] = createSignal('');
const [selectedLog, setSelectedLog] = createSignal<RequestLogType | null>(null);
onMount(async () => {
try {
const fetchedLogs = await fetchLogs();
setLogs(fetchedLogs);
} catch (error) {
console.error('Error fetching logs:', error);
const [logs] = createResource(
() => ({ search: search(), method: method() }),
async (filters) => {
// Solid's createResource refetches when the source accessor changes.
// We can add a debounce here if we want to avoid too many requests.
return logsApi.list(filters);
}
);
const methods = createMemo(() => {
if (!logs()) return [];
const allMethods = logs()!.map(log => log.method);
return [...new Set(allMethods)];
});
const handleLogClick = (log: RequestLogType) => {
setSelectedLog(log);
};
const handleCloseDetails = () => {
setSelectedLog(null);
};
const formatDate = (dateStr: string) => {
return new Date(dateStr).toLocaleString();
};
return (
<div class="flex space-x-4">
<div class={selectedLog() ? "w-1/3" : "w-full"}>
<>
<div class="space-y-4">
<h2 class="text-2xl font-semibold">Request Log</h2>
<div class="overflow-x-auto">
<Card>
<ul class="divide-y divide-gray-200">
<For each={logs()}>
{(log) => (
<li
class="p-4 hover:bg-gray-50 cursor-pointer"
onClick={() => handleLogClick(log)}
>
<div class="flex justify-between">
<span class="font-medium">{log.method}</span>
<span class="text-sm text-gray-500">{new Date(log.created_at).toLocaleTimeString()}</span>
<div class="p-4 flex items-center space-x-4 bg-gray-50 border-b">
<div class="flex-1">
<Input
type="text"
placeholder="Search in request/response..."
value={search()}
onInput={(e) => setSearch(e.currentTarget.value)}
/>
</div>
</li>
<div>
<Select
value={method()}
onChange={(e) => setMethod(e.currentTarget.value)}
class="min-w-[200px]"
>
<option value="">All Methods</option>
<For each={methods()}>
{(m) => <option value={m}>{m}</option>}
</For>
</Select>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Method</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Request Body</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<Show when={!logs.loading} fallback={<tr><td colspan="3" class="text-center py-4">Loading...</td></tr>}>
<For each={logs()} fallback={
<tr>
<td colspan="3" class="text-center py-8 text-gray-500">
No logs found.
</td>
</tr>
}>
{(log) => (
<tr class="hover:bg-gray-50 cursor-pointer" onClick={() => handleLogClick(log)}>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{log.method}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{formatDate(log.created_at)}</td>
<td class="px-6 py-4 text-sm text-gray-500 font-mono truncate max-w-lg">
{JSON.stringify(log.request_body)}
</td>
</tr>
)}
</For>
</ul>
</Show>
</tbody>
</table>
</div>
</Card>
</div>
</div>
<Show when={selectedLog()}>
{(log) =>
<div class="w-2/3">
<RequestDetails log={log()} />
</div>}
{(log) => <RequestDetails log={log()} onClose={handleCloseDetails} />}
</Show>
</div>
</>
);
};

View File

@@ -4,7 +4,7 @@ const Modal: Component<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
const [local, others] = splitProps(props, ['class']);
return (
<div
class={`fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50 ${local.class}`}
class={`fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50 ${local.class || ""}`}
{...others}
/>
);
@@ -14,7 +14,7 @@ const ModalContent: Component<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
const [local, others] = splitProps(props, ['class']);
return (
<div
class={`bg-white rounded-lg shadow-xl max-w-md w-full mx-4 ${local.class}`}
class={`bg-white rounded-lg shadow-xl w-full mx-4 ${local.class || ""}`}
{...others}
/>
);

View File

@@ -1,15 +1,17 @@
use std::sync::Arc;
use axum::{
Json,
extract::{Path, State},
extract::{Path, Query, State},
http::StatusCode,
Json,
};
use serde::Deserialize;
use tracing::error;
use crate::{
AppContext, auth,
auth,
db::{self, models::RequestLog},
AppContext,
};
use super::models::*;
@@ -237,7 +239,10 @@ pub async fn update_rule(
{
Ok(_) => match db::repositories::rules::find_by_id(&state.db, id).await {
Ok(Some(rule)) => Ok(Json(rule.into())),
_ => Err((StatusCode::NOT_FOUND, Json(ApiError::new("Rule not found")))),
_ => Err((
StatusCode::NOT_FOUND,
Json(ApiError::new("Rule not found")),
)),
},
Err(e) => {
error!("Failed to update rule: {}", e);
@@ -310,11 +315,25 @@ pub async fn verify_command(
}
}
}
// Log handlers
#[derive(Deserialize)]
pub struct ListLogsParams {
pub method: Option<String>,
pub search: Option<String>,
}
pub async fn list_logs(
State(state): State<Arc<AppContext>>,
Query(params): Query<ListLogsParams>,
) -> Result<Json<Vec<RequestLog>>, (StatusCode, Json<ApiError>)> {
match db::repositories::logs::list_all(&state.db).await {
match db::repositories::logs::list(
&state.db,
params.method.as_deref(),
params.search.as_deref(),
)
.await
{
Ok(logs) => Ok(Json(logs)),
Err(e) => {
error!("Failed to list logs: {}", e);

View File

@@ -1,13 +1,37 @@
use crate::db::models::RequestLog;
use serde_json::Value;
use sqlx::SqlitePool;
use sqlx::{QueryBuilder, SqlitePool};
pub async fn list_all(pool: &SqlitePool) -> anyhow::Result<Vec<RequestLog>> {
Ok(
sqlx::query_as::<_, RequestLog>("SELECT * FROM request_logs ORDER BY created_at")
.fetch_all(pool)
.await?,
)
pub async fn list(
pool: &SqlitePool,
method: Option<&str>,
search: Option<&str>,
) -> anyhow::Result<Vec<RequestLog>> {
let mut builder: QueryBuilder<sqlx::Sqlite> =
QueryBuilder::new("SELECT * FROM request_logs");
if let Some(method_val) = method {
builder.push(" WHERE method = ");
builder.push_bind(method_val);
}
if let Some(search_val) = search {
let pattern = format!("%{}%", search_val);
if method.is_some() {
builder.push(" AND (request_body LIKE ");
} else {
builder.push(" WHERE (request_body LIKE ");
}
builder.push_bind(pattern.clone());
builder.push(" OR response_body LIKE ");
builder.push_bind(pattern);
builder.push(")");
}
builder.push(" ORDER BY created_at DESC");
let query = builder.build_query_as();
Ok(query.fetch_all(pool).await?)
}
pub async fn create(