好想什么呢
来猜猜吧
logs 部分
结合laravel logs
重构
在laravel logs
基础上将logs
存入数据库
先下config\logging
中添加channels
如下
1 2 3 4 5 6 7 8 9 10 11 12
| 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['mysql'], ], 'mysql' => [ 'driver' => 'custom', 'name' => 'mysql', 'via' => App\Logging\MySQLLogger::class, 'level' => 'debug', ], ]
|
新建MySQLLogger
这部分可以查看laravel 文档
Logger
的 name
不能正常传入,问题暂时没找到根源
于是进行手动传入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?php namespace App\Logging;
use Monolog\Logger; use App\Logging\AdminLogsHandler;
class MySQLLogger { public function __invoke(array $config) { return new Logger( env('APP_NAME'), [ new LogsHandler( $config['level'], $config['name'] ) ] ); } }
|
之后是AdminLogsHandler
用于将logs
提交到数据库
这里也可以复写其他方法,可以自行查看Monolog\Logger
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?php
namespace App\Logging;
use Monolog\Logger; use Monolog\Handler\AbstractProcessingHandler; use App\Models\Logs;
class AdminLogsHandler extends AbstractProcessingHandler { private $name; public function __construct($level, $name) { parent::__construct($level); $this->name = $name; }
protected function write(array $record) { Logs::create([ 'channel' => $this->name, 'message' => $record['message'], 'level' => $record['level_name'], 'context' => $record['context'] ]); } }
|
App\Models\Logs
注意要添加批量写入
1 2 3 4 5 6 7 8 9
| protected $fillable = [ 'channel', 'message', 'level', 'context' ]; protected $casts = [ 'context' => 'array', ];
|
数据迁移如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| $table->increments('id'); $table->string('channel')->index(); $table->enum('level', [ 'DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY' ])->default('INFO'); $table->longText('message'); $table->text('context'); $table->timestamps();
|
之后可以使用
Log::info('message' , ['id' => $id])
以上