Appearance
审计日志模块
审计模块(audit)提供操作日志的记录与查询能力。所有日志按租户隔离,支持按用户、操作类型、资源类型筛选和分页查询。
架构概览
modules/audit/
├── domain/ # AuditLog 实体、AuditQuery、Repository 接口
├── application/ # Service(Log 写入、Query 查询)
├── infrastructure/ # GORM AuditRepository 实现、AutoMigrate
└── interfaces/ # HTTP Handler、路由注册数据模型
AuditLog 实体
| 字段 | 类型 | 说明 |
|---|---|---|
| ID | uint | 主键 |
| TenantID | string (UUID) | 租户 ID,索引 |
| UserID | uint | 操作用户 ID,索引 |
| Action | string(64) | 操作类型,索引(如 user.login、article.create) |
| Resource | string(128) | 资源类型,索引(如 user、article) |
| ResourceID | string(128) | 资源 ID |
| Detail | text | 操作详情(JSON 或文本) |
| IP | string(64) | 客户端 IP |
| CreatedAt | time.Time | 创建时间,索引 |
数据库表: audit_logs
索引: tenant_id、user_id、action、resource、created_at — 优化筛选和分页查询性能。
API 接口
| 方法 | 路径 | 权限 | 说明 |
|---|---|---|---|
| GET | /api/v1/audit/logs | audit.log.read | 分页查询审计日志 |
查询参数
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
user_id | int | — | 按用户 ID 筛选 |
action | string | — | 按操作类型筛选 |
resource | string | — | 按资源类型筛选 |
page | int | 1 | 页码 |
page_size | int | 20 | 每页条数(最大 100) |
响应格式
json
{
"items": [
{
"id": 1,
"tenant_id": "uuid-xxx",
"user_id": 5,
"action": "user.login",
"resource": "user",
"resource_id": "5",
"detail": "登录成功",
"ip": "203.0.113.10",
"created_at": "2026-10-01T10:00:00Z"
}
],
"total": 100,
"page": 1
}内部 API
审计模块的 Service.Log() 方法供其他模块内部调用,不通过 HTTP 暴露:
go
func (s *Service) Log(ctx context.Context, tenantID string, userID uint,
action, resource, resourceID, detail, ip string) error其他模块的 Handler 或中间件可通过 DI 获取 audit.Service 来记录操作日志。
安全特性
- 租户隔离强制校验: Repository 层在查询前检查
TenantID非空,防止跨租户数据泄露 - 分页上限:
page_size最大 100,防止大量数据查询 - 默认分页: page=1, pageSize=20
- 排序: 按
created_at DESC倒序
依赖注入
go
fx.Module("audit",
fx.Provide(
auditinfra.NewAuditRepository,
application.NewService,
NewHandler,
),
)
