LogFormatterFactory.php 1.4 KB
<?php
/**
 * @author:wlj
 * @date: 2022/6/7 16:49
 */

namespace App\Factory;

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

class LogFormatterFactory
{
    /**
     * 实现日志工厂
     *
     * @param array $config /config/logging.php 当前频道的配置
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        return new Logger('', [
            $this->create($config, Logger::ERROR, 'errors'),
            $this->create($config, Logger::INFO, 'info'),
        ]);
    }

    private function create($config, $level, $suffix = '')
    {
        $time = time();
        $path = date('Y-m', $time) . '/' . date('d', $time) . '_' . $suffix . '.log';
        $path = 'logs/' . $config['prefix'] . '/' . $path;
        $path = storage_path($path);

        try {
            if (!file_exists($path)) {
                $directory = pathinfo($path, PATHINFO_DIRNAME);
                if(!file_exists($directory)){
                    mkdir($directory, 0755, true);
                    chown($directory, 'www');
                }
                touch($path);
                chown($path, 'www');
            }
        }catch (\Throwable $exception){}

        $handler = new StreamHandler($path, $level, false);
        $handler->setFormatter(new LineFormatter(null, 'Y-m-d H:i:s', false, true));

        return $handler;
    }

}