AuditLog
Quién hizo qué, cuándo y desde dónde: cada cambio de miembros, llaves, ajustes y datos, el más nuevo primero. Filtra por persona, acción y fechas; abre uno para ver exactamente qué cambió; exporta lo que está en pantalla.
import { Table, FilterBar, DateRangePicker, JsonViewer } from '@sypnia/ui/react'
En un computador
Filtra por persona o acción, cambia las fechas, abre un evento, exporta el resultado como CSV.
Registro de auditoría
Cada cambio en Northwind, el más nuevo primero. Se guarda 365 días.
| Cuándo | Persona | Acción | Sobre | Desde |
|---|---|---|---|---|
17 nov 2026, 10:00ahora | ARAna Ruiz | Inició sesión | — | Bogotá, CO · 181.49.0.0 |
17 nov 2026, 2:18hace 8 horas | LOLuis Ortega | Invitó a un miembro | sofia@northwind.io | Madrid, ES · 181.49.17.29 |
16 nov 2026, 18:36hace 15 horas | MGMarta Gil | Borró una tabla | orders_2024 | Lima, PE · 181.49.34.58 |
16 nov 2026, 10:54hace 23 horas | KMKenji Mori | Cambió ajustes | northwind-shop · Access | Bogotá, CO · 181.49.51.87 |
16 nov 2026, 3:12ayer | ARAna Ruiz | Inició sesión | — | Madrid, ES · 181.49.68.116 |
15 nov 2026, 19:30anteayer | LOLuis Ortega | Sacó a un miembro | old-bot@northwind.io | Lima, PE · 181.49.85.145 |
15 nov 2026, 11:48anteayer | MGMarta Gil | Creó una llave de API | checkout server | Bogotá, CO · 181.49.102.174 |
15 nov 2026, 4:06anteayer | KMKenji Mori | Revocó una llave de API | nightly export | Madrid, ES · 181.49.119.203 |
14 nov 2026, 20:24hace 3 días | ARAna Ruiz | Inició sesión | — | Lima, PE · 181.49.136.232 |
14 nov 2026, 12:42hace 3 días | LOLuis Ortega | Invitó a un miembro | sofia@northwind.io | Bogotá, CO · 181.49.153.6 |
14 nov 2026, 5:00hace 3 días | MGMarta Gil | Borró una tabla | orders_2024 | Madrid, ES · 181.49.170.35 |
13 nov 2026, 21:18hace 4 días | KMKenji Mori | Cambió ajustes | northwind-shop · Access | Lima, PE · 181.49.187.64 |
13 nov 2026, 13:36hace 4 días | ARAna Ruiz | Inició sesión | — | Bogotá, CO · 181.49.204.93 |
13 nov 2026, 5:54hace 4 días | LOLuis Ortega | Sacó a un miembro | old-bot@northwind.io | Madrid, ES · 181.49.221.122 |
12 nov 2026, 22:12hace 4 días | MGMarta Gil | Creó una llave de API | checkout server | Lima, PE · 181.49.238.151 |
12 nov 2026, 14:30hace 5 días | KMKenji Mori | Revocó una llave de API | nightly export | Bogotá, CO · 181.49.0.180 |
12 nov 2026, 6:48hace 5 días | ARAna Ruiz | Inició sesión | — | Madrid, ES · 181.49.17.209 |
11 nov 2026, 23:06hace 5 días | LOLuis Ortega | Invitó a un miembro | sofia@northwind.io | Lima, PE · 181.49.34.238 |
11 nov 2026, 15:24hace 6 días | MGMarta Gil | Borró una tabla | orders_2024 | Bogotá, CO · 181.49.51.12 |
11 nov 2026, 7:42hace 6 días | KMKenji Mori | Cambió ajustes | northwind-shop · Access | Madrid, ES · 181.49.68.41 |
Código
import { useMemo, useState } from 'react';
import {
Avatar, Badge, Button, DateRangePicker, DescriptionList, Drawer, EmptyState, Field, FilterBar, InlineCode, JsonViewer, Page, PageHeader, Row,
SkeletonOf, SkeletonWords, Stack, Table, Text, downloadCsv, useSypnia, type DataFilters, type DateRange,
} from '@sypnia/ui/react';
// Who did what, when and from where, in an organization: every change to members, keys, settings and data, newest
// first, kept for a year. Filter by person, kind of action and dates; open one to see exactly what changed; export
// what is on screen as CSV for a review.
type Event = { id: string; at: number; actor: string; action: 'key.created' | 'key.revoked' | 'member.invited' | 'member.removed' | 'settings.changed' | 'table.dropped' | 'sign_in'; target: string; ip: string; place: string };
const en = {
title: 'Audit log', lead: 'Every change in Northwind, newest first. Kept for 365 days.', exportCsv: 'Export CSV', filters: 'Filter the log', who: 'Person', what: 'Action', dates: 'Dates',
when: 'When', target: 'On', from: 'From', count: (n: number) => `${n} events`, detail: 'What happened', changes: 'The change, as recorded', close: 'Close',
actions: { 'key.created': 'Created an API key', 'key.revoked': 'Revoked an API key', 'member.invited': 'Invited a member', 'member.removed': 'Removed a member', 'settings.changed': 'Changed settings', 'table.dropped': 'Deleted a table', sign_in: 'Signed in' },
none: 'Nothing happened with these filters', noneBody: 'Widen the dates or clear a filter.', clear: 'Clear filters', event: 'Event', ip: 'IP address',
failed: 'The log could not be loaded. Every event is kept; try again in a minute.',
};
const es: typeof en = {
title: 'Registro de auditoría', lead: 'Cada cambio en Northwind, el más nuevo primero. Se guarda 365 días.', exportCsv: 'Exportar CSV', filters: 'Filtrar el registro', who: 'Persona', what: 'Acción', dates: 'Fechas',
when: 'Cuándo', target: 'Sobre', from: 'Desde', count: (n: number) => `${n} eventos`, detail: 'Qué pasó', changes: 'El cambio, tal como quedó registrado', close: 'Cerrar',
actions: { 'key.created': 'Creó una llave de API', 'key.revoked': 'Revocó una llave de API', 'member.invited': 'Invitó a un miembro', 'member.removed': 'Sacó a un miembro', 'settings.changed': 'Cambió ajustes', 'table.dropped': 'Borró una tabla', sign_in: 'Inició sesión' },
none: 'No pasó nada con estos filtros', noneBody: 'Amplía las fechas o quita un filtro.', clear: 'Borrar filtros', event: 'Evento', ip: 'Dirección IP',
failed: 'No se pudo cargar el registro. Cada evento está guardado; intenta de nuevo en un minuto.',
};
const people = ['Ana Ruiz', 'Luis Ortega', 'Marta Gil', 'Kenji Mori'];
const kinds: Event['action'][] = ['sign_in', 'settings.changed', 'key.created', 'member.invited', 'sign_in', 'key.revoked', 'table.dropped', 'member.removed'];
const targets: Record<Event['action'], string> = { 'key.created': 'checkout server', 'key.revoked': 'nightly export', 'member.invited': 'sofia@northwind.io', 'member.removed': 'old-bot@northwind.io', 'settings.changed': 'northwind-shop · Access', 'table.dropped': 'orders_2024', sign_in: '—' };
const now = Date.UTC(2026, 10, 17, 15);
const events: Event[] = Array.from({ length: 86 }, (_, i) => {
const action = kinds[(i * 3) % kinds.length];
return { id: `evt_${(70412 - i * 13).toString(36)}`, at: now - i * 7.7 * 3600e3, actor: people[(i * 5) % 4], action, target: targets[action], ip: `181.49.${(i * 17) % 255}.${(i * 29) % 255}`, place: ['Bogotá, CO', 'Madrid, ES', 'Lima, PE'][i % 3] };
});
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
export default function AuditLog({ state = 'ready' }: { state?: 'ready' | 'loading' | 'none' | 'error' }) {
const { locale, format } = useSypnia();
const c = locale.startsWith('es') ? es : en;
const [filters, setFilters] = useState<DataFilters>(state === 'none' ? { action: 'table.dropped', actor: 'Kenji Mori' } : {});
const [range, setRange] = useState<DateRange | null>({ start: iso(now - 30 * 86400e3), end: iso(now) });
const [open, setOpen] = useState<Event | null>(null);
const [failed, setFailed] = useState(state === 'error');
const shown = useMemo(() => events.filter((e) => (!filters.actor || e.actor === filters.actor) && (!filters.action || e.action === filters.action)
&& (!range || (iso(e.at) >= range.start && iso(e.at) <= range.end))), [filters, range]);
// Loading: the real page. The dates and filters are the person's, so they are there; the events are a page of rows
// (and the pagination bar, as there were more than a page the last time), each value as long as a real one.
const loading = state === 'loading';
const was = (i: number) => events[i % events.length];
const fields = [
{ id: 'actor', label: c.who, type: 'select' as const, options: people },
{ id: 'action', label: c.what, type: 'select' as const, options: Object.entries(c.actions).map(([value, label]) => ({ value, label })) },
];
const csv = () => downloadCsv('audit-log', [
{ header: c.when, value: (e: Event) => new Date(e.at).toISOString() }, { header: c.who, value: (e: Event) => e.actor }, { header: c.what, value: (e: Event) => e.action },
{ header: c.target, value: (e: Event) => e.target }, { header: c.ip, value: (e: Event) => e.ip },
], shown);
return (
<Page wide>
<PageHeader title={c.title} lead={c.lead} actions={<Button icon="download" onClick={csv} disabled={loading || !shown.length}>{c.exportCsv}</Button>} />
<Row top>
<Field label={c.dates}><DateRangePicker value={range} onChange={setRange} max={iso(now)} /></Field>
</Row>
<FilterBar label={c.filters} fields={fields} values={filters} onChange={setFilters} />
<Table label={c.title} rows={failed || loading ? undefined : shown} rowKey={(e) => e.id} pageSize={20} onRowClick={setOpen} loading={loading} loadingRows={events.length}
error={failed ? c.failed : undefined} onRetry={() => setFailed(false)} toolbar={loading ? <SkeletonOf><Badge tone="neutral">{c.count(shown.length)}</Badge></SkeletonOf> : <Badge tone="neutral">{c.count(shown.length)}</Badge>}
empty={<EmptyState icon="audit" compact title={c.none} actions={<Button onClick={() => setFilters({})}>{c.clear}</Button>}>{c.noneBody}</EmptyState>}
columns={[
{ id: 'when', header: c.when, cell: (e) => <Stack gap={0}><span>{format.dateTime(new Date(e.at))}</span><Text as="span" size="xs" tone="muted">{format.relative(new Date(e.at), now)}</Text></Stack>,
skeleton: (i) => <Stack gap={0}><span><SkeletonWords>{format.dateTime(new Date(was(i).at))}</SkeletonWords></span><Text as="span" size="xs" tone="muted"><SkeletonWords>{format.relative(new Date(was(i).at), now)}</SkeletonWords></Text></Stack> },
{ id: 'who', header: c.who, cell: (e) => <Row gap={2} nowrap><Avatar name={e.actor} size="sm" />{e.actor}</Row>,
skeleton: (i) => <Row gap={2} nowrap><SkeletonOf><Avatar name={was(i).actor} size="sm" /></SkeletonOf><SkeletonWords>{was(i).actor}</SkeletonWords></Row> },
{ id: 'what', header: c.what, cell: (e) => <Badge tone={e.action === 'table.dropped' || e.action === 'member.removed' || e.action === 'key.revoked' ? 'warn' : 'neutral'}>{c.actions[e.action]}</Badge>,
skeleton: (i) => <SkeletonOf><Badge>{c.actions[was(i).action]}</Badge></SkeletonOf> },
{ id: 'target', header: c.target, cell: (e) => e.target, skeleton: (i) => <SkeletonWords>{was(i).target}</SkeletonWords> },
{ id: 'from', header: c.from, cell: (e) => `${e.place} · ${e.ip}`, skeleton: (i) => <SkeletonWords>{`${was(i).place} · ${was(i).ip}`}</SkeletonWords> },
]} />
<Drawer open={open !== null} onClose={() => setOpen(null)} title={open ? c.actions[open.action] : c.detail} footer={<Button onClick={() => setOpen(null)}>{c.close}</Button>}>
{open && (
<Stack gap={5}>
<DescriptionList columns={1} items={[
{ term: c.who, description: open.actor }, { term: c.when, description: format.dateTime(new Date(open.at)) },
{ term: c.target, description: open.target }, { term: c.from, description: `${open.place} · ${open.ip}` }, { term: c.event, description: <InlineCode>{open.id}</InlineCode> },
]} />
<JsonViewer title={c.changes} open={2} value={{ id: open.id, type: open.action, actor: { name: open.actor, ip: open.ip }, target: open.target, at: new Date(open.at).toISOString(), ...(open.action === 'settings.changed' ? { changes: { signups: { from: true, to: false } } } : {}) }} />
</Stack>
)}
</Drawer>
</Page>
);
} En un celular
En un celular cada evento es una tarjeta y el detalle ocupa la pantalla.
Nada coincide
Los filtros se quedan, con una forma de borrarlos.
Registro de auditoría
Cada cambio en Northwind, el más nuevo primero. Se guarda 365 días.
No pasó nada con estos filtros
Skeleton
Las fechas y los filtros se quedan (son de la persona); el registro dibuja una página de filas del tamaño de eventos reales, y la barra de paginación.
Registro de auditoría
Cada cambio en Northwind, el más nuevo primero. Se guarda 365 días.
| Cuándo | Persona | Acción | Sobre | Desde |
|---|---|---|---|---|
Cuándo usarlo
Úsalo cuando
- Organizaciones que deben responder «¿quién cambió esto?».
- Exportar los eventos filtrados para una revisión.
No lo uses cuando
- Dejar que la gente edite o borre eventos: el registro solo crece.
- Solo códigos para las acciones: «Borró una tabla», con el código en el detalle.
Para todos
- Cada fila abre su detalle con Enter o un clic; el detalle es un panel lateral que devuelve el foco a la fila.
- Las acciones destructivas llevan una palabra además de un color.
- El rango de fechas son dos fechas, escritas o elegidas en un calendario.
Props
| Table | Tipo | Por defecto |
|---|---|---|
columnsobligatorio | Column<Row>[] | |
labelobligatorioA name for screen readers. | string | |
rowKeyobligatorio | (row: Row) => string | number | |
rowsobligatorio | Row[] | undefined | |
dense | boolean | |
emptyWhat to show when there are no rows: an EmptyState with the next step. | ReactNode | |
errorSomething failed: the region says so. Say what happened in plain words. | ReactNode | |
loadingData is on its way: rows are drawn as skeletons of the right shape. | boolean | |
loadingRowsHow many skeleton rows to draw while loading: as many as will come (the count of the last visit, a known total). Default 6, never more than a page. | number | |
onRetryWith `error`: shows a «Try again» button that calls it. | (() => void) | |
onRowClick | ((row: Row) => void) | |
pageSizeRows per page, 25 by default: every table paginates by itself. For server-side pages pass `pagination` instead. | number | |
paginationServer-side pagination: the table shows `rows` as they are and this bar under them. | { page: number; pageSize: number; total: number; onPage: (p: number) => void; onPageSize?: ((s: number) => void); } | |
toolbar | ReactNode |
| FilterBar | Tipo | Por defecto |
|---|---|---|
fieldsobligatorio | FilterField[] | |
onChangeobligatorio | (values: DataFilters) => void | |
valuesobligatorioThe value of each filter by field id. An empty or missing value means the filter is off. | DataFilters | |
collapsedOnly the chips of the filters that are on, without the fields. | boolean | |
labelA name for screen readers. | string |
| DateRangePicker | Tipo | Por defecto |
|---|---|---|
aria-describedby | string | |
aria-labelThe name for screen readers when there is no Field around it. | string | |
aria-labelledby | string | |
className | string | |
defaultValue | DateRange | |
disabled | boolean | |
endName | string | |
idInside a Field it comes from the Field. | string | |
invalidMarks the value as wrong. Inside a `<Field error>` it is set for you. | boolean | |
maxThe last day that can be chosen. | string | |
minThe first day that can be chosen, as `2026-11-01`. | string | |
nameThe name of the value when it travels in a form. | string | |
onChange | ((range: DateRange | null) => void) | |
startNameNames of the two values when they travel in a form. | string | |
unavailableDays that cannot be chosen: return true for them. | ((date: string) => boolean) | |
valueFrom one day to another, both included: `{ start: '2026-11-01', end: '2026-11-17' }`. | DateRange | null |
| JsonViewer | Tipo | Por defecto |
|---|---|---|
valueobligatorio | unknown | |
open | number | 2 |
title | string | JSON |