<?php /** * Created by PhpStorm. * User: Zero * Date: 2021/06/09 * Time: 10:14:32 */ namespace Meibuyu\Micro\Tools; use Hyperf\Logger\Logger; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; use Monolog\Handler\FormattableHandlerInterface; use Monolog\Handler\HandlerInterface; use Monolog\Handler\RotatingFileHandler; use Psr\Log\LoggerInterface; /** * Class Log * @package App\Services * @method static emergency($message, string $name = 'app') * @method static alert($message, string $name = 'app') * @method static critical($message, string $name = 'app') * @method static error($message, string $name = 'app') * @method static warning($message, string $name = 'app') * @method static notice($message, string $name = 'app') * @method static info($message, string $name = 'app') * @method static debug($message, string $name = 'app') */ class Log { /** * @var LoggerInterface */ protected static $logs; /** * @return LoggerInterface */ public static function log($channel = 'app') { if (!isset(self::$logs[$channel])) { self::$logs[$channel] = make(Logger::class, [ 'name' => $channel, 'handlers' => self::handlers($channel), ]); } return self::$logs[$channel]; } protected static function handlers($channel): array { $handlerConfigs = [ [ 'class' => RotatingFileHandler::class, 'constructor' => [ 'filename' => BASE_PATH . "/runtime/logs/$channel.log", 'level' => Logger::DEBUG, ], 'formatter' => [ 'class' => LineFormatter::class, 'constructor' => [ 'format' => "[%datetime%] %channel%.%level_name%: %message%\n", 'dateFormat' => 'Y-m-d H:i:s', 'allowInlineLineBreaks' => true, ], ], ], ]; $handlers = []; foreach ($handlerConfigs as $value) { $formatterConfig = $value['formatter']; /** @var HandlerInterface $handler */ $handler = make($value['class'], $value['constructor']); if ($handler instanceof FormattableHandlerInterface) { $formatterClass = $formatterConfig['class']; $formatterConstructor = $formatterConfig['constructor']; /** @var FormatterInterface $formatter */ $formatter = make($formatterClass, $formatterConstructor); $handler->setFormatter($formatter); } $handlers[] = $handler; } return $handlers; } public static function __callStatic($name, $arguments) { $msg = $arguments[0]; if (is_array($msg)) { $msg = var_export($msg, true); } $channel = $arguments[1] ?? 'app'; return static::log($channel)->{$name}($msg); } }