Skip to content

审计日志模块 ​

审计模块(audit)提供操作日志的记录与查询能力。所有日志按租户隔离,支持按用户、操作类型、资源类型筛选和分页查询。

架构概览 ​

modules/audit/
├── domain/          # AuditLog 实体、AuditQuery、Repository 接口
├── application/     # Service(Log 写入、Query 查询)
├── infrastructure/  # GORM AuditRepository 实现、AutoMigrate
└── interfaces/      # HTTP Handler、路由注册

数据模型 ​

AuditLog 实体 ​

字段类型说明
IDuint主键
TenantIDstring (UUID)租户 ID,索引
UserIDuint操作用户 ID,索引
Actionstring(64)操作类型,索引(如 user.login、article.create)
Resourcestring(128)资源类型,索引(如 user、article)
ResourceIDstring(128)资源 ID
Detailtext操作详情(JSON 或文本)
IPstring(64)客户端 IP
CreatedAttime.Time创建时间,索引

数据库表: audit_logs

索引: tenant_id、user_id、action、resource、created_at — 优化筛选和分页查询性能。

API 接口 ​

方法路径权限说明
GET/api/v1/audit/logsaudit.log.read分页查询审计日志

查询参数 ​

参数类型默认值说明
user_idint—按用户 ID 筛选
actionstring—按操作类型筛选
resourcestring—按资源类型筛选
pageint1页码
page_sizeint20每页条数(最大 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,
    ),
)

Released under the Apache 2.0 License.