Laravel日志类

269 阅读1分钟
<?php

namespace App\Common\Util;

use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * Class FileLog
 * @package App\Common\Util
 */
class FileLog {

    /**
     * @var string
     */
    private $uniqid = NULL;
    private $log = NULL;
    private static $monoLog = [];

    private function __construct($channel)
    {
        //保证整个请求不同的channel进程好号唯一
        $this->uniqid = getRequestId();
        $this->log = $this->initLoger($channel);
    }

    public function __call($method, $parameters)
    {
        return $this->log->$method(...$parameters);
    }

    /**
     * @param $channel
     * @return mixed
     */
    static function getInstance($channel)
    {
        if ( ! $channel)
        {
            $channel = 'common';
        }
        if ( ! isset(self::$monoLog[$channel]))
        {
            self::$monoLog[$channel] = new self($channel);
        }
        return self::$monoLog[$channel];
    }


    private function initLoger($channel)
    {
        $log = new Logger($channel);
        $logsPath = storage_path('logs/' . $channel) . '/' . $channel . '.log';
        $level = config('app.debug') ? Logger::DEBUG : Logger::INFO;
        list($usec, $sec) = explode(" ", microtime());
        // 日志文件相关操作
        $handler = new RotatingFileHandler($logsPath, 31, $level, TRUE, 0777);
        // 日志格式
        $formatter = new LineFormatter("[%datetime%] | {$this->uniqid} | %level_name% # %message% %context% %extra%\n", "Y-m-d H:i:s" . sprintf('%02d', round($usec * 100)), FALSE, TRUE);
        $handler->setFormatter($formatter);

        $log->pushHandler($handler);

        //添加额外的数据
        $log->pushProcessor(function ($record) {
            //$record['extra']['uniqid'] = $this->uniqid;
            return $record;
        });
        return $log;
    }

}
/*
 * 获取请求id,没有生成默认放在header里面,可以是web或者console
 */
function getRequestId(){
    $requestId = request()->header('Request-Id');
    if (! $requestId){
        $requestId = Illuminate\Support\Str::uuid();
        request()->headers->set('Request-Id', $requestId);
    }

    return $requestId;
}

实际效果

[2022-04-22 12:05:5992] | 626229a6dfe5b | INFO #  execution time: 17.63ms; select * from `table` where `id` in ("5f119fd68779db0001ab0e2b") and `deleted_at` is null