Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d02cc60f94 | ||
|
|
b1b7cb97de |
@@ -1,6 +1,10 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/pkg/response"
|
||||
@@ -13,100 +17,100 @@ func SetupLogRoutes(r *gin.RouterGroup) {
|
||||
logs := r.Group("/logs")
|
||||
{
|
||||
logs.GET("", handleGetLogs)
|
||||
logs.GET("/export", handleExportLogs)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetLogs(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
// logFilter 日志列表与导出共用同一套筛选,避免两边口径漂移
|
||||
type logFilter struct {
|
||||
userID uint
|
||||
appIDs []uint
|
||||
logType string
|
||||
status string
|
||||
applicationID string
|
||||
startDate string
|
||||
endDate string
|
||||
search string
|
||||
}
|
||||
|
||||
func newLogFilter(c *gin.Context) logFilter {
|
||||
userID := c.GetUint("user_id")
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
return logFilter{
|
||||
userID: userID,
|
||||
appIDs: appIDs,
|
||||
logType: c.Query("type"),
|
||||
status: c.Query("status"),
|
||||
applicationID: c.Query("application_id"),
|
||||
startDate: c.Query("start_date"),
|
||||
endDate: c.Query("end_date"),
|
||||
search: c.Query("search"),
|
||||
}
|
||||
}
|
||||
|
||||
page, pageSize := parsePageParams(c)
|
||||
logType := c.Query("type")
|
||||
status := c.Query("status")
|
||||
applicationID := c.Query("application_id")
|
||||
startDate := c.Query("start_date")
|
||||
endDate := c.Query("end_date")
|
||||
search := c.Query("search")
|
||||
|
||||
var logs []model.Log
|
||||
var total int64
|
||||
|
||||
query := database.DB.Model(&model.Log{})
|
||||
|
||||
if len(appIDs) > 0 {
|
||||
query = query.Where("application_id IN ? OR user_id = ?", appIDs, userID)
|
||||
func (f logFilter) query() *gorm.DB {
|
||||
// 可见范围:自己应用下产生的 + 自己这个账号产生的
|
||||
q := database.DB.Model(&model.Log{})
|
||||
if len(f.appIDs) > 0 {
|
||||
q = q.Where("application_id IN ? OR user_id = ?", f.appIDs, f.userID)
|
||||
} else {
|
||||
query = query.Where("user_id = ?", userID)
|
||||
q = q.Where("user_id = ?", f.userID)
|
||||
}
|
||||
|
||||
if logType != "" && logType != "all" {
|
||||
query = query.Where("log_type = ?", logType)
|
||||
// 按应用筛选时必须是自己的应用;不是自己的应用直接查空,别拿它当探测手段
|
||||
if f.applicationID != "" && f.applicationID != "all" {
|
||||
owned := false
|
||||
for _, a := range f.appIDs {
|
||||
if strconv.FormatUint(uint64(a), 10) == f.applicationID {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if owned {
|
||||
q = q.Where("application_id = ?", f.applicationID)
|
||||
} else {
|
||||
q = q.Where("1 = 0")
|
||||
}
|
||||
}
|
||||
|
||||
if status != "" && status != "all" {
|
||||
query = query.Where("status = ?", status)
|
||||
if f.logType != "" && f.logType != "all" {
|
||||
q = q.Where("log_type = ?", f.logType)
|
||||
}
|
||||
|
||||
if applicationID != "" && applicationID != "all" {
|
||||
query = query.Where("application_id = ?", applicationID)
|
||||
if f.status != "" && f.status != "all" {
|
||||
q = q.Where("status = ?", f.status)
|
||||
}
|
||||
|
||||
if startDate != "" {
|
||||
query = query.Where("created_at >= ?", startDate+" 00:00:00")
|
||||
if f.startDate != "" {
|
||||
q = q.Where("created_at >= ?", f.startDate+" 00:00:00")
|
||||
}
|
||||
|
||||
if endDate != "" {
|
||||
query = query.Where("created_at <= ?", endDate+" 23:59:59")
|
||||
if f.endDate != "" {
|
||||
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
|
||||
}
|
||||
|
||||
if search != "" {
|
||||
p := "%" + escapeLike(search) + "%"
|
||||
query = query.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
|
||||
if f.search != "" {
|
||||
p := "%" + escapeLike(f.search) + "%"
|
||||
q = q.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
query.Count(&total)
|
||||
func handleGetLogs(c *gin.Context) {
|
||||
f := newLogFilter(c)
|
||||
page, pageSize := parsePageParams(c)
|
||||
|
||||
var total int64
|
||||
f.query().Count(&total)
|
||||
|
||||
// 三个统计数字必须和列表同源(同一个 Log 表 + 同一套筛选),
|
||||
// 否则会出现「列表 0 条、顶部写着成功 128」这种对不上的情况。
|
||||
// 以前用的是 ApiUsage 表,而且完全不带筛选条件。
|
||||
baseQuery := func() *gorm.DB {
|
||||
q := database.DB.Model(&model.Log{})
|
||||
if len(appIDs) > 0 {
|
||||
q = q.Where("application_id IN ? OR user_id = ?", appIDs, userID)
|
||||
} else {
|
||||
q = q.Where("user_id = ?", userID)
|
||||
}
|
||||
if logType != "" && logType != "all" {
|
||||
q = q.Where("log_type = ?", logType)
|
||||
}
|
||||
if status != "" && status != "all" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
if applicationID != "" && applicationID != "all" {
|
||||
q = q.Where("application_id = ?", applicationID)
|
||||
}
|
||||
if startDate != "" {
|
||||
q = q.Where("created_at >= ?", startDate+" 00:00:00")
|
||||
}
|
||||
if endDate != "" {
|
||||
q = q.Where("created_at <= ?", endDate+" 23:59:59")
|
||||
}
|
||||
if search != "" {
|
||||
p := "%" + escapeLike(search) + "%"
|
||||
q = q.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
var successCount, failedCount, operationCount int64
|
||||
baseQuery().Where("status = ?", "success").Count(&successCount)
|
||||
baseQuery().Where("status = ?", "failed").Count(&failedCount)
|
||||
baseQuery().Where("log_type = ?", "operation").Count(&operationCount)
|
||||
f.query().Where("status = ?", "success").Count(&successCount)
|
||||
f.query().Where("status = ?", "failed").Count(&failedCount)
|
||||
f.query().Where("log_type = ?", "operation").Count(&operationCount)
|
||||
|
||||
var logs []model.Log
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Preload("User").Preload("Application").Preload("AppUser").Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
|
||||
if err := f.query().Preload("User").Preload("Application").Preload("AppUser").
|
||||
Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
|
||||
response.Error(c, 500, "获取日志失败")
|
||||
return
|
||||
}
|
||||
@@ -122,3 +126,54 @@ func handleGetLogs(c *gin.Context) {
|
||||
"operation_count": operationCount,
|
||||
})
|
||||
}
|
||||
|
||||
// 日志导出(CSV):和列表同一套筛选,最多 10 万条。
|
||||
func handleExportLogs(c *gin.Context) {
|
||||
f := newLogFilter(c)
|
||||
|
||||
const exportLimit = 100000
|
||||
var logs []model.Log
|
||||
if err := f.query().Preload("User").Preload("Application").Preload("AppUser").
|
||||
Order("created_at DESC").Limit(exportLimit).Find(&logs).Error; err != nil {
|
||||
response.Error(c, 500, "导出日志失败")
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition",
|
||||
fmt.Sprintf("attachment; filename=logs_%s.csv", time.Now().Format("20060102-150405")))
|
||||
|
||||
typeName := map[string]string{"operation": "操作", "verification": "验证", "exception": "异常"}
|
||||
statusName := map[string]string{"success": "成功", "failed": "失败", "pending": "处理中"}
|
||||
|
||||
buf := make([]byte, 0, 64*len(logs)+128)
|
||||
buf = append(buf, 0xEF, 0xBB, 0xBF) // BOM,Excel 不乱码
|
||||
buf = append(buf, []byte("时间,类型,级别,动作,资源,状态,用户,应用,主体,IP,设备,详情,错误\n")...)
|
||||
for _, l := range logs {
|
||||
typ := typeName[l.LogType]
|
||||
if typ == "" {
|
||||
typ = l.LogType
|
||||
}
|
||||
st := statusName[l.Status]
|
||||
if st == "" {
|
||||
st = l.Status
|
||||
}
|
||||
userName, appName, subjectName := "", "", ""
|
||||
if l.User != nil {
|
||||
userName = l.User.Username
|
||||
}
|
||||
if l.Application != nil {
|
||||
appName = l.Application.Name
|
||||
}
|
||||
if l.AppUser != nil {
|
||||
subjectName = l.AppUser.Username
|
||||
}
|
||||
line := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n",
|
||||
l.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
csvField(typ), csvField(l.Level), csvField(l.Action), csvField(l.Resource), csvField(st),
|
||||
csvField(userName), csvField(appName), csvField(subjectName),
|
||||
csvField(l.IPAddress), csvField(l.DeviceID), csvField(l.Details), csvField(l.ErrorMessage))
|
||||
buf = append(buf, []byte(line)...)
|
||||
}
|
||||
c.String(200, string(buf))
|
||||
}
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import type { Log } from '@/pages/admin/logs/data/schema'
|
||||
|
||||
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
|
||||
import SingleFilter from '@/components/data-table/single-filter.vue'
|
||||
import { BasicPage } from '@/components/global-layout'
|
||||
import DataTable from '@/pages/admin/logs/components/data-table.vue'
|
||||
import api from '@/services/api'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Application {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const loading = ref(true)
|
||||
const logs = ref<Log[]>([])
|
||||
const applications = ref<Application[]>([])
|
||||
const currentPage = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const total = ref(0)
|
||||
const successCount = ref(0)
|
||||
const failedCount = ref(0)
|
||||
const operationCount = ref(0)
|
||||
|
||||
const appFilter = ref<string>('')
|
||||
const typeFilter = ref<string>('')
|
||||
const statusFilter = ref<string>('')
|
||||
const startDate = ref<string>('')
|
||||
const endDate = ref<string>('')
|
||||
|
||||
const applicationOptions = computed(() => {
|
||||
return applications.value.map(app => ({
|
||||
label: app.name,
|
||||
value: String(app.id),
|
||||
}))
|
||||
})
|
||||
|
||||
const typeOptions = computed(() => [
|
||||
{ label: t('admin.logs.types.operation'), value: 'operation' },
|
||||
{ label: t('admin.logs.types.verification'), value: 'verification' },
|
||||
{ label: t('admin.logs.types.exception'), value: 'exception' },
|
||||
])
|
||||
|
||||
const statusOptions = computed(() => [
|
||||
{ label: t('admin.success'), value: 'success' },
|
||||
{ label: t('admin.failed'), value: 'failed' },
|
||||
])
|
||||
|
||||
async function fetchApplications() {
|
||||
try {
|
||||
const data = await api.get<{ applications: Application[] }>('/dev/applications')
|
||||
applications.value = data?.applications || []
|
||||
}
|
||||
catch (error) {
|
||||
console.error('获取应用列表失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchLogs() {
|
||||
loading.value = true
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
params.append('page', String(currentPage.value))
|
||||
params.append('page_size', String(pageSize.value))
|
||||
|
||||
if (appFilter.value) {
|
||||
params.append('application_id', appFilter.value)
|
||||
}
|
||||
if (typeFilter.value) {
|
||||
params.append('type', typeFilter.value)
|
||||
}
|
||||
if (statusFilter.value) {
|
||||
params.append('status', statusFilter.value)
|
||||
}
|
||||
if (startDate.value) {
|
||||
params.append('start_date', startDate.value.split('T')[0])
|
||||
}
|
||||
if (endDate.value) {
|
||||
params.append('end_date', endDate.value.split('T')[0])
|
||||
}
|
||||
|
||||
const data = await api.get<any>(`/dev/logs?${params.toString()}`)
|
||||
logs.value = data?.logs || []
|
||||
total.value = data?.total || 0
|
||||
successCount.value = data?.success_count || 0
|
||||
failedCount.value = data?.failed_count || 0
|
||||
operationCount.value = data?.operation_count || 0
|
||||
}
|
||||
catch (error) {
|
||||
console.error('获取日志记录失败:', error)
|
||||
logs.value = []
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchApplications()
|
||||
fetchLogs()
|
||||
})
|
||||
|
||||
watch([appFilter, typeFilter, statusFilter, startDate, endDate], () => {
|
||||
currentPage.value = 1
|
||||
fetchLogs()
|
||||
})
|
||||
|
||||
const serverPagination = computed(() => ({
|
||||
currentPage: currentPage.value,
|
||||
pageSize: pageSize.value,
|
||||
total: total.value,
|
||||
onChange: (page: number) => {
|
||||
currentPage.value = page
|
||||
fetchLogs()
|
||||
},
|
||||
}))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BasicPage
|
||||
:title="t('admin.logs.title')"
|
||||
:description="t('admin.logs.description')"
|
||||
sticky
|
||||
>
|
||||
<div class="space-y-6">
|
||||
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<UiCard>
|
||||
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<UiCardTitle class="text-sm font-medium">
|
||||
{{ t('admin.logs.totalLogs') }}
|
||||
</UiCardTitle>
|
||||
<FileText class="size-4 text-muted-foreground" />
|
||||
</UiCardHeader>
|
||||
<UiCardContent>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ total }}
|
||||
</div>
|
||||
</UiCardContent>
|
||||
</UiCard>
|
||||
|
||||
<UiCard>
|
||||
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<UiCardTitle class="text-sm font-medium">
|
||||
{{ t('admin.logs.successCount') }}
|
||||
</UiCardTitle>
|
||||
<CheckCircle class="size-4 text-muted-foreground" />
|
||||
</UiCardHeader>
|
||||
<UiCardContent>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ successCount }}
|
||||
</div>
|
||||
</UiCardContent>
|
||||
</UiCard>
|
||||
|
||||
<UiCard>
|
||||
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<UiCardTitle class="text-sm font-medium">
|
||||
{{ t('admin.logs.failedCount') }}
|
||||
</UiCardTitle>
|
||||
<XCircle class="size-4 text-muted-foreground" />
|
||||
</UiCardHeader>
|
||||
<UiCardContent>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ failedCount }}
|
||||
</div>
|
||||
</UiCardContent>
|
||||
</UiCard>
|
||||
|
||||
<UiCard>
|
||||
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<UiCardTitle class="text-sm font-medium">
|
||||
{{ t('admin.logs.operationCount') }}
|
||||
</UiCardTitle>
|
||||
<Activity class="size-4 text-muted-foreground" />
|
||||
</UiCardHeader>
|
||||
<UiCardContent>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ operationCount }}
|
||||
</div>
|
||||
</UiCardContent>
|
||||
</UiCard>
|
||||
</div>
|
||||
|
||||
<UiCard>
|
||||
<UiCardContent class="p-6">
|
||||
<DataTable
|
||||
:loading
|
||||
:data="logs"
|
||||
:server-pagination="serverPagination"
|
||||
@refresh="fetchLogs"
|
||||
>
|
||||
<template #filters>
|
||||
<SingleFilter
|
||||
v-model="appFilter"
|
||||
:title="t('admin.logs.columns.application')"
|
||||
:options="applicationOptions"
|
||||
/>
|
||||
<SingleFilter
|
||||
v-model="typeFilter"
|
||||
:title="t('admin.logs.columns.type')"
|
||||
:options="typeOptions"
|
||||
/>
|
||||
<SingleFilter
|
||||
v-model="statusFilter"
|
||||
:title="t('admin.logs.columns.status')"
|
||||
:options="statusOptions"
|
||||
/>
|
||||
<DateRangeFilter
|
||||
v-model:start-model-value="startDate"
|
||||
v-model:end-model-value="endDate"
|
||||
/>
|
||||
</template>
|
||||
</DataTable>
|
||||
</UiCardContent>
|
||||
</UiCard>
|
||||
</div>
|
||||
</BasicPage>
|
||||
</template>
|
||||
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
|
||||
import { Activity, CheckCircle, Download, FileText, XCircle } from 'lucide-vue-next'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import { BasicPage } from '@/components/global-layout'
|
||||
import SingleFilter from '@/components/data-table/single-filter.vue'
|
||||
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
|
||||
import api from '@/services/api'
|
||||
import api, { BASE_URL } from '@/services/api'
|
||||
|
||||
import type { Log } from '@/pages/admin/logs/data/schema'
|
||||
|
||||
@@ -112,6 +112,23 @@ async function fetchLogs() {
|
||||
}
|
||||
}
|
||||
|
||||
// 导出当前筛选结果(后端 /dev/logs/export,与列表同一套筛选条件)
|
||||
function handleExport() {
|
||||
const token = localStorage.getItem('token')
|
||||
const params = new URLSearchParams()
|
||||
if (appFilter.value && appFilter.value !== 'all')
|
||||
params.append('application_id', appFilter.value)
|
||||
if (typeFilter.value && typeFilter.value !== 'all')
|
||||
params.append('type', typeFilter.value)
|
||||
if (statusFilter.value && statusFilter.value !== 'all')
|
||||
params.append('status', statusFilter.value)
|
||||
if (startDate.value)
|
||||
params.append('start_date', startDate.value.split('T')[0])
|
||||
if (endDate.value)
|
||||
params.append('end_date', endDate.value.split('T')[0])
|
||||
window.open(`${BASE_URL}/dev/logs/export?${params.toString()}&token=${token}`, '_blank')
|
||||
}
|
||||
|
||||
watch([appFilter, typeFilter, statusFilter, startDate, endDate], () => {
|
||||
currentPage.value = 1
|
||||
fetchLogs()
|
||||
@@ -202,6 +219,12 @@ onMounted(() => {
|
||||
@page-change="currentPage = $event; fetchLogs()"
|
||||
@page-size-change="pageSize = $event; currentPage = 1; fetchLogs()"
|
||||
>
|
||||
<template #actions>
|
||||
<UiButton variant="outline" size="sm" :disabled="loading" @click="handleExport">
|
||||
<Download class="mr-2 size-4" />
|
||||
{{ t('admin.logs.exportBtn') }}
|
||||
</UiButton>
|
||||
</template>
|
||||
<template #filters>
|
||||
<SingleFilter
|
||||
v-model="appFilter"
|
||||
|
||||
@@ -1953,7 +1953,8 @@
|
||||
"create_card_type": "Create Card Type: {name}",
|
||||
"update_card_type": "Update Card Type: {name}",
|
||||
"delete_card_type": "Delete Card Type: {name}"
|
||||
}
|
||||
},
|
||||
"exportBtn": "Export logs"
|
||||
},
|
||||
"cloudConstants": {
|
||||
"title": "Cloud Constants",
|
||||
|
||||
@@ -1970,7 +1970,8 @@
|
||||
"create_card_type": "创建卡密类型: {name}",
|
||||
"update_card_type": "更新卡密类型: {name}",
|
||||
"delete_card_type": "删除卡密类型: {name}"
|
||||
}
|
||||
},
|
||||
"exportBtn": "导出日志"
|
||||
},
|
||||
"cloudConstants": {
|
||||
"title": "云端常量",
|
||||
|
||||
Reference in New Issue
Block a user