LogFormatterFactory.php 1020 字节
<?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);
        $handler = new StreamHandler($path, $level, false);
        $handler->setFormatter(new LineFormatter(null, 'Y-m-d H:i:s', false, true));
        return $handler;
    }

}