笔记:QueryLog
基于laravel的事件实现:
QueryLogListener代码:
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
class QueryLogListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(QueryExecuted $event)
{
//是否启用 Sql 日志
$queryLog = config('database.query_log');
$querySlowLogTime = config('database.query_log_slow_time');
if ($queryLog) {
$sql = $event->sql;
$arg = $event->bindings;
if ($arg) {
foreach ($arg as $key => $value) {
$offset = strpos($sql, '?');
if ($offset !== false) {
if (is_int($value)) {
$value = (int)$value;
} else {
$value = '"' . (string)$value . '"';
}
}
$sql = substr_replace($sql, $value, $offset, strlen('?'));
}
}
$log = vsprintf($sql, $event->bindings);
$logStr = "sql:" . $log . " spend_time:" . $event->time;
if ($querySlowLogTime > 0 && $event->time >= $querySlowLogTime) {
Log::channel('querySlowLog')->info($logStr);
} else {
Log::channel('queryLog')->info($logStr);
}
}
}
}
config/database.php 添加配置:
/*
* sql logs
*/
'query_log' => env('QUERY_LOG', false),
'query_log_slow_time' => env('QUERY_LOG_SLOW_TIME', 0),
config/logging.php 添加配置:
/*
* chanel: queryLog, querySlowLog
*/
'queryLog' => [
'driver' => 'daily',
'path' => storage_path('logs/query/query.log'),
'level' => 'debug',
'days' => 14,
],
'querySlowLog' => [
'driver' => 'daily',
'path' => storage_path('logs/query/slow.log'),
'level' => 'debug',
'days' => 14,
],
本作品采用《CC 协议》,转载必须注明作者和本文链接
怎么调用呢
@dingding2019 基于事件监听实现,无需调用。参考laravel事件系统:事件系统《Laravel 8 中文文档》
overture 有composer包
大佬,原生实现的话有什么思路没
@如梦又似幻 原生一样的思路呗,不过自己实现一个观察者而已。不过既然纯原生好像也不用麻烦,搞什么监听事件了。既然DB模型或者说DB驱动你都实现了,随便加个DB日志的单列,不就想怎么玩就怎么玩了嘛。