StructuredLogViewer.vue 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. <script setup lang="ts">
  2. import type { SorterResult, TablePaginationConfig } from 'ant-design-vue/es/table/interface'
  3. import type { AccessLogEntry, AdvancedSearchRequest, PreflightResponse } from '@/api/nginx_log'
  4. import { DownOutlined, ExclamationCircleOutlined, LoadingOutlined, ReloadOutlined } from '@ant-design/icons-vue'
  5. import { message, Tag } from 'ant-design-vue'
  6. import dayjs from 'dayjs'
  7. import nginx_log from '@/api/nginx_log'
  8. import { useWebSocketEventBus } from '@/composables/useWebSocketEventBus'
  9. import { bytesToSize } from '@/lib/helper'
  10. import SearchFilters from './components/SearchFilters.vue'
  11. interface Props {
  12. logPath?: string
  13. }
  14. interface SearchSummary {
  15. pv?: number
  16. uv?: number
  17. total_traffic?: number
  18. unique_pages?: number
  19. avg_traffic_per_pv?: number
  20. }
  21. const props = defineProps<Props>()
  22. // Route and router
  23. const route = useRoute()
  24. // WebSocket event bus for index ready notifications
  25. const { subscribe: subscribeToEvent } = useWebSocketEventBus()
  26. // Use provided log path or let backend determine default
  27. const logPath = computed(() => props.logPath || undefined)
  28. // Check if this is an error log (error logs don't support structured processing)
  29. const isErrorLog = computed(() => {
  30. if (props.logPath) {
  31. return props.logPath.includes('error.log') || props.logPath.includes('error_log')
  32. }
  33. // Check route path
  34. return route.path.includes('error')
  35. })
  36. // Reactive data - Only advanced search mode now
  37. const timeRange = ref({
  38. start: null as dayjs.Dayjs | null, // Will be set from server time range
  39. end: null as dayjs.Dayjs | null, // Will be set from server time range
  40. })
  41. const preflightResponse = ref<PreflightResponse | null>(null)
  42. const searchFilters = ref({
  43. query: '',
  44. ip: '',
  45. method: '',
  46. status: [] as string[],
  47. path: '',
  48. user_agent: '',
  49. referer: '',
  50. browser: [] as string[],
  51. os: [] as string[],
  52. device: [] as string[],
  53. })
  54. const searchResults = ref<AccessLogEntry[]>([])
  55. const searchTotal = ref(0)
  56. const searchLoading = ref(false)
  57. const indexingStatus = ref<'idle' | 'indexing' | 'ready' | 'failed'>('idle')
  58. const currentPage = ref(1)
  59. const pageSize = ref(50)
  60. const sortBy = ref('timestamp')
  61. const sortOrder = ref<'asc' | 'desc'>('desc')
  62. // Cache for failed path validations to prevent repeated calls
  63. const pathValidationCache = ref<Map<string, boolean>>(new Map())
  64. // Removed showAdvancedFilters - filters are always shown now
  65. // Date range for ARangePicker
  66. const dateRange = computed({
  67. get: () => {
  68. const start = timeRange.value.start
  69. const end = timeRange.value.end
  70. // Return undefined if either value is null/undefined, otherwise return the tuple
  71. return (start && end) ? [start, end] as [typeof start, typeof end] : undefined
  72. },
  73. set: value => {
  74. if (value && Array.isArray(value) && value.length === 2) {
  75. timeRange.value.start = value[0]
  76. timeRange.value.end = value[1]
  77. }
  78. },
  79. })
  80. const filteredEntries = computed(() => {
  81. // Since we removed the simple filter, just return search results directly
  82. return searchResults.value
  83. })
  84. // Summary stats from search response
  85. const searchSummary = ref<SearchSummary | null>(null)
  86. // Computed properties for indexing status
  87. const isLoading = computed(() => searchLoading.value)
  88. const isIndexing = computed(() => indexingStatus.value === 'indexing')
  89. const isReady = computed(() => indexingStatus.value === 'ready')
  90. const isFailed = computed(() => indexingStatus.value === 'failed')
  91. // Combined status computed properties
  92. const shouldShowContent = computed(() => !isFailed.value)
  93. const shouldShowControls = computed(() => isReady.value)
  94. const shouldShowIndexingSpinner = computed(() => isIndexing.value)
  95. const shouldShowResults = computed(() => isReady.value && searchSummary.value !== null)
  96. // Status code color mapping
  97. function getStatusColor(status: number): string {
  98. if (status >= 200 && status < 300)
  99. return 'success'
  100. if (status >= 300 && status < 400)
  101. return 'processing'
  102. if (status >= 400 && status < 500)
  103. return 'warning'
  104. if (status >= 500)
  105. return 'error'
  106. return 'default'
  107. }
  108. // Device type color mapping
  109. function getDeviceColor(deviceType: string): string {
  110. const colors: Record<string, string> = {
  111. 'Desktop': 'blue',
  112. 'Mobile': 'green',
  113. 'Tablet': 'orange',
  114. 'Bot': 'red',
  115. 'TV': 'purple',
  116. 'Smart Speaker': 'cyan',
  117. 'Game Console': 'magenta',
  118. 'Wearable': 'gold',
  119. }
  120. return colors[deviceType] || 'default'
  121. }
  122. // Get sort order for column
  123. function getSortOrder(fieldName: string): 'ascend' | 'descend' | undefined {
  124. if (sortBy.value === fieldName) {
  125. return sortOrder.value === 'asc' ? 'ascend' : 'descend'
  126. }
  127. return undefined
  128. }
  129. // Table columns configuration
  130. const structuredLogColumns = computed(() => [
  131. {
  132. title: $gettext('Time'),
  133. dataIndex: 'timestamp',
  134. width: 140,
  135. fixed: 'left' as const,
  136. sorter: true,
  137. sortOrder: getSortOrder('timestamp'),
  138. customRender: ({ record }: { record: AccessLogEntry }) => h('span', dayjs.unix(record.timestamp).format('YYYY-MM-DD HH:mm:ss')),
  139. },
  140. {
  141. title: $gettext('IP'),
  142. dataIndex: 'ip',
  143. width: 350,
  144. sorter: true,
  145. sortOrder: getSortOrder('ip'),
  146. customRender: ({ record }: { record: AccessLogEntry }) => {
  147. const locationParts: string[] = []
  148. if (record.region_code) {
  149. locationParts.push(record.region_code)
  150. }
  151. if (record.province) {
  152. locationParts.push(record.province)
  153. }
  154. if (record.city) {
  155. locationParts.push(record.city)
  156. }
  157. return h('div', { class: 'flex items-center gap-2' }, [
  158. locationParts.length > 0 ? h(Tag, { color: 'blue', size: 'small' }, { default: () => locationParts.join(' · ') }) : null,
  159. h('span', record.ip),
  160. ])
  161. },
  162. },
  163. {
  164. title: $gettext('Request'),
  165. dataIndex: 'path',
  166. ellipsis: {
  167. showTitle: true,
  168. },
  169. width: 350,
  170. customRender: ({ record }: { record: AccessLogEntry }) => {
  171. let methodColor = 'default'
  172. if (record.method === 'GET')
  173. methodColor = 'green'
  174. else if (record.method === 'POST')
  175. methodColor = 'blue'
  176. return h('div', [
  177. h(Tag, {
  178. color: methodColor,
  179. size: 'small',
  180. }, { default: () => record.method }),
  181. h('span', { class: 'ml-1' }, record.path),
  182. ])
  183. },
  184. },
  185. {
  186. title: $gettext('Status'),
  187. dataIndex: 'status',
  188. width: 80,
  189. sorter: true,
  190. sortOrder: getSortOrder('status'),
  191. customRender: ({ record }: { record: AccessLogEntry }) => h(Tag, { color: getStatusColor(record.status) }, { default: () => record.status }),
  192. },
  193. {
  194. title: $gettext('Size'),
  195. dataIndex: 'bytes_sent',
  196. width: 80,
  197. sorter: true,
  198. sortOrder: getSortOrder('bytes_sent'),
  199. customRender: ({ record }: { record: AccessLogEntry }) => h('span', bytesToSize(record.bytes_sent)),
  200. },
  201. {
  202. title: $gettext('Browser'),
  203. dataIndex: 'browser',
  204. width: 120,
  205. sorter: true,
  206. sortOrder: getSortOrder('browser'),
  207. customRender: ({ record }: { record: AccessLogEntry }) => {
  208. if (record.browser && record.browser !== 'Unknown') {
  209. const browserText = record.browser_version
  210. ? `${record.browser} ${record.browser_version}`
  211. : record.browser
  212. return h('div', browserText)
  213. }
  214. return null
  215. },
  216. },
  217. {
  218. title: $gettext('OS'),
  219. dataIndex: 'os',
  220. width: 120,
  221. sorter: true,
  222. sortOrder: getSortOrder('os'),
  223. customRender: ({ record }: { record: AccessLogEntry }) => {
  224. if (record.os && record.os !== 'Unknown') {
  225. const osText = record.os_version
  226. ? `${record.os} ${record.os_version}`
  227. : record.os
  228. return h('div', osText)
  229. }
  230. return null
  231. },
  232. },
  233. {
  234. title: $gettext('Device'),
  235. dataIndex: 'device_type',
  236. width: 90,
  237. sorter: true,
  238. sortOrder: getSortOrder('device_type'),
  239. customRender: ({ record }: { record: AccessLogEntry }) => record.device_type
  240. ? h(Tag, { color: getDeviceColor(record.device_type), size: 'small' }, { default: () => record.device_type })
  241. : null,
  242. },
  243. {
  244. title: $gettext('Referer'),
  245. dataIndex: 'referer',
  246. ellipsis: true,
  247. width: 200,
  248. customRender: ({ record }: { record: AccessLogEntry }) => record.referer && record.referer !== '-'
  249. ? h('span', record.referer)
  250. : null,
  251. },
  252. ])
  253. // Time range presets (Grafana-style)
  254. const timePresets = [
  255. { label: () => $gettext('Last 15 minutes'), value: () => ({ start: dayjs().subtract(15, 'minute'), end: dayjs() }) },
  256. { label: () => $gettext('Last 30 minutes'), value: () => ({ start: dayjs().subtract(30, 'minute'), end: dayjs() }) },
  257. { label: () => $gettext('Last hour'), value: () => ({ start: dayjs().subtract(1, 'hour'), end: dayjs() }) },
  258. { label: () => $gettext('Last 4 hours'), value: () => ({ start: dayjs().subtract(4, 'hour'), end: dayjs() }) },
  259. { label: () => $gettext('Last 12 hours'), value: () => ({ start: dayjs().subtract(12, 'hour'), end: dayjs() }) },
  260. { label: () => $gettext('Last 24 hours'), value: () => ({ start: dayjs().subtract(24, 'hour'), end: dayjs() }) },
  261. { label: () => $gettext('Last 7 days'), value: () => ({ start: dayjs().subtract(7, 'day'), end: dayjs() }) },
  262. { label: () => $gettext('Last 30 days'), value: () => ({ start: dayjs().subtract(30, 'day'), end: dayjs() }) },
  263. ]
  264. // Load structured logs function - now only uses advanced search
  265. async function loadLogs() {
  266. await performAdvancedSearch()
  267. }
  268. // Advanced search function
  269. async function performAdvancedSearch() {
  270. // Don't search if time range is not set yet
  271. if (!timeRange.value.start || !timeRange.value.end) {
  272. return
  273. }
  274. searchLoading.value = true
  275. try {
  276. const searchRequest: AdvancedSearchRequest = {
  277. start_time: timeRange.value.start.unix(),
  278. end_time: timeRange.value.end.unix(),
  279. query: searchFilters.value.query || undefined,
  280. ip: searchFilters.value.ip || undefined,
  281. method: searchFilters.value.method || undefined,
  282. status: searchFilters.value.status.length > 0 ? searchFilters.value.status.map(s => Number.parseInt(s)).filter(n => !Number.isNaN(n)) : undefined,
  283. path: searchFilters.value.path || undefined,
  284. user_agent: searchFilters.value.user_agent || undefined,
  285. referer: searchFilters.value.referer || undefined,
  286. browser: searchFilters.value.browser.length > 0 ? searchFilters.value.browser.join(',') : undefined,
  287. os: searchFilters.value.os.length > 0 ? searchFilters.value.os.join(',') : undefined,
  288. device: searchFilters.value.device.length > 0 ? searchFilters.value.device.join(',') : undefined,
  289. limit: pageSize.value,
  290. offset: (currentPage.value - 1) * pageSize.value,
  291. sort_by: sortBy.value,
  292. sort_order: sortOrder.value,
  293. log_path: logPath.value,
  294. }
  295. const result = await nginx_log.search(searchRequest)
  296. searchResults.value = result.entries || []
  297. searchTotal.value = result.total || 0
  298. searchSummary.value = result.summary || null
  299. }
  300. catch (error: unknown) {
  301. // Check if this is a path validation error - don't show message for these
  302. if (isPathValidationError(error)) {
  303. // Silently reset results for path validation errors
  304. searchResults.value = []
  305. searchTotal.value = 0
  306. return
  307. }
  308. // Reset results on error
  309. searchResults.value = []
  310. searchTotal.value = 0
  311. searchSummary.value = null
  312. }
  313. finally {
  314. searchLoading.value = false
  315. }
  316. }
  317. // Load preflight information (single request, no retries)
  318. async function loadPreflight(): Promise<boolean> {
  319. // Check cache for known invalid paths
  320. const currentPath = logPath.value || ''
  321. if (pathValidationCache.value.has(currentPath) && !pathValidationCache.value.get(currentPath)) {
  322. throw new Error('Path validation failed (cached)')
  323. }
  324. try {
  325. preflightResponse.value = await nginx_log.getPreflight(logPath.value)
  326. if (preflightResponse.value.available) {
  327. // Cache this path as valid and set time range
  328. pathValidationCache.value.set(currentPath, true)
  329. timeRange.value.start = dayjs.unix(preflightResponse.value.start_time)
  330. timeRange.value.end = dayjs.unix(preflightResponse.value.end_time)
  331. return true // Index is ready
  332. }
  333. else {
  334. // Index is not ready, will wait for event notification
  335. // Don't show message here - let the UI status handle it
  336. // Use default range temporarily
  337. timeRange.value.start = dayjs().subtract(7, 'day')
  338. timeRange.value.end = dayjs()
  339. return false // Index not ready
  340. }
  341. }
  342. catch (error: unknown) {
  343. // Check if this is a path validation error by error code
  344. if (isPathValidationError(error)) {
  345. // Cache this path as invalid to prevent future calls
  346. pathValidationCache.value.set(currentPath, false)
  347. throw error // Immediately fail for path validation errors
  348. }
  349. // For other errors, set fallback range but don't show error message here
  350. // The error will be handled by the caller
  351. timeRange.value.start = dayjs().subtract(7, 'day')
  352. timeRange.value.end = dayjs()
  353. throw error // Let the caller handle the error message
  354. }
  355. }
  356. // Apply time preset
  357. function applyTimePreset(preset: { value: () => { start: dayjs.Dayjs, end: dayjs.Dayjs } }) {
  358. const range = preset.value()
  359. timeRange.value = range
  360. loadLogs()
  361. }
  362. // Reset search filters
  363. function resetSearchFilters() {
  364. searchFilters.value = {
  365. query: '',
  366. ip: '',
  367. method: '',
  368. status: [],
  369. path: '',
  370. user_agent: '',
  371. referer: '',
  372. browser: [],
  373. os: [],
  374. device: [],
  375. }
  376. currentPage.value = 1
  377. performAdvancedSearch()
  378. }
  379. // Note: handleSortingChange function removed - sorting is now handled directly in handleTableChange
  380. // Handle table sorting and pagination change
  381. function handleTableChange(
  382. pagination: TablePaginationConfig,
  383. filters: Record<string, unknown>,
  384. sorter: SorterResult<AccessLogEntry> | SorterResult<AccessLogEntry>[],
  385. ) {
  386. let shouldResetPage = false
  387. // Update page size first
  388. if (pagination.pageSize !== undefined && pagination.pageSize !== pageSize.value) {
  389. pageSize.value = pagination.pageSize
  390. shouldResetPage = true // Reset to first page when page size changes
  391. }
  392. // Handle sorting changes
  393. const singleSorter = Array.isArray(sorter) ? sorter[0] : sorter
  394. if (singleSorter?.field && singleSorter?.order) {
  395. const newSortBy = mapColumnToSortField(String(singleSorter.field))
  396. const newSortOrder = singleSorter.order === 'ascend' ? 'asc' : 'desc'
  397. // Check if sorting actually changed
  398. if (newSortBy !== sortBy.value || newSortOrder !== sortOrder.value) {
  399. sortBy.value = newSortBy
  400. sortOrder.value = newSortOrder
  401. shouldResetPage = true // Reset to first page when sorting changes
  402. }
  403. }
  404. // Update pagination (do this after handling sort/pageSize)
  405. if (shouldResetPage) {
  406. currentPage.value = 1
  407. }
  408. else if (pagination.current !== undefined) {
  409. currentPage.value = pagination.current
  410. }
  411. nextTick(() => {
  412. performAdvancedSearch()
  413. })
  414. }
  415. // Map table column names to backend sort fields
  416. function mapColumnToSortField(column: string): string {
  417. const mapping: Record<string, string> = {
  418. timestamp: 'timestamp',
  419. ip: 'ip',
  420. method: 'method',
  421. path: 'path',
  422. status: 'status',
  423. bytes_sent: 'bytes_sent',
  424. browser: 'browser',
  425. os: 'os',
  426. device_type: 'device_type',
  427. }
  428. return mapping[column] || 'timestamp'
  429. }
  430. // Get display name for sort field
  431. function getSortDisplayName(field: string): string {
  432. const displayNames: Record<string, string> = {
  433. timestamp: $gettext('Time'),
  434. ip: $gettext('IP Address'),
  435. method: $gettext('Method'),
  436. path: $gettext('Path'),
  437. status: $gettext('Status'),
  438. bytes_sent: $gettext('Size'),
  439. browser: $gettext('Browser'),
  440. os: $gettext('OS'),
  441. device_type: $gettext('Device'),
  442. }
  443. return displayNames[field] || field
  444. }
  445. // Reset sorting to default
  446. function resetSorting() {
  447. sortBy.value = 'timestamp'
  448. sortOrder.value = 'desc'
  449. currentPage.value = 1
  450. performAdvancedSearch()
  451. }
  452. // Refresh data - reload preflight and search results
  453. async function refreshData() {
  454. if (isErrorLog.value || isFailed.value) {
  455. return
  456. }
  457. try {
  458. indexingStatus.value = 'indexing'
  459. // Clear cache for current path to force fresh data
  460. const currentPath = logPath.value || ''
  461. pathValidationCache.value.delete(currentPath)
  462. // Reload preflight data
  463. const hasIndexedData = await loadPreflight()
  464. indexingStatus.value = 'ready'
  465. // Reload search results if we have valid data
  466. if (hasIndexedData && timeRange.value.start && timeRange.value.end) {
  467. await performAdvancedSearch()
  468. message.success($gettext('Data refreshed successfully'))
  469. }
  470. }
  471. catch {
  472. indexingStatus.value = 'failed'
  473. message.error($gettext('Failed to refresh data'))
  474. }
  475. }
  476. // Helper function to check if error is a path validation error
  477. function isPathValidationError(error: unknown): boolean {
  478. if (!(error instanceof Error)) {
  479. return false
  480. }
  481. try {
  482. // Check if error response contains path validation error codes
  483. const errorData = JSON.parse(error.message)
  484. if (errorData.scope === 'nginx_log' && errorData.code) {
  485. const code = Number.parseInt(errorData.code)
  486. // Path validation error codes: 50013, 50014, 50015
  487. return code === 50013 || code === 50014 || code === 50015
  488. }
  489. }
  490. catch {
  491. // Ignore parsing errors
  492. }
  493. return false
  494. }
  495. // Handle initialization with indexed data and search
  496. async function handleInitializedData(hasIndexedData: boolean) {
  497. if (timeRange.value.start && timeRange.value.end) {
  498. await performAdvancedSearch()
  499. // Only show messages for specific scenarios
  500. if (searchResults.value.length === 0 && hasIndexedData) {
  501. message.info($gettext('No logs found in the selected time range.'))
  502. }
  503. else if (searchResults.value.length > 0 && !hasIndexedData) {
  504. message.info($gettext('Background indexing in progress. Data will be updated automatically when ready.'))
  505. }
  506. }
  507. }
  508. // Handle index ready notification from WebSocket
  509. async function handleIndexReadyNotification(data: {
  510. log_path: string
  511. start_time: string
  512. end_time: string
  513. available: boolean
  514. index_status: string
  515. }) {
  516. const currentPath = logPath.value || ''
  517. // Check if the notification is for the current log path
  518. if (data.log_path === currentPath || (!currentPath && data.log_path)) {
  519. message.success($gettext('Log indexing completed! Loading updated data...'))
  520. try {
  521. // Re-request preflight to get the latest information
  522. const hasIndexedData = await loadPreflight()
  523. if (hasIndexedData) {
  524. indexingStatus.value = 'ready'
  525. // Load initial data with the updated time range
  526. await performAdvancedSearch()
  527. }
  528. }
  529. catch (error) {
  530. console.error('Failed to reload preflight after indexing completion:', error)
  531. indexingStatus.value = 'failed'
  532. }
  533. }
  534. }
  535. // Initialize on mount
  536. onMounted(async () => {
  537. // Skip initialization for error logs
  538. if (isErrorLog.value) {
  539. return
  540. }
  541. // Subscribe to index ready notifications
  542. subscribeToEvent('nginx_log_index_ready', handleIndexReadyNotification)
  543. indexingStatus.value = 'indexing'
  544. try {
  545. const hasIndexedData = await loadPreflight()
  546. if (hasIndexedData) {
  547. // Index is ready and data is available
  548. indexingStatus.value = 'ready'
  549. await handleInitializedData(hasIndexedData)
  550. }
  551. // Index is not ready yet, keep indexing status and wait for event notification
  552. // indexingStatus remains 'indexing'
  553. }
  554. catch {
  555. indexingStatus.value = 'failed'
  556. // Don't show any error messages - the empty page clearly indicates the issue
  557. }
  558. })
  559. // Watch for log path changes to clear cache and reload
  560. watch(logPath, (newPath, oldPath) => {
  561. // Clear cache when path changes
  562. if (newPath !== oldPath) {
  563. pathValidationCache.value.clear()
  564. }
  565. if (isReady.value) {
  566. loadLogs()
  567. }
  568. })
  569. // Watch for time range changes (only after initialization)
  570. watch(timeRange, () => {
  571. if (isReady.value) {
  572. loadLogs()
  573. }
  574. }, { deep: true })
  575. // Expose functions for parent component
  576. defineExpose({
  577. loadLogs,
  578. refreshData,
  579. })
  580. </script>
  581. <template>
  582. <div>
  583. <!-- Error Log Notice -->
  584. <div v-if="isErrorLog" class="mb-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded">
  585. <div class="flex items-start">
  586. <div class="flex-shrink-0">
  587. <ExclamationCircleOutlined class="h-5 w-5 text-yellow-400" />
  588. </div>
  589. <div class="ml-3">
  590. <h3 class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
  591. {{ $gettext('Error Log Detected') }}
  592. </h3>
  593. <div class="mt-2 text-sm text-yellow-700 dark:text-yellow-300">
  594. <p>{{ $gettext('Error logs do not support structured analysis as they contain free-form text messages.') }}</p>
  595. <p class="mt-1">
  596. {{ $gettext('For error logs, please use the Raw Log Viewer for better viewing experience.') }}
  597. </p>
  598. </div>
  599. <div class="mt-3">
  600. <AButton size="small" type="primary" @click="$router.push('/nginx_log')">
  601. {{ $gettext('Go to Raw Log Viewer') }}
  602. </AButton>
  603. </div>
  604. </div>
  605. </div>
  606. </div>
  607. <!-- Access Log Content (only show for non-error logs and non-failed preflight) -->
  608. <div v-else-if="shouldShowContent">
  609. <!-- Time Range and Search Controls (only show when ready) -->
  610. <div v-if="shouldShowControls" class="mb-4">
  611. <!-- Time Range Picker -->
  612. <div class="mb-4">
  613. <div class="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300">
  614. {{ $gettext('Time Range') }}
  615. </div>
  616. <ASpace wrap>
  617. <ADropdown placement="bottomLeft">
  618. <template #overlay>
  619. <AMenu @click="({ key }) => applyTimePreset(timePresets[Number(key)])">
  620. <AMenuItem v-for="(preset, index) in timePresets" :key="index">
  621. {{ preset.label() }}
  622. </AMenuItem>
  623. </AMenu>
  624. </template>
  625. <AButton>
  626. {{ $gettext('Quick Select') }}
  627. <DownOutlined />
  628. </AButton>
  629. </ADropdown>
  630. <ARangePicker
  631. v-model:value="dateRange"
  632. show-time
  633. format="YYYY-MM-DD HH:mm:ss"
  634. @change="performAdvancedSearch"
  635. />
  636. <AButton
  637. type="default"
  638. :loading="isIndexing"
  639. @click="refreshData"
  640. >
  641. <template #icon>
  642. <ReloadOutlined />
  643. </template>
  644. </AButton>
  645. </ASpace>
  646. </div>
  647. <!-- Search Filters -->
  648. <SearchFilters
  649. v-model="searchFilters"
  650. class="mb-6"
  651. @search="performAdvancedSearch"
  652. @reset="resetSearchFilters"
  653. />
  654. <!-- Sort Info -->
  655. <div v-if="sortBy !== 'timestamp' || sortOrder !== 'desc'" class="mb-4 p-2 bg-blue-50 dark:bg-blue-900/20 rounded border border-blue-200 dark:border-blue-800">
  656. <span class="text-sm text-blue-600 dark:text-blue-300">
  657. {{ $gettext('Sorted by') }}: <strong>{{ getSortDisplayName(sortBy) }}</strong> ({{ sortOrder === 'asc' ? $gettext('Ascending') : $gettext('Descending') }})
  658. </span>
  659. <AButton size="small" type="text" class="ml-2" @click="resetSorting">
  660. {{ $gettext('Reset') }}
  661. </AButton>
  662. </div>
  663. </div>
  664. <!-- Loading State -->
  665. <div v-if="isLoading" class="text-center" style="padding: 40px;">
  666. <LoadingOutlined class="text-2xl text-blue-500" />
  667. <p style="margin-top: 16px;">
  668. {{ $gettext('Searching logs...') }}
  669. </p>
  670. </div>
  671. <!-- Indexing Status -->
  672. <div v-else-if="shouldShowIndexingSpinner" class="text-center" style="padding: 40px;">
  673. <LoadingOutlined class="text-2xl text-blue-500" />
  674. <p style="margin-top: 16px;">
  675. {{ $gettext('Indexing logs, please wait...') }}
  676. </p>
  677. </div>
  678. <!-- Search Results (show when indexing is ready and we have search results) -->
  679. <div v-else-if="shouldShowResults">
  680. <!-- Summary -->
  681. <div class="mb-4 p-4 bg-gray-50 dark:bg-trueGray-800 rounded">
  682. <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
  683. <div class="text-center">
  684. <AStatistic
  685. :title="$gettext('Total Entries')"
  686. :value="searchTotal"
  687. />
  688. </div>
  689. <div class="text-center">
  690. <AStatistic
  691. :title="$gettext('PV')"
  692. :value="searchSummary?.pv || 0"
  693. />
  694. </div>
  695. <div class="text-center">
  696. <AStatistic
  697. :title="$gettext('UV')"
  698. :value="searchSummary?.uv || 0"
  699. />
  700. </div>
  701. <div class="text-center">
  702. <AStatistic
  703. :title="$gettext('Traffic')"
  704. :value="bytesToSize(searchSummary?.total_traffic || 0)"
  705. />
  706. </div>
  707. <div class="text-center">
  708. <AStatistic
  709. :title="$gettext('Unique Pages')"
  710. :value="searchSummary?.unique_pages || 0"
  711. />
  712. </div>
  713. <div class="text-center">
  714. <AStatistic
  715. :title="$gettext('Avg/PV')"
  716. :value="bytesToSize(Math.round(searchSummary?.avg_traffic_per_pv || 0))"
  717. />
  718. </div>
  719. </div>
  720. </div>
  721. <!-- Log Table (show if we have entries) -->
  722. <div v-if="filteredEntries.length > 0">
  723. <ATable
  724. :data-source="filteredEntries"
  725. :pagination="{
  726. current: currentPage,
  727. pageSize,
  728. total: searchTotal,
  729. showSizeChanger: true,
  730. showQuickJumper: true,
  731. showTotal: (total, range) => $gettext('%{start}-%{end} of %{total} items', {
  732. start: range[0].toLocaleString(),
  733. end: range[1].toLocaleString(),
  734. total: total.toLocaleString(),
  735. }),
  736. }"
  737. size="small"
  738. :scroll="{ x: 2400 }"
  739. :columns="structuredLogColumns"
  740. :loading="isLoading"
  741. @change="handleTableChange"
  742. />
  743. </div>
  744. <!-- Empty State within search results -->
  745. <div v-else class="text-center" style="padding: 40px;">
  746. <AEmpty :description="$gettext('No entries in current page')" />
  747. <p class="text-gray-500 mt-2">
  748. {{ $gettext('Try adjusting your search criteria or navigate to different pages.') }}
  749. </p>
  750. </div>
  751. </div>
  752. <!-- Empty State -->
  753. <div v-else class="text-center" style="padding: 40px;">
  754. <AEmpty :description="$gettext('No structured log data available')" />
  755. <div v-if="isReady" class="mt-4">
  756. <p class="text-gray-500">
  757. {{ $gettext('Try adjusting your search criteria or time range.') }}
  758. </p>
  759. <p v-if="timeRange.start && timeRange.end" class="text-gray-400 text-sm mt-2">
  760. {{ $gettext('Search range') }}: {{ timeRange.start.format('YYYY-MM-DD HH:mm') }} - {{ timeRange.end.format('YYYY-MM-DD HH:mm') }}
  761. <Tag v-if="preflightResponse && preflightResponse.available" color="green" size="small" class="ml-2">
  762. {{ $gettext('From indexed logs') }}
  763. </Tag>
  764. <Tag v-else color="orange" size="small" class="ml-2">
  765. {{ $gettext('Default range') }}
  766. </Tag>
  767. </p>
  768. <AButton type="primary" class="mt-2" @click="resetSearchFilters">
  769. {{ $gettext('Reset Search') }}
  770. </AButton>
  771. </div>
  772. </div>
  773. </div> <!-- End of Access Log Content -->
  774. <!-- Failed State (show empty page when preflight fails) -->
  775. <div v-else class="text-center" style="padding: 80px 40px;">
  776. <AEmpty :description="$gettext('Log file not available')" />
  777. </div>
  778. </div>
  779. </template>