用 PHP 8 Attribute 声明"谁在什么时候改了什么",免去在方法里手写日志调用。它记的是业务语义("删除了用户张三"),不是请求流水——后者由
AuditLog中间件负责。
安装
composer require wiseadmin/wise-operation-log
php think vendor:publish # 可选,覆盖默认配置配置自动加载;operation_log 表由 registerMigrations() 注册,迁移后建立。
必须注册中间件,否则 Attribute 不会被执行(app/middleware.php):
return [ \wise\operationlog\middleware\OperationLog::class ];另有独立的 wise\operationlog\middleware\AuditLog,负责 POST/PUT/DELETE/PATCH 的原始请求审计,落 audit_log。两者互补:一个是"发生了什么业务动作",一个是"收到了什么请求"。
Attribute 用法
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
public function __construct(
public string $template = '', // 类级可省略,方法级必填
public string $channel = 'default',
public array $conditions = [], // ["字段路径" => "期望值"]
public bool $recordParams = false,
public array $tags = [],
public string $level = 'INFO'
) {}类级声明公共默认值,方法级只写 template,自动继承 channel / tags / conditions / recordParams:
use wise\operationlog\attribute\OperationLog as Log;
use wise\operationlog\context\LogContext;
#[Log(channel: 'admin', tags: ['user'])]
class UserController
{
#[Log(template: '删除了用户{user.name}')]
public function delete($id)
{
LogContext::set('user', ['name' => '张三']);
// ...
}
}模板支持 {变量}、{user.name} 嵌套取值与 |filter(default / date),可以写 {created_at|date:'Y-m-d'}。conditions 用来只记特定情况:['status' => 'success'] 表示仅当上下文中 status 为该值时才记录。
LogContext(wise\operationlog\context\LogContext):set()、get()、all()、clear()。Swoole 协程下经 wise\support\runtime\Runtime::context() 隔离,FPM / CLI 用静态数组——所以必须在请求内设置,跨请求复用会串号。
门面与命令
use wise\operationlog\facade\OperationLog;
OperationLog::query(); // 查询
OperationLog::cleanup(90); // 清理 90 天前
OperationLog::retain();
OperationLog::stats();
OperationLog::trend();
OperationLog::hotspots();
OperationLog::ipAnalysis();命令:
php think wise:operationlog:clean <days> [--max=N]
php think wise:operationlog:archive [--dry-run]
php think wise:operationlog:report [--stats --trend --hotspots --error-rate --all --start --end --top=20]
php think wise:operationlog:anomaly [--type=all --window=5 --threshold=3 --error-count=10]archive 需要 archive.enable = true 才工作,否则直接提示未启用并返回——这是"配了没生效"的常见原因。
配置里值得改的几项
| 键 | 默认 | 说明 |
|---|---|---|
queue.enable | false | 开启后异步写入,需要 worker |
operator.id_resolver | auth_id('admin') | 取"谁"的方式,多用户体系要改 |
sensitive.enable | true | 敏感字段脱敏 |
buffer.max_size | 500 | 缓冲上限,shutdown_save 决定退出时是否落盘 |
ttl.days / ttl.max_records | 依配置 | 保留策略,auto_cleanup 默认关 |
exclude.controllers/routes/ips | 空 | 排除高频噪音(如健康检查接口) |
audit.retention_days | 1095 | 审计日志保留三年(合规常见要求) |
三个容易搞错的认知
一、"加了 Attribute 就会记录"。 中间件没注册就不会执行,且方法必须是公开方法——私有方法与 CLI 命令都不经过它。
二、"操作日志能还原字段旧值"。 它记动作与参数摘要,字段级 diff 是 ChangeLoggable 的事。
三、"params 可以随便开"。 recordParams 会存下请求参数,先确认 sensitive 规则覆盖了密码、token、手机号。
自查:给一个控制器方法加 #[Log(template: ...)] 并执行一次,OperationLog::query() 应能查到;wise:operationlog:report --stats 有统计;命中 sensitive 规则的字段已脱敏。
框架侧口径见操作日志与审计。