ThinkPHP6 调整日志记录渠道


ThinkPHP6 默认的日志渠道写入的日志,没有访问链接端口,每次请求也没有明显的区别。所以这里需要对其进行调整。

 

1、增加日志通道,将默认的file日志通道配置复制一份,并修改名字为tp6log

<?php

// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
return [
    // 默认日志记录通道
    'default'      => env('log.channel', 'tp6log'),
    // 日志记录级别
    'level'        => ['sql','diy','error'],
    // 日志类型记录的通道 ['error'=>'email',...]
    'type_channel' => [],
    // 关闭全局日志写入
    'close'        => false,
    // 全局日志处理 支持闭包
    'processor'    => null,

    // 日志通道列表
    'channels'     => [
        'file' => [
            // 日志记录方式
            'type'           => 'File',
            // 日志保存目录
            'path'           => '',
            // 单文件日志写入
            'single'         => false,
            // 独立日志级别
            'apart_level'    => [],
            // 最大日志文件数量
            'max_files'      => 0,
            // 使用JSON格式记录
            'json'           => false,
            // 日志处理
            'processor'      => null,
            // 关闭通道日志写入
            'close'          => false,
            // 日志输出格式化
            'format'         => '[%s][%s] %s',
            // 是否实时写入
            'realtime_write' => false,
        ],
        'tp6log' => [
            // 日志记录方式
            'type'           => 'common\log\Tp6Log',
            // 日志保存目录
            'path'           => '',
            // 单文件日志写入
            'single'         => false,
            // 独立日志级别
            'apart_level'    => [],
            // 最大日志文件数量
            'max_files'      => 0,
            // 使用JSON格式记录
            'json'           => false,
            // 日志处理
            'processor'      => null,
            // 关闭通道日志写入
            'close'          => false,
            // 日志输出格式化
            'format'         => '[%s][%s] %s',
            // 是否实时写入
            'realtime_write' => false,
        ],
        // 其它日志通道配置
    ],

];

 

2、找到框架中日志驱动中默认的File驱动文件,复制一份修改为Tp6log.php ,将日志通道配置 tp6log type 设置为  common\log\Tp6Log ,并对Tp6log.php文件做如下调整:

   2.1 调整日志路径,用于区分正常日志cli日志

  if (empty($this->config['path'])) {
            if (request()->isCli()) {
                $this->config['path'] = $app->getRuntimePath().'cli_log';
            } else {
                $this->config['path'] = $app->getRuntimePath().'log';
            }
        }

   2.2 增加分割线 ,区分每次请求,并增加请求信息

   // 新增
        $request = Request::instance();
        $requestInfo = [
            'ip' => $request->ip(),
            'method' => $request->method(),
        ];

        $url = request()->url(true);

        array_unshift($info, "---------------------------------------------------------------\r\n[{$time}] {$requestInfo['ip']} {$requestInfo['method']} $url");

 

完整代码如下

 

<?php

/*
 *  +----------------------------------------------------------------------
 *  | wangqy
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2023 http://upwqy.com All rights reserved.
 *  +----------------------------------------------------------------------
 *  | Author: wangqy <529857614@qq.com>
 *  +----------------------------------------------------------------------
 */

namespace common\log;

use think\App;
use think\contract\LogHandlerInterface;
use think\facade\Request;

/**
 * 本地化调试输出到文件.
 */
class Tp6Log implements LogHandlerInterface
{
    /**
     * 配置参数.
     *
     * @var array
     */
    protected $config = [
        'time_format' => 'c',
        'single' => false,
        'file_size' => 2097152,
        'path' => '',
        'apart_level' => [],
        'max_files' => 0,
        'json' => false,
        'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
        'format' => '[%s][%s] %s',
    ];

    // 实例化并传入参数
    public function __construct(App $app, $config = [])
    {
        if (\is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }

        if (empty($this->config['format'])) {
            $this->config['format'] = '[%s][%s] %s';
        }

        if (empty($this->config['path'])) {
            if (request()->isCli()) {
                $this->config['path'] = $app->getRuntimePath().'cli_log';
            } else {
                $this->config['path'] = $app->getRuntimePath().'log';
            }
        }

        if (\DIRECTORY_SEPARATOR != substr($this->config['path'], -1)) {
            $this->config['path'] .= \DIRECTORY_SEPARATOR;
        }


    }

    /**
     * 日志写入接口.
     *
     * @param array $log 日志信息
     */
    public function save(array $log): bool
    {
        $destination = $this->getMasterLogFile();

        $path = \dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);

        $info = [];

        // 日志信息封装
        $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        // 新增
        $request = Request::instance();
        $requestInfo = [
            'ip' => $request->ip(),
            'method' => $request->method(),
        ];

        $url = request()->url(true);

        array_unshift($info, "---------------------------------------------------------------\r\n[{$time}] {$requestInfo['ip']} {$requestInfo['method']} $url");

        foreach ($log as $type => $val) {
            $message = [];
            foreach ($val as $msg) {
                if (!\is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $message[] = $this->config['json'] ?
                    json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) :
                    sprintf($this->config['format'], $time, $type, $msg);
            }

            if (true === $this->config['apart_level'] || \in_array($type, $this->config['apart_level'])) {
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);
                $this->write($message, $filename);

                continue;
            }

            $info[$type] = $message;
        }

        if ($info) {
            return $this->write($info, $destination);
        }

        return true;
    }

    /**
     * 日志写入.
     *
     * @param array  $message     日志信息
     * @param string $destination 日志文件
     */
    protected function write(array $message, string $destination): bool
    {
        // 检测日志文件大小,超过配置大小则备份日志文件重新生成
        $this->checkLogSize($destination);

        $info = [];

        foreach ($message as $type => $msg) {
            $info[$type] = \is_array($msg) ? implode(PHP_EOL, $msg) : $msg;
        }

        $message = implode(PHP_EOL, $info).PHP_EOL;

        return error_log($message, 3, $destination);
    }

    /**
     * 获取主日志文件名.
     */
    protected function getMasterLogFile(): string
    {
        if ($this->config['max_files']) {
            $files = glob($this->config['path'].'*.log');

            try {
                if (\count($files) > $this->config['max_files']) {
                    unlink($files[0]);
                }
            } catch (\Exception $e) {
            }
        }

        if ($this->config['single']) {
            $name = \is_string($this->config['single']) ? $this->config['single'] : 'single';
            $destination = $this->config['path'].$name.'.log';
        } else {
            if ($this->config['max_files']) {
                $filename = date('Ymd').'.log';
            } else {
                $filename = date('Ym').\DIRECTORY_SEPARATOR.date('d').'.log';
            }

            $destination = $this->config['path'].$filename;
        }

        return $destination;
    }

    /**
     * 获取独立日志文件名.
     *
     * @param string $path 日志目录
     * @param string $type 日志类型
     */
    protected function getApartLevelFile(string $path, string $type): string
    {
        if ($this->config['single']) {
            $name = \is_string($this->config['single']) ? $this->config['single'] : 'single';

            $name .= '_'.$type;
        } elseif ($this->config['max_files']) {
            $name = date('Ymd').'_'.$type;
        } else {
            $name = date('d').'_'.$type;
        }

        return $path.\DIRECTORY_SEPARATOR.$name.'.log';
    }

    /**
     * 检查日志文件大小并自动生成备份文件.
     *
     * @param string $destination 日志文件
     */
    protected function checkLogSize(string $destination): void
    {
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
            try {
                rename($destination, \dirname($destination).\DIRECTORY_SEPARATOR.time().'-'.basename($destination));
            } catch (\Exception $e) {
            }
        }
    }
}

 

修正过的日志文件记录的日志

发布时间 : 2023-03-01,阅读量:1400 , 分类: ThinkPHP
本文链接:https://upwqy.com/details/54.html
Packagist 镜像使用方法 PHP教程 - EOF(heredoc) 使用说明