概述
Laravel 框架自带的日志功能,默认是已文件的形式把系统日志记录在/storage/logs目录,我们的项目大部分部署在k8s容器,这导致我们项目在线上环境出现异常问题时,查看日志不太方便,并且不是所有开发人员都有线上环境账号。
因此尝试,扩展laravel日志通道,把日志记录在mysql。
要将Laravel日志保存在mysql数据库中,需要做以下几个步骤:
1. Laravel 配置
config/logging.php 配置文件
'channels' => [
'mysql' => [
'driver' => 'custom',
'via' => App\Logging\MysqlLogger::class,
],
]
.env 文件
LOG_MYSQL_CHANNEL_TABLE=logs #表名
LOG_MYSQL_CHANNEL_CONNECTION=logs #mysql链接
app/config/database.php 加入logs mysql链接信息
//记录一些自定义的系统运行日志
'logs' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
2. 日志通道代码编写
定义日志通道
app/Logging/MysqlLogger.php
<?php
/**
* 定义mysql日志channel
*/
namespace App\Logging;
class MysqlLogger
{
public function __invoke(array $config){
return tap(new \Monolog\Logger('mysql'), function ($logger) {
$logger->pushHandler(new MysqlLoggerHandler());
});
}
}
然后添加一个自定义的 Monolog 发射器(handler)到您的应用中以记录日志到 MySQL:
app/Logging/MysqlLoggerHandler.php
<?php
/**
* 日志写入mysql表logs
*/
namespace App\Logging;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
class MysqlLoggerHandler extends AbstractProcessingHandler
{
public $table;
public $connection;
public function __construct($level = Logger::DEBUG, bool $bubble = true)
{
$this->table = env('LOG_MYSQL_CHANNEL_TABLE','logs');
$this->connection = env('LOG_MYSQL_CHANNEL_CONNECTION','logs');
parent::__construct($level, $bubble);
}
protected function write(array $record): void
{
try{
if(isset($record['context']['exception']) && is_object($record['context']['exception'])){
$record['context']['exception'] = (array)$record['context']['exception'];
}
$record['request_data'] = request()->all() ??[];
$log = [
'guid' => guid(),
'title' => $record['message'],
'level' => $record['level_name'],
'request_host' => $record['request_host'] ?? request()->getSchemeAndHttpHost(),
'request_uri' => $record['request_uri'] ?? request()->getRequestUri(),
'request_method' => $record['request_method'] ?? request()->getMethod(),
'request_ip' => request()->getClientIp(),
'request_data' => json_encode($record['request_data']) ,
'context' => isset($record['context']) ? json_encode($record['context']) : '',
'created_at' => $record['datetime']->format('Y-m-d H:i:s'),
'updated_at' => $record['datetime']->format('Y-m-d H:i:s'),
];
if($this->connection && $this->table){
// TODO: Implement write() method.
DB::connection($this->connection)->table($this->table)->insert(
$log
);
}
}catch (\Exception $e){
Log::channel('daily')->error($e->getMessage().$e->getFile().$e->getTraceAsString());
}
}
}
3.创建储存日志logs表
CREATE TABLE `logs` (
`guid` varchar(64) NOT NULL COMMENT '自增主键',
`title` text COMMENT '标题',
`level` varchar(64) DEFAULT '' COMMENT '日志等级 INFO/ERROR...',
`request_host` varchar(255) DEFAULT NULL COMMENT '请求host',
`request_uri` varchar(128) NOT NULL COMMENT '请求uri',
`request_method` varchar(512) DEFAULT NULL COMMENT '请求方法',
`request_data` text COMMENT '请求参数',
`request_ip` varchar(255) DEFAULT NULL COMMENT 'ip',
`context` text COMMENT '额外参数',
`created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT NULL COMMENT '更新时间',
`deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`guid`),
KEY `request_uri` (`request_uri`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统运行日志记录表';
4.代码使用
Log::channel('mysql')->info('测试日志写入mysql',['a' => time()]);
5.注意:记录mysql执行sql语句的日志需要进行以下修改避免日志无限死循环记录
如: app/Providers/AppServiceProvider.php
if($this->app->environment() !== 'production'){
DB::listen(function ($query) {
$tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
$qBindings = [];
foreach ($query->bindings as $key => $value) {
if (is_numeric($key)) {
$qBindings[] = $value;
} else {
$tmp = str_replace(':'.$key, '"'.$value.'"', $tmp);
}
}
$tmp = vsprintf($tmp, $qBindings);
$tmp = str_replace("\\", "", $tmp);
#这里必须指定通道,避免无限循环写日志
Log::channel('daily')->info(' execution time: '.$query->time.'ms; '.$tmp);
});
}