Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore/unified-logs-fixes-03 (#36725)

Joshen Lim620805a1acd7
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
index 7010753bfff..0cb64d8ab94 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
@@ -42,6 +42,7 @@ import {
} from 'ui'
import { RefreshButton } from '../../ui/DataTable/RefreshButton'
import { UNIFIED_LOGS_COLUMNS } from './components/Columns'
+import { DownloadLogsButton } from './components/DownloadLogsButton'
import { LogsListPanel } from './components/LogsListPanel'
import { ServiceFlowPanel } from './ServiceFlowPanel'
import { CHART_CONFIG, SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants'
@@ -314,6 +315,7 @@ export const UnifiedLogs = () => {
/>
<DataTableToolbar
renderActions={() => [
+ <DownloadLogsButton searchParameters={searchParameters} />,
<RefreshButton isLoading={isRefetchingData} onRefresh={refetchAllData} />,
fetchPreviousPage ? (
<LiveButton
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts
index 8d6f7577932..3efedfb24fe 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts
@@ -45,8 +45,6 @@ export const getLevelLabel = (value: (typeof LEVELS)[number]): string => {
return '4xx'
case 'error':
return '5xx'
- default:
- return 'Unknown'
}
}
@@ -76,11 +74,6 @@ export function getLevelRowClassName(value: (typeof LEVELS)[number]): string {
'bg-destructive/5 hover:bg-destructive/10 data-[state=selected]:bg-destructive/20 focus-visible:bg-destructive/10',
'dark:bg-error/10 dark:hover:bg-destructive/20 dark:data-[state=selected]:bg-destructive/30 dark:focus-visible:bg-destructive/20'
)
- case 'info':
- return cn(
- 'bg-info/5 hover:bg-info/10 data-[state=selected]:bg-info/20 focus-visible:bg-info/10',
- 'dark:bg-info/10 dark:hover:bg-info/20 dark:data-[state=selected]:bg-info/30 dark:focus-visible:bg-info/20'
- )
default:
return ''
}
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/DataTableSheetContent.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/DataTableSheetContent.tsx
index ff08c51e681..6fd5aa0ac68 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/DataTableSheetContent.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/DataTableSheetContent.tsx
@@ -71,7 +71,7 @@ export function DataTableSheetContent<TData, TMeta>({
)}
>
<dt className="shrink-0 text-muted-foreground">{field.label}</dt>
- <dd className="font-mono w-full text-right">
+ <dd className="font-mono w-full text-right truncate">
{Component ? <Component {...data} metadata={metadata} /> : value}
</dd>
</div>
@@ -87,7 +87,7 @@ export function DataTableSheetContent<TData, TMeta>({
)}
>
<dt className="shrink-0 text-muted-foreground">{field.label}</dt>
- <dd className="font-mono w-full text-right">
+ <dd className="font-mono w-full text-right truncate">
{Component ? <Component {...data} metadata={metadata} /> : value}
</dd>
</DataTableSheetRowAction>
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx
new file mode 100644
index 00000000000..84b8a1ed03e
--- /dev/null
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx
@@ -0,0 +1,168 @@
+import saveAs from 'file-saver'
+import { Download } from 'lucide-react'
+import Papa from 'papaparse'
+import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useGetUnifiedLogsMutation } from 'data/logs/get-unified-logs'
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogSection,
+ DialogTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+} from 'ui'
+import { QuerySearchParamsType } from '../UnifiedLogs.types'
+
+const DEFAULT_NUM_ROWS = '100'
+const DEFAULT_DURATION = '1'
+
+interface DownloadLogsButtonProps {
+ searchParameters: QuerySearchParamsType
+}
+
+export const DownloadLogsButton = ({ searchParameters }: DownloadLogsButtonProps) => {
+ const { ref } = useParams()
+ const [numRows, setNumRows] = useState(DEFAULT_NUM_ROWS)
+ const [numHours, setNumHours] = useState(DEFAULT_NUM_ROWS)
+ const [selectedFormat, setSelectedFormat] = useState<'csv' | 'json'>()
+
+ const { mutate: retrieveLogs, isLoading } = useGetUnifiedLogsMutation({
+ onSuccess: (res) => {
+ if (selectedFormat === 'json') {
+ const blob = new Blob([JSON.stringify(res, null, 2)], { type: 'text/json;charset=utf-8;' })
+ saveAs(blob, `supabase_logs.json`)
+ toast.success('Downloading logs as JSON')
+ } else {
+ if (res.length === 0) return
+ const headers = Object.keys(res[0])
+ const formattedResults = res.map((row: any) => {
+ const r = { ...row }
+ Object.keys(row).forEach((x) => {
+ if (typeof row[x] === 'object') r[x] = JSON.stringify(row[x])
+ })
+ return r
+ })
+ const csv = Papa.unparse(formattedResults, { columns: headers })
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
+ saveAs(blob, `supabase_logs.csv`)
+ toast.success('Downloading logs as CSV')
+ }
+
+ setSelectedFormat(undefined)
+ },
+ })
+
+ const onExportData = () => {
+ if (!ref) return console.error('Project ref is required')
+
+ const hasSpecificTimeRange = 'date' in searchParameters
+ retrieveLogs({
+ projectRef: ref,
+ search: searchParameters,
+ limit: Number(numRows),
+ hoursAgo: !hasSpecificTimeRange ? Number(numHours) : undefined,
+ })
+ }
+
+ useEffect(() => {
+ if (!!selectedFormat) {
+ setNumRows(DEFAULT_NUM_ROWS)
+ setNumHours(DEFAULT_DURATION)
+ }
+ }, [selectedFormat])
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger>
+ <ButtonTooltip
+ type="outline"
+ className="w-[26px]"
+ icon={<Download className="text-foreground" />}
+ tooltip={{ content: { side: 'bottom', text: 'Download logs' } }}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-36">
+ <DropdownMenuItem onClick={() => setSelectedFormat('csv')}>
+ <p>Download as CSV</p>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setSelectedFormat('json')}>
+ <p>Download as JSON</p>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Dialog
+ open={!!selectedFormat}
+ onOpenChange={(open) => {
+ if (!open) setSelectedFormat(undefined)
+ }}
+ >
+ <DialogContent size="small">
+ <DialogHeader className="border-b">
+ <DialogTitle>Download logs as {selectedFormat?.toLocaleUpperCase()}</DialogTitle>
+ <DialogDescription>
+ Export your logs with the currently applied filters
+ </DialogDescription>
+ </DialogHeader>
+ <DialogSection className="flex flex-col gap-y-2">
+ <div className="flex justify-between gap-x-2">
+ <p className="text-sm mb-2">Result limit for export</p>
+ <Select_Shadcn_ value={numRows} onValueChange={setNumRows}>
+ <SelectTrigger_Shadcn_ className="w-24">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="100">100</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="500">500</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="1000">1000</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </div>
+ {!('date' in searchParameters) && (
+ <div className="flex justify-between gap-x-2">
+ <p className="text-sm mb-2">Duration to retrieve</p>
+ <Select_Shadcn_ value={numHours} onValueChange={setNumHours}>
+ <SelectTrigger_Shadcn_ className="w-36">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="1">1 hour ago</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="12">12 hours ago</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="24">24 hours ago</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </div>
+ )}
+ </DialogSection>
+ <DialogFooter>
+ <Button
+ type="default"
+ disabled={isLoading}
+ onClick={() => setSelectedFormat(undefined)}
+ >
+ Cancel
+ </Button>
+ <Button type="primary" loading={isLoading} onClick={onExportData}>
+ Export
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsx
index cadfcf0ccbb..8bba137b90a 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsx
@@ -1,3 +1,4 @@
+import CopyButton from 'components/ui/CopyButton'
import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'
import { HoverCardTimestamp } from './HoverCardTimestamp'
@@ -27,9 +28,10 @@ export const LogsList = ({ logs = [] }: LogsListProps) => {
<div className="text-sm font-mono">
{logs.map((log) => {
const date = new Date(Number(log.timestamp) / 1000)
+ const message = log.event_message.split('\n').filter((x) => x.length > 0)
return (
- <div key={log.id} className="py-1.5 px-4 border-b border-border last:border-0">
+ <div key={log.id} className="group py-1.5 px-4 border-b border-border last:border-0">
<div className="flex items-start gap-5">
<div className="flex flex-row items-center gap-5 flex-shrink-0">
<HoverCardTimestamp date={date} className="flex-shrink-0" />
@@ -39,8 +41,18 @@ export const LogsList = ({ logs = [] }: LogsListProps) => {
className="min-w-20 flex-shrink-0"
/>
</div>
- <div className="mt-1 whitespace-pre-wrap break-all pl-2 text-[0.8rem] flex-shrink-0 overflow-x-auto">
- {log.event_message}
+ <div className="w-full grow relative mt-1 whitespace-pre-wrap break-all pl-2 text-[0.75rem] flex-shrink-0">
+ {message.map((x, i) => (
+ <pre key={`message-${i}`} className="font-mono w-full">
+ {x}
+ </pre>
+ ))}
+ <CopyButton
+ iconOnly
+ type="default"
+ text={log.event_message}
+ className="absolute top-[5px] right-2 z-10 opacity-0 group-hover:opacity-100 transition"
+ />
</div>
</div>
</div>
diff --git a/apps/studio/components/ui/DataTable/DataTable.constants.ts b/apps/studio/components/ui/DataTable/DataTable.constants.ts
index da947462782..89aa4de5783 100644
--- a/apps/studio/components/ui/DataTable/DataTable.constants.ts
+++ b/apps/studio/components/ui/DataTable/DataTable.constants.ts
@@ -8,7 +8,7 @@ export const SPACE_DELIMITER = '_'
export const RANGE_DELIMITER = '-'
export const SORT_DELIMITER = '.'
-export const LEVELS = ['success', 'warning', 'error', 'info'] as const
+export const LEVELS = ['success', 'warning', 'error'] as const
export const presets = [
{
diff --git a/apps/studio/components/ui/DataTable/DataTable.utils.ts b/apps/studio/components/ui/DataTable/DataTable.utils.ts
index 12997306dab..3f7c330a8ff 100644
--- a/apps/studio/components/ui/DataTable/DataTable.utils.ts
+++ b/apps/studio/components/ui/DataTable/DataTable.utils.ts
@@ -78,7 +78,6 @@ export function getLevelColor(
bg: 'bg-destructive',
border: 'border-destructive',
}
- case 'info':
default:
return {
text: 'text-info',
diff --git a/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx b/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx
index d1cec2acbfe..fb161601636 100644
--- a/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx
@@ -170,7 +170,7 @@ export function DataTableSheetRowAction<TData, TFields extends DataTableFilterFi
<div className="absolute inset-0 bg-background/70 place-content-center">Value copied</div>
) : null}
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" side="left">
+ <DropdownMenuContent align="end" side="bottom" className="w-40">
{renderOptions()}
<DropdownMenuSeparator />
<DropdownMenuItem
diff --git a/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx b/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx
index 24fc9a6641a..abbc1d1f93e 100644
--- a/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx
@@ -2,7 +2,6 @@ import { GripVertical, Settings2 } from 'lucide-react'
import { useMemo, useState } from 'react'
import {
- Button,
Checkbox_Shadcn_,
Command_Shadcn_ as Command,
CommandEmpty_Shadcn_ as CommandEmpty,
@@ -14,6 +13,7 @@ import {
PopoverContent_Shadcn_ as PopoverContent,
PopoverTrigger_Shadcn_ as PopoverTrigger,
} from 'ui'
+import { ButtonTooltip } from '../ButtonTooltip'
import { Sortable, SortableDragHandle, SortableItem } from './primitives/Sortable'
import { useDataTable } from './providers/DataTableProvider'
@@ -36,13 +36,14 @@ export function DataTableViewOptions() {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
- <Button
+ <ButtonTooltip
type="outline"
size="tiny"
role="combobox"
aria-expanded={open}
className="w-[26px]"
icon={<Settings2 className="text-foreground" />}
+ tooltip={{ content: { side: 'bottom', text: 'Toggle column visibility' } }}
/>
</PopoverTrigger>
<PopoverContent portal side="bottom" align="end" className="w-[200px] p-0">
diff --git a/apps/studio/components/ui/DataTable/RefreshButton.tsx b/apps/studio/components/ui/DataTable/RefreshButton.tsx
index 2adee376572..0f664e62586 100644
--- a/apps/studio/components/ui/DataTable/RefreshButton.tsx
+++ b/apps/studio/components/ui/DataTable/RefreshButton.tsx
@@ -1,5 +1,5 @@
import { LoaderCircle, RefreshCcw } from 'lucide-react'
-import { Button } from 'ui'
+import { ButtonTooltip } from '../ButtonTooltip'
interface RefreshButtonProps {
isLoading: boolean
@@ -8,7 +8,7 @@ interface RefreshButtonProps {
export const RefreshButton = ({ isLoading, onRefresh }: RefreshButtonProps) => {
return (
- <Button
+ <ButtonTooltip
size="tiny"
type="outline"
disabled={isLoading}
@@ -21,6 +21,7 @@ export const RefreshButton = ({ isLoading, onRefresh }: RefreshButtonProps) => {
<RefreshCcw className="text-foreground" />
)
}
+ tooltip={{ content: { side: 'bottom', text: 'Refresh logs' } }}
/>
)
}
diff --git a/apps/studio/data/logs/get-unified-logs.ts b/apps/studio/data/logs/get-unified-logs.ts
new file mode 100644
index 00000000000..7280249c5b2
--- /dev/null
+++ b/apps/studio/data/logs/get-unified-logs.ts
@@ -0,0 +1,91 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { getUnifiedLogsQuery } from 'components/interfaces/UnifiedLogs/UnifiedLogs.queries'
+import { QuerySearchParamsType } from 'components/interfaces/UnifiedLogs/UnifiedLogs.types'
+import { handleError, post } from 'data/fetchers'
+import type { ResponseError } from 'types'
+import { getUnifiedLogsISOStartEnd } from './unified-logs-infinite-query'
+
+export type getUnifiedLogsVariables = {
+ projectRef: string
+ search: QuerySearchParamsType
+ limit: number
+ hoursAgo?: number
+}
+
+// [Joshen] Mainly for retrieving logs on demand for downloading
+export async function retrieveUnifiedLogs({
+ projectRef,
+ search,
+ limit,
+ hoursAgo,
+}: getUnifiedLogsVariables) {
+ if (typeof projectRef === 'undefined')
+ throw new Error('projectRef is required for retrieveUnifiedLogs')
+
+ const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search, hoursAgo)
+ const sql = `${getUnifiedLogsQuery(search)} ORDER BY timestamp DESC, id DESC LIMIT ${limit}`
+
+ const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
+ params: { path: { ref: projectRef } },
+ body: { iso_timestamp_start: isoTimestampStart, iso_timestamp_end: isoTimestampEnd, sql },
+ })
+
+ if (error) handleError(error)
+
+ const resultData = data?.result ?? []
+
+ const result = resultData.map((row: any) => {
+ const date = new Date(Number(row.timestamp) / 1000)
+ return {
+ id: row.id,
+ date,
+ timestamp: row.timestamp,
+ level: row.level,
+ status: row.status || 200,
+ method: row.method,
+ host: row.host,
+ pathname: (row.url || '').replace(/^https?:\/\/[^\/]+/, '') || row.pathname || '',
+ event_message: row.event_message || row.body || '',
+ headers:
+ typeof row.headers === 'string' ? JSON.parse(row.headers || '{}') : row.headers || {},
+ regions: row.region ? [row.region] : [],
+ log_type: row.log_type || '',
+ latency: row.latency || 0,
+ log_count: row.log_count || null,
+ logs: row.logs || [],
+ auth_user: row.auth_user || null,
+ }
+ })
+
+ return result
+}
+
+type LogDrainCreateData = Awaited<ReturnType<typeof retrieveUnifiedLogs>>
+
+export const useGetUnifiedLogsMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<LogDrainCreateData, ResponseError, getUnifiedLogsVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<LogDrainCreateData, ResponseError, getUnifiedLogsVariables>(
+ (vars) => retrieveUnifiedLogs(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to retrieve logs: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/logs/unified-logs-infinite-query.ts b/apps/studio/data/logs/unified-logs-infinite-query.ts
index 1e83b6d5360..c8e04f258ef 100644
--- a/apps/studio/data/logs/unified-logs-infinite-query.ts
+++ b/apps/studio/data/logs/unified-logs-infinite-query.ts
@@ -24,7 +24,10 @@ export type UnifiedLogsData = any
export type UnifiedLogsError = ResponseError
export type UnifiedLogsVariables = { projectRef?: string; search: QuerySearchParamsType }
-export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {
+export const getUnifiedLogsISOStartEnd = (
+ search: QuerySearchParamsType,
+ endHoursFromNow: number = 1
+) => {
// Extract date range from search or use default (last hour)
let isoTimestampStart: string
let isoTimestampEnd: string
@@ -36,8 +39,8 @@ export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {
} else {
const now = new Date()
isoTimestampEnd = now.toISOString()
- const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)
- isoTimestampStart = oneHourAgo.toISOString()
+ const nHoursAgo = new Date(now.getTime() - 60 * 60 * (endHoursFromNow * 1000))
+ isoTimestampStart = nHoursAgo.toISOString()
}
return { isoTimestampStart, isoTimestampEnd }