Commit fea571fc authored by 王源's avatar 王源 🎧

封装 Log 类

parent df76c0ea
<?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];
$channel = $arguments[1];
return static::log($channel)->{$name}($msg);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment