Skip to content

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

Update logs page UI

Joshen Limf81cfe08c33b
diff --git a/studio/components/interfaces/Settings/Logs/LogPanel.tsx b/studio/components/interfaces/Settings/Logs/LogPanel.tsx
new file mode 100644
index 00000000000..7e9b0637728
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/LogPanel.tsx
@@ -0,0 +1,104 @@
+import { FC } from 'react'
+import {
+ Button,
+ Input,
+ Dropdown,
+ Typography,
+ IconChevronDown,
+ IconRefreshCw,
+ IconX,
+ Toggle,
+} from '@supabase/ui'
+import { LogTemplate } from '.'
+
+interface Props {
+ searchValue?: string
+ templates?: any
+ isLoading: boolean
+ isCustomQuery: boolean
+ hasNewData: boolean
+ showReset: boolean
+ onReset: () => void
+ onRefresh?: () => void
+ onSearch?: (query: string) => void
+ onCustomClick?: () => void
+ onSelectTemplate: (template: LogTemplate) => void
+}
+
+/**
+ * Logs control panel header + wrapper
+ */
+const LogPanel: FC<Props> = ({
+ searchValue,
+ templates = [],
+ isLoading,
+ isCustomQuery,
+ hasNewData,
+ showReset,
+ onReset,
+ onRefresh,
+ onSearch = () => {},
+ onCustomClick,
+ onSelectTemplate,
+}) => {
+ return (
+ <div className="bg-panel-header-light dark:bg-panel-header-dark">
+ <div className="px-2 py-1 flex items-center justify-between w-full">
+ <div className="flex flex-row gap-x-4 items-center">
+ <Button
+ type="text"
+ icon={
+ <div className="relative">
+ {hasNewData && (
+ <div className={['absolute -top-0.5 -right-0.5', 'h-2 w-2 z-50'].join(' ')}>
+ <div className="bg-green-500 rounded-full w-full h-full"></div>
+ <div className="absolute top-0 right-0 bg-green-500 rounded-full w-full h-full animate-ping"></div>
+ </div>
+ )}
+ <IconRefreshCw />
+ </div>
+ }
+ loading={isLoading}
+ onClick={onRefresh}
+ >
+ Refresh
+ </Button>
+ <Dropdown
+ side="bottom"
+ align="start"
+ overlay={templates.map((template: LogTemplate) => (
+ <Dropdown.Item key={template.label} onClick={() => onSelectTemplate(template)}>
+ <Typography.Text>{template.label}</Typography.Text>
+ </Dropdown.Item>
+ ))}
+ >
+ <Button type="text" iconRight={<IconChevronDown />}>
+ Templates
+ </Button>
+ </Dropdown>
+
+ <div className="flex items-center space-x-2">
+ <Typography.Text type="secondary" small>
+ Search via query
+ </Typography.Text>
+ <Toggle size="tiny" checked={isCustomQuery} onChange={onCustomClick} />
+ </div>
+ </div>
+ <div className="flex items-center gap-x-4">
+ <Input
+ size="tiny"
+ className="max-w-32"
+ placeholder="Filter"
+ onChange={(e) => onSearch(e.target.value)}
+ value={searchValue}
+ actions={
+ showReset && <IconX size={'tiny'} className="cursor-pointer mx-1" onClick={onReset} />
+ }
+ />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default LogPanel
diff --git a/studio/components/interfaces/Settings/Logs/LogSelection.tsx b/studio/components/interfaces/Settings/Logs/LogSelection.tsx
new file mode 100644
index 00000000000..49f119f46dd
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/LogSelection.tsx
@@ -0,0 +1,63 @@
+import dayjs from 'dayjs'
+import { FC } from 'react'
+import { Input, Typography, IconX } from '@supabase/ui'
+
+import { LogData } from './Logs.types'
+
+interface Props {
+ log: LogData
+ onClose: () => void
+}
+
+/**
+ * Log selection display
+ */
+const LogSelection: FC<Props> = ({ log, onClose }) => {
+ return (
+ <div
+ className={[
+ 'h-full flex flex-col flex-grow border border-l-0',
+ 'border-panel-border-light dark:border-panel-border-dark',
+ ].join(' ')}
+ >
+ <div
+ className={[
+ 'bg-panel-header-light dark:bg-panel-header-dark',
+ 'border-b border-panel-border-interior-light',
+ 'dark:border-panel-border-interior-dark',
+ ].join(' ')}
+ >
+ <div className="px-6 py-4 flex items-center">
+ <div className="flex flex-row justify-between items-center w-full">
+ <Typography.Title level={5}>{dayjs(log.timestamp / 1000).toString()}</Typography.Title>
+ <div className="cursor-pointer" onClick={onClose}>
+ <IconX size={14} />
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="flex-grow overflow-y-auto bg-panel-body-light dark:bg-panel-body-dark">
+ <div className="p-4 flex-col space-y-4">
+ <div className="space-y-2">
+ <Typography.Text small>Event message</Typography.Text>
+ <Typography.Text code className="block w-full overflow-x-auto" small>
+ {log.event_message}{' '}
+ </Typography.Text>
+ </div>
+ <div className="space-y-2">
+ <Typography.Text small>Metadata</Typography.Text>
+ <Input.TextArea
+ className="font-mono mt-4"
+ size="tiny"
+ rows={25}
+ disabled
+ value={JSON.stringify(log.metadata, null, 2)}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default LogSelection
diff --git a/studio/components/interfaces/Settings/Logs/LogTable.tsx b/studio/components/interfaces/Settings/Logs/LogTable.tsx
new file mode 100644
index 00000000000..fb02efb0c98
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/LogTable.tsx
@@ -0,0 +1,90 @@
+import dayjs from 'dayjs'
+import { useEffect, useState } from 'react'
+import { Typography } from '@supabase/ui'
+import DataGrid from '@supabase/react-data-grid'
+
+import LogSelection from './LogSelection'
+import { LogData } from './Logs.types'
+
+interface Props {
+ isCustomQuery: boolean
+ data?: LogData[]
+}
+
+/**
+ * Logs table view with focus side panel
+ */
+const LogTable = ({ isCustomQuery, data }: Props) => {
+ const [focusedLog, setFocusedLog] = useState<LogData | null>(null)
+ const columns = ['timestamp', 'event_message'].map((v) => ({
+ key: v,
+ name: v,
+ width: v === 'timestamp' ? 210 : undefined,
+ resizable: true,
+ headerRenderer: () => {
+ return <div className="flex items-center text-xs font-mono h-full">{v}</div>
+ },
+ formatter: ({ row }: any) => {
+ let value = row[v]
+ if (v === 'timestamp') {
+ value = dayjs(Number(row['timestamp']) / 1000).toISOString()
+ }
+ return (
+ <p
+ className={[
+ 'block whitespace-wrap font-mono',
+ `${row.id === focusedLog?.id ? 'font-bold' : ''}`,
+ `${v === 'timestamp' ? 'text-green-500' : ''}`,
+ ].join(' ')}
+ >
+ {value}
+ </p>
+ )
+ },
+ }))
+
+ const logMap = (data || []).reduce((acc: any, d) => {
+ acc[d.id] = d
+ return acc
+ }, {})
+
+ useEffect(() => {
+ if (!data) return
+ if (focusedLog && !(focusedLog.id in logMap)) {
+ setFocusedLog(null)
+ }
+ }, [Object.keys(logMap)])
+
+ if (!data) return null
+
+ // [Joshen] Hmm quite hacky now, but will do
+ const maxHeight = isCustomQuery ? 'calc(100vh - 42px - 10rem)' : 'calc(100vh - 42px - 3rem)'
+
+ return (
+ <section className="flex flex-1 flex-row" style={{ maxHeight }}>
+ <DataGrid
+ style={{ height: '100%' }}
+ className="flex-grow flex-1"
+ onSelectedCellChange={({ idx, rowIdx }) => setFocusedLog(data[rowIdx])}
+ noRowsFallback={
+ <div className="p-4">
+ <Typography.Text type="secondary" small className="font-mono">
+ No data returned from query
+ </Typography.Text>
+ </div>
+ }
+ columns={columns as any}
+ rowClass={(r) => `${r.id === focusedLog?.id ? 'bg-green-800' : 'cursor-pointer'}`}
+ rows={data}
+ rowKeyGetter={(r) => r.id}
+ onRowClick={(r) => setFocusedLog(logMap[r.id])}
+ />
+ {focusedLog && (
+ <div className="w-2/5 flex flex-col">
+ <LogSelection onClose={() => setFocusedLog(null)} log={focusedLog} />
+ </div>
+ )}
+ </section>
+ )
+}
+export default LogTable
diff --git a/studio/components/interfaces/Settings/Logs/Logs.constants.ts b/studio/components/interfaces/Settings/Logs/Logs.constants.ts
new file mode 100644
index 00000000000..c81dd48fff1
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/Logs.constants.ts
@@ -0,0 +1,11 @@
+import { LogTemplate } from '.'
+
+export const TEMPLATES: LogTemplate[] = [
+ { label: 'Recent Errors', mode: 'simple', searchString: '[Ee]rror|\\s[45][0-9][0-9]\\s' },
+ {
+ label: 'POST or PATCH',
+ mode: 'custom',
+ searchString:
+ "REGEXP_CONTAINS(event_message, 'POST') OR REGEXP_CONTAINS(event_message, 'PATCH') ",
+ },
+]
diff --git a/studio/components/interfaces/Settings/Logs/Logs.types.ts b/studio/components/interfaces/Settings/Logs/Logs.types.ts
new file mode 100644
index 00000000000..ba9021d0bfb
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/Logs.types.ts
@@ -0,0 +1,16 @@
+interface Metadata {
+ [key: string]: string | number | Object | Object[]
+}
+
+export interface LogData {
+ id: string
+ timestamp: number
+ event_message: string
+ metadata: Metadata
+}
+
+export interface LogTemplate {
+ label: string
+ mode: 'custom' | 'simple'
+ searchString: string
+}
diff --git a/studio/components/interfaces/Settings/Logs/index.ts b/studio/components/interfaces/Settings/Logs/index.ts
new file mode 100644
index 00000000000..1f094158c52
--- /dev/null
+++ b/studio/components/interfaces/Settings/Logs/index.ts
@@ -0,0 +1,6 @@
+import LogPanel from './LogPanel'
+import LogTable from './LogTable'
+
+export * from './Logs.types'
+export * from './Logs.constants'
+export { LogPanel, LogTable }
diff --git a/studio/components/layouts/SettingsLayout/SettingsLayout.tsx b/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
index 53a78a920a6..bab5d9ef241 100644
--- a/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
+++ b/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
@@ -10,11 +10,10 @@ import { useRouter } from 'next/router'
interface Props {
title?: string
- className?: string
children: ReactNode
}
-const SettingsLayout: FC<Props> = ({ title, className = '', children }) => {
+const SettingsLayout: FC<Props> = ({ title, children }) => {
const { ui } = useStore()
const projectRef = ui.selectedProject?.ref ?? 'default'
@@ -30,7 +29,7 @@ const SettingsLayout: FC<Props> = ({ title, className = '', children }) => {
product="Settings"
productMenu={<ProductMenu page={pageKey} menu={generateSettingsMenu(projectRef)} />}
>
- <main style={{ maxHeight: '100vh' }} className={'flex-1 overflow-y-auto ' + className}>
+ <main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">
{children}
</main>
</BaseLayout>
diff --git a/studio/components/layouts/SettingsLayout/SettingsMenu.utils.ts b/studio/components/layouts/SettingsLayout/SettingsMenu.utils.ts
index 768b787ab42..2dd092f8010 100644
--- a/studio/components/layouts/SettingsLayout/SettingsMenu.utils.ts
+++ b/studio/components/layouts/SettingsLayout/SettingsMenu.utils.ts
@@ -20,7 +20,7 @@ export const generateSettingsMenu = (ref: string): ProductMenuGroup[] => {
},
{
title: 'Logs',
- items: ['rest', 'realtime', 'auth', 'storage', 'database'].map((type: string) => {
+ items: ['database', 'auth', 'realtime', 'rest', 'storage'].map((type: string) => {
return {
name: LOG_TYPE_LABEL_MAPPING[type],
key: `logs-${type}`,
diff --git a/studio/components/to-be-cleaned/Panel.tsx b/studio/components/to-be-cleaned/Panel.tsx
index fc4d6fd3da9..ba6f1f802a0 100644
--- a/studio/components/to-be-cleaned/Panel.tsx
+++ b/studio/components/to-be-cleaned/Panel.tsx
@@ -22,7 +22,7 @@ function Panel(props: any) {
<div
className={`
border border-panel-border-light dark:border-panel-border-dark
- rounded ${props.noMargin? "" : "mb-8"} ${props.className}`}
+ rounded ${props.noMargin ? '' : 'mb-8'} ${props.className}`}
>
{props.title && (
<div className={headerClasses.join(' ')}>
diff --git a/studio/components/ui/CodeEditor/CodeEditor.tsx b/studio/components/ui/CodeEditor/CodeEditor.tsx
index 4c533606c76..06d1d68a30b 100644
--- a/studio/components/ui/CodeEditor/CodeEditor.tsx
+++ b/studio/components/ui/CodeEditor/CodeEditor.tsx
@@ -1,5 +1,5 @@
import { FC, useEffect, useRef } from 'react'
-import Editor, { useMonaco } from '@monaco-editor/react'
+import Editor from '@monaco-editor/react'
import { timeout } from 'lib/helpers'
import Connecting from '../Loading'
@@ -13,20 +13,17 @@ interface Props {
onInputChange: (value?: string) => void
onInputRun?: (value: string) => void
hideLineNumbers?: boolean
- className?: string
}
const CodeEditor: FC<Props> = ({
id,
language,
defaultValue,
- isReadOnly,
- onInputChange = () => { },
- onInputRun = () => { },
- hideLineNumbers,
- className = ""
+ isReadOnly = false,
+ hideLineNumbers = false,
+ onInputChange = () => {},
+ onInputRun = () => {},
}) => {
- const monaco = useMonaco()
const editorRef = useRef()
useEffect(() => {
@@ -60,7 +57,7 @@ const CodeEditor: FC<Props> = ({
<Editor
path={id}
theme="supabase"
- className={"monaco-editor " + className}
+ className="monaco-editor"
defaultLanguage={language}
defaultValue={defaultValue}
loading={<Connecting />}
@@ -75,7 +72,7 @@ const CodeEditor: FC<Props> = ({
lineNumbers: hideLineNumbers ? 'off' : undefined,
glyphMargin: hideLineNumbers ? false : undefined,
lineNumbersMinChars: hideLineNumbers ? 0 : undefined,
- folding: hideLineNumbers? false : undefined
+ folding: hideLineNumbers ? false : undefined,
}}
onMount={onMount}
onChange={onInputChange}
diff --git a/studio/components/ui/Logs/LogPanel.tsx b/studio/components/ui/Logs/LogPanel.tsx
deleted file mode 100644
index 5a787855f0a..00000000000
--- a/studio/components/ui/Logs/LogPanel.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import React from 'react'
-import { Button, Input, Dropdown, Typography, IconChevronDown } from '@supabase/ui'
-import Panel from 'components/to-be-cleaned/Panel'
-
-interface Props {
- showReset: boolean
- onReset: () => void
- onRefresh?: () => void
- onSearch?: (query: string) => void
- onCustomClick?: () => void
- isLoading: boolean
- children?: JSX.Element
- searchValue?: string
- templates?: {
- label: string
- onClick: () => void
- }[]
-}
-
-/**
- * Logs control panel header + wrapper
- */
-const LogPanel = ({
- onRefresh,
- isLoading,
- searchValue,
- children,
- onSearch,
- onCustomClick,
- showReset,
- onReset,
- templates = [] }: Props) => (
- <Panel
- title={
- <div className="flex items-center justify-between w-full" >
- <div className="flex flex-row gap-x-4">
- <Dropdown
- side="bottom"
- align="start"
- overlay={templates.map(p =>
- <Dropdown.Item key={p.label} onClick={p.onClick}>
- <Typography.Text>{p.label}</Typography.Text>
- </Dropdown.Item>
- )}
- >
- <Button
- iconRight={<IconChevronDown />}
- type="secondary" onClick={() => console.log("templates clicked")}>Templates</Button>
- </Dropdown>
-
- <Button type="secondary" onClick={onCustomClick}>Custom query</Button>
- {showReset && (
- <Button type="dashed" onClick={onReset}>Reset filters</Button>)}
- </div>
- <div className="flex flex-row gap-x-4">
- <Input className="max-w-32" placeholder="Filter" onChange={e => {
- if (onSearch) onSearch(e.target.value)
- }} value={searchValue} />
- <Button
- type="outline"
- loading={isLoading}
- disabled={isLoading ? true : false}
- onClick={onRefresh}
- >
- Refresh
- </Button>
-
- </div>
- </div>
- }
- >
- {children}
- </Panel>
-)
-export default LogPanel
\ No newline at end of file
diff --git a/studio/components/ui/Logs/LogSelection.tsx b/studio/components/ui/Logs/LogSelection.tsx
deleted file mode 100644
index a004510568a..00000000000
--- a/studio/components/ui/Logs/LogSelection.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import React from 'react'
-import { Button, Input, Typography } from '@supabase/ui'
-import Panel from 'components/to-be-cleaned/Panel'
-import { LogData } from "./LogTable"
-import dayjs from 'dayjs'
-
-interface Props {
- log: LogData
- onClose: () => void
-}
-
-/**
- * Log selection display
- */
-const LogSelection = ({ log, onClose }: Props) => (
- <Panel
- title={
- <div className="flex flex-row justify-between items-center w-full">
- <Typography.Title level={5}>{dayjs(log.timestamp / 1000).toString()}</Typography.Title>
- <Button size="tiny" type="secondary" onClick={onClose}>Close</Button>
- </div>
- }
- >
- <div className="p-4 h-full flex-col">
- <Typography.Text code className="block w-full overflow-x-auto" small>{log.event_message} </Typography.Text>
- <Input.TextArea label="Metadata" className="font-mono mt-4" size="tiny" rows={25} disabled value={JSON.stringify(log.metadata, null, 2)} />
- </div>
-
-
- </Panel>
-)
-export default LogSelection
\ No newline at end of file
diff --git a/studio/components/ui/Logs/LogTable.tsx b/studio/components/ui/Logs/LogTable.tsx
deleted file mode 100644
index abd9f08be42..00000000000
--- a/studio/components/ui/Logs/LogTable.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import React, { useEffect, useState } from 'react'
-import { Typography } from '@supabase/ui'
-import dayjs from 'dayjs'
-import LogSelection from './LogSelection'
-import DataGrid from '@supabase/react-data-grid'
-interface Props {
- data: LogData[] | null | undefined
-}
-
-interface Metadata {
- [key: string]: string | number | Object | Object[]
-}
-export interface LogData {
- id: string
- timestamp: number
- event_message: string
- metadata: Metadata
-}
-
-interface Column {
- key: string
- name: string
-}
-
-/**
- * Logs table view with focus side panel
- */
-const LogTable = ({ data }: Props) => {
- const [focusedLog, setFocusedLog] = useState<LogData | null>(null);
- const columns = ["timestamp", "event_message"].map(v => ({
- key: v, name: v,
- width: v === "timestamp" ? 240 : undefined,
- resizable: true,
- headerRenderer: () => {
- return <div className="flex items-center justify-center font-mono h-full">{v}</div>
- },
- formatter: ({ row }: any) => {
- let value = row[v]
- if (v === 'timestamp') {
- value = dayjs(Number(row["timestamp"]) / 1000).toString()
- }
- return <p className={`block whitespace-line-wrap ${row.id === focusedLog?.id ? "font-bold" : ""}`}>{value}</p>
- }
- }))
-
- const logMap = (data || []).reduce((acc: any, d) => {
- acc[d.id] = d
- return acc
- }, {})
- useEffect(() => {
- if (!data) return
- if (focusedLog && !(focusedLog.id in logMap)) {
- setFocusedLog(null)
- }
- }, [Object.keys(logMap)])
-
- if (!data) return null
-
- return (<section className="flex flex-row gap-x-4">
- <DataGrid
- style={{ height: "unset", minHeight: "75vh" }}
- className="flex-grow flex-1"
- onSelectedCellChange={({ idx, rowIdx }) => setFocusedLog(data[rowIdx])}
- noRowsFallback={<Typography.Text className="text-center">No data returned from query</Typography.Text>}
- columns={columns as any}
- rowClass={r => `${r.id === focusedLog?.id ? "bg-green-800" : "cursor-pointer"}`}
- rows={data}
- rowKeyGetter={r => r.id}
- onRowClick={r => setFocusedLog(logMap[r.id])}
- />
- {focusedLog && (
- <div className="w-2/5">
- <LogSelection onClose={() => setFocusedLog(null)} log={focusedLog} />
- </div>
- )}
- </section>
- )
-}
-export default LogTable
\ No newline at end of file
diff --git a/studio/lib/constants/index.ts b/studio/lib/constants/index.ts
index fade7083e76..d14763cbb05 100644
--- a/studio/lib/constants/index.ts
+++ b/studio/lib/constants/index.ts
@@ -89,9 +89,9 @@ export const POLICY_MODAL_VIEWS = {
}
export const LOG_TYPE_LABEL_MAPPING: { [k: string]: string } = {
- rest: 'Edge - PostgREST',
- realtime: 'Edge - Realtime',
- auth: 'Edge - Auth',
- storage: 'Edge - Storage',
+ rest: 'PostgREST',
+ realtime: 'Realtime',
+ auth: 'Auth',
+ storage: 'Storage',
database: 'Database',
}
diff --git a/studio/pages/project/[ref]/settings/logs/[type].tsx b/studio/pages/project/[ref]/settings/logs/[type].tsx
index 77291c44a15..8f35603c383 100644
--- a/studio/pages/project/[ref]/settings/logs/[type].tsx
+++ b/studio/pages/project/[ref]/settings/logs/[type].tsx
@@ -1,22 +1,39 @@
-import React, { useEffect, useRef, useState } from 'react'
-import { SettingsLayout } from 'components/layouts/'
+import useSWR from 'swr'
+import debounce from 'lodash/debounce'
+import { useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/router'
-import LogPanel from 'components/ui/Logs/LogPanel'
-import { LOG_TYPE_LABEL_MAPPING } from 'lib/constants'
import { observer } from 'mobx-react-lite'
+import { Typography, Loading, IconLoader, IconAlertCircle } from '@supabase/ui'
+
import { withAuth } from 'hooks'
import { get } from 'lib/common/fetch'
-import LogTable, { LogData } from 'components/ui/Logs/LogTable'
-import useSWR from 'swr'
-import { API_URL } from 'lib/constants'
-import { Typography, Button } from '@supabase/ui'
-import debounce from 'lodash/debounce'
+import { API_URL, LOG_TYPE_LABEL_MAPPING } from 'lib/constants'
+import { SettingsLayout } from 'components/layouts/'
import CodeEditor from 'components/ui/CodeEditor'
-import { ButtonProps } from '@supabase/ui/dist/cjs/components/Button/Button'
+import {
+ LogPanel,
+ LogTable,
+ LogData,
+ TEMPLATES,
+ LogTemplate,
+} from 'components/interfaces/Settings/Logs'
+import { uuidv4 } from 'lib/helpers'
interface CountData {
count: number
}
+
+interface Count {
+ data: [CountData] | []
+ error?: any
+}
+
+interface Logs {
+ data: LogData[]
+ count: number
+ error: any
+}
+
/**
* Acts as a container component for the entire log display
*/
@@ -24,113 +41,112 @@ export const LogPage = () => {
const router = useRouter()
const { ref, type } = router.query
+ const [editorId, setEditorId] = useState<string>(uuidv4())
const [search, setSearch] = useState<string>('')
const [queryParams, setQueryParams] = useState<string>('')
const [where, setWhere] = useState<string>('')
const [mode, setMode] = useState<'simple' | 'custom'>('simple')
const [latestRefresh, setLatestRefresh] = useState<string>(new Date().toISOString())
- const title = LOG_TYPE_LABEL_MAPPING[type as string]
-
- // handle log fetching
- const {
- data,
- isValidating: isLoading,
- mutate,
- } = useSWR<{ data: LogData[]; count: number; error: any }>(
- `${API_URL}/projects/${ref}/logs?${queryParams}`,
- get,
- {
- revalidateOnFocus: false,
- }
- )
-
+ const title = `Logs - ${LOG_TYPE_LABEL_MAPPING[type as string]}`
const debouncedQueryParams = useRef(debounce(setQueryParams, 600)).current
useEffect(() => {
const params = {
type: type as string,
search_query: search || '',
- where: where || '',
+ where: mode === 'custom' ? where || '' : '',
}
const qs = new URLSearchParams(params).toString()
debouncedQueryParams(qs)
return () => debouncedQueryParams.cancel()
- }, [search, where, type])
+ }, [mode, search, where, type])
- const countKey = `${API_URL}/projects/${ref}/logs?${queryParams}&count=true&period_start=${latestRefresh}`
- const { data: countData } = useSWR<{ data: [CountData] | []; error?: any }>(countKey, get, {
- refreshInterval: 5000,
- })
- const newCount = countData?.data?.[0]?.count ?? 0
+ // handle log fetching
+ const logUrl = `${API_URL}/projects/${ref}/logs?${queryParams}`
+ const { data, isValidating, mutate } = useSWR<Logs>(logUrl, get, { revalidateOnFocus: false })
const { data: logData, error } = data || {}
+ const countUrl = `${API_URL}/projects/${ref}/logs?${queryParams}&count=true&period_start=${latestRefresh}`
+ const { data: countData } = useSWR<Count>(countUrl, get, { refreshInterval: 5000 })
+ const newCount = countData?.data?.[0]?.count ?? 0
+
+ const handleReset = () => {
+ setWhere('')
+ setSearch('')
+ setEditorId(uuidv4())
+ }
+
const handleRefresh = () => {
setLatestRefresh(new Date().toISOString())
mutate()
}
+
const handleModeToggle = () => {
- if (mode === 'simple') {
- setMode('custom')
- setSearch('')
+ setMode(mode === 'simple' ? 'custom' : 'simple')
+ }
+
+ const onSelectTemplate = (template: LogTemplate) => {
+ setMode(template.mode)
+ if (template.mode === 'simple') {
+ setSearch(template.searchString)
+ setWhere('')
} else {
- setMode('simple')
+ setWhere(template.searchString)
+ setSearch('')
+ setEditorId(uuidv4())
}
}
+
return (
- <SettingsLayout title={title} className="p-4 space-y-4">
- <LogPanel
- showReset={where || search ? true : false}
- onReset={() => {
- setWhere('')
- setSearch('')
- setMode('simple') // this is necessary to reset the value of the monaco editor
- }}
- templates={[
- { label: 'Recent Errors', onClick: () => setSearch('[Ee]rror|\\s[45][0-9][0-9]\\s') },
- {
- label: 'POST or PATCH',
- onClick: () => {
- setSearch('')
- setMode('custom')
- setWhere(
- "REGEXP_CONTAINS(event_message, 'POST') OR REGEXP_CONTAINS(event_message, 'PATCH') "
- )
- },
- },
- ]}
- searchValue={search}
- onCustomClick={handleModeToggle}
- isLoading={isLoading}
- onRefresh={handleRefresh}
- onSearch={setSearch}
- />
- {mode === 'custom' && (
- <div>
- <CodeEditor
- className="p-4 h-24"
- hideLineNumbers
- id={'logs-where-editor'}
- language="pgsql"
- defaultValue={where}
- onInputChange={(v) => setWhere(v || '')}
- onInputRun={handleRefresh}
- />
+ <SettingsLayout title={title}>
+ <div className="h-full flex flex-col flex-grow">
+ <LogPanel
+ isCustomQuery={mode === 'custom'}
+ isLoading={isValidating}
+ hasNewData={newCount > 0}
+ showReset={search.length > 0}
+ searchValue={search}
+ templates={TEMPLATES}
+ onReset={handleReset}
+ onRefresh={handleRefresh}
+ onSearch={setSearch}
+ onCustomClick={handleModeToggle}
+ onSelectTemplate={onSelectTemplate}
+ />
+ {mode === 'custom' && (
+ <div className="min-h-[7rem] h-28">
+ <CodeEditor
+ id={editorId}
+ language="pgsql"
+ defaultValue={where}
+ onInputChange={(v) => setWhere(v || '')}
+ onInputRun={handleRefresh}
+ />
+ </div>
+ )}
+ <div className="flex flex-col flex-grow relative">
+ {isValidating && (
+ <div
+ className={[
+ 'absolute top-0 w-full h-full bg-gray-800 flex items-center justify-center',
+ `${isValidating ? 'bg-opacity-75 z-50' : ''}`,
+ ].join(' ')}
+ >
+ <IconLoader className="animate-spin" />
+ </div>
+ )}
+ {error && (
+ <div className="flex w-full h-full justify-center items-center space-x-2 mx-auto">
+ <IconAlertCircle size={16} />
+ <Typography.Text type="secondary">Sorry! Could not fetch data</Typography.Text>
+ </div>
+ )}
+ <LogTable data={logData} isCustomQuery={mode === 'custom'} />
</div>
- )}
- {error && (
- <Typography.Text className="text-center w-full block">Could not fetch data</Typography.Text>
- )}
- {newCount > 0 && <LoadNewLogsButton onClick={handleRefresh} />}
- <LogTable data={logData} />
+ </div>
</SettingsLayout>
)
}
-const LoadNewLogsButton = (props: ButtonProps) => (
- <Button type="dashed" block {...props}>
- Load new logs
- </Button>
-)
-
export default withAuth(observer(LogPage))