| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- /*
- * This file is part of the overtrue/wechat.
- *
- * (c) overtrue <i@overtrue.me>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace ByteDance\Kernel\Log;
- use Monolog\Formatter\LineFormatter;
- use Monolog\Handler\ErrorLogHandler;
- use Monolog\Handler\HandlerInterface;
- use Monolog\Handler\RotatingFileHandler;
- use Monolog\Handler\SlackWebhookHandler;
- use Monolog\Handler\StreamHandler;
- use Monolog\Handler\SyslogHandler;
- use Monolog\Logger as Monolog;
- use ByteDance\Kernel\ServiceContainer;
- use Psr\Log\LoggerInterface;
- /**
- * Class LogManager.
- *
- * @author overtrue <i@overtrue.me>
- */
- class LogManager implements LoggerInterface
- {
- /**
- * @var \ByteDance\Kernel\ServiceContainer
- */
- protected $app;
- /**
- * The array of resolved channels.
- *
- * @var array
- */
- protected $channels = [];
- /**
- * The registered custom driver creators.
- *
- * @var array
- */
- protected $customCreators = [];
- /**
- * The Log levels.
- *
- * @var array
- */
- protected $levels = [
- 'debug' => Monolog::DEBUG,
- 'info' => Monolog::INFO,
- 'notice' => Monolog::NOTICE,
- 'warning' => Monolog::WARNING,
- 'error' => Monolog::ERROR,
- 'critical' => Monolog::CRITICAL,
- 'alert' => Monolog::ALERT,
- 'emergency' => Monolog::EMERGENCY,
- ];
- /**
- * LogManager constructor.
- *
- * @param \ByteDance\Kernel\ServiceContainer $app
- */
- public function __construct(ServiceContainer $app)
- {
- $this->app = $app;
- }
- /**
- * Create a new, on-demand aggregate logger instance.
- *
- * @param array $channels
- * @param string|null $channel
- *
- * @return \Psr\Log\LoggerInterface
- */
- public function stack(array $channels, $channel = null)
- {
- return $this->createStackDriver(compact('channels', 'channel'));
- }
- /**
- * Get a log channel instance.
- *
- * @param string|null $channel
- *
- * @return mixed
- */
- public function channel($channel = null)
- {
- return $this->get($channel);
- }
- /**
- * Get a log driver instance.
- *
- * @param string|null $driver
- *
- * @return mixed
- */
- public function driver($driver = null)
- {
- return $this->get($driver ?? $this->getDefaultDriver());
- }
- /**
- * Attempt to get the log from the local cache.
- *
- * @param string $name
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function get($name)
- {
- try {
- return $this->channels[$name] ?? ($this->channels[$name] = $this->resolve($name));
- } catch (\Throwable $e) {
- $logger = $this->createEmergencyLogger();
- $logger->emergency('Unable to create configured logger. Using emergency logger.', [
- 'exception' => $e,
- ]);
- return $logger;
- }
- }
- /**
- * Resolve the given log instance by name.
- *
- * @param string $name
- *
- * @throws \InvalidArgumentException
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function resolve($name)
- {
- $config = $this->app['config']->get(\sprintf('log.channels.%s', $name));
- if (is_null($config)) {
- throw new \InvalidArgumentException(\sprintf('Log [%s] is not defined.', $name));
- }
- if (isset($this->customCreators[$config['driver']])) {
- return $this->callCustomCreator($config);
- }
- $driverMethod = 'create'.ucfirst($config['driver']).'Driver';
- if (method_exists($this, $driverMethod)) {
- return $this->{$driverMethod}($config);
- }
- throw new \InvalidArgumentException(\sprintf('Driver [%s] is not supported.', $config['driver']));
- }
- /**
- * Create an emergency log handler to avoid white screens of death.
- *
- * @return \Monolog\Logger
- */
- protected function createEmergencyLogger()
- {
- return new Monolog('EasyWeChat', $this->prepareHandlers([new StreamHandler(
- \sys_get_temp_dir().'/easywechat/easywechat.log', $this->level(['level' => 'debug'])
- )]));
- }
- /**
- * Call a custom driver creator.
- *
- * @param array $config
- *
- * @return mixed
- */
- protected function callCustomCreator(array $config)
- {
- return $this->customCreators[$config['driver']]($this->app, $config);
- }
- /**
- * Create an aggregate log driver instance.
- *
- * @param array $config
- *
- * @return \Monolog\Logger
- */
- protected function createStackDriver(array $config)
- {
- $handlers = [];
- foreach ($config['channels'] ?? [] as $channel) {
- $handlers = \array_merge($handlers, $this->channel($channel)->getHandlers());
- }
- return new Monolog($this->parseChannel($config), $handlers);
- }
- /**
- * Create an instance of the single file log driver.
- *
- * @param array $config
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function createSingleDriver(array $config)
- {
- return new Monolog($this->parseChannel($config), [
- $this->prepareHandler(
- new StreamHandler($config['path'], $this->level($config))
- ),
- ]);
- }
- /**
- * Create an instance of the daily file log driver.
- *
- * @param array $config
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function createDailyDriver(array $config)
- {
- return new Monolog($this->parseChannel($config), [
- $this->prepareHandler(new RotatingFileHandler(
- $config['path'], $config['days'] ?? 7, $this->level($config)
- )),
- ]);
- }
- /**
- * Create an instance of the Slack log driver.
- *
- * @param array $config
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function createSlackDriver(array $config)
- {
- return new Monolog($this->parseChannel($config), [
- $this->prepareHandler(new SlackWebhookHandler(
- $config['url'],
- $config['channel'] ?? null,
- $config['username'] ?? 'EasyWeChat',
- $config['attachment'] ?? true,
- $config['emoji'] ?? ':boom:',
- $config['short'] ?? false,
- $config['context'] ?? true,
- $this->level($config)
- )),
- ]);
- }
- /**
- * Create an instance of the syslog log driver.
- *
- * @param array $config
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function createSyslogDriver(array $config)
- {
- return new Monolog($this->parseChannel($config), [
- $this->prepareHandler(new SyslogHandler(
- 'EasyWeChat', $config['facility'] ?? LOG_USER, $this->level($config))
- ),
- ]);
- }
- /**
- * Create an instance of the "error log" log driver.
- *
- * @param array $config
- *
- * @return \Psr\Log\LoggerInterface
- */
- protected function createErrorlogDriver(array $config)
- {
- return new Monolog($this->parseChannel($config), [
- $this->prepareHandler(new ErrorLogHandler(
- $config['type'] ?? ErrorLogHandler::OPERATING_SYSTEM, $this->level($config))
- ),
- ]);
- }
- /**
- * Prepare the handlers for usage by Monolog.
- *
- * @param array $handlers
- *
- * @return array
- */
- protected function prepareHandlers(array $handlers)
- {
- foreach ($handlers as $key => $handler) {
- $handlers[$key] = $this->prepareHandler($handler);
- }
- return $handlers;
- }
- /**
- * Prepare the handler for usage by Monolog.
- *
- * @param \Monolog\Handler\HandlerInterface $handler
- *
- * @return \Monolog\Handler\HandlerInterface
- */
- protected function prepareHandler(HandlerInterface $handler)
- {
- return $handler->setFormatter($this->formatter());
- }
- /**
- * Get a Monolog formatter instance.
- *
- * @return \Monolog\Formatter\FormatterInterface
- */
- protected function formatter()
- {
- $formatter = new LineFormatter(null, null, true, true);
- $formatter->includeStacktraces();
- return $formatter;
- }
- /**
- * Extract the log channel from the given configuration.
- *
- * @param array $config
- *
- * @return string
- */
- protected function parseChannel(array $config)
- {
- return $config['name'] ?? null;
- }
- /**
- * Parse the string level into a Monolog constant.
- *
- * @param array $config
- *
- * @throws \InvalidArgumentException
- *
- * @return int
- */
- protected function level(array $config)
- {
- $level = $config['level'] ?? 'debug';
- if (isset($this->levels[$level])) {
- return $this->levels[$level];
- }
- throw new \InvalidArgumentException('Invalid log level.');
- }
- /**
- * Get the default log driver name.
- *
- * @return string
- */
- public function getDefaultDriver()
- {
- return $this->app['config']['log.default'];
- }
- /**
- * Set the default log driver name.
- *
- * @param string $name
- */
- public function setDefaultDriver($name)
- {
- $this->app['config']['log.default'] = $name;
- }
- /**
- * Register a custom driver creator Closure.
- *
- * @param string $driver
- * @param \Closure $callback
- *
- * @return $this
- */
- public function extend($driver, \Closure $callback)
- {
- $this->customCreators[$driver] = $callback->bindTo($this, $this);
- return $this;
- }
- /**
- * System is unusable.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function emergency($message, array $context = [])
- {
- return $this->driver()->emergency($message, $context);
- }
- /**
- * Action must be taken immediately.
- *
- * Example: Entire website down, database unavailable, etc. This should
- * trigger the SMS alerts and wake you up.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function alert($message, array $context = [])
- {
- return $this->driver()->alert($message, $context);
- }
- /**
- * Critical conditions.
- *
- * Example: Application component unavailable, unexpected exception.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function critical($message, array $context = [])
- {
- return $this->driver()->critical($message, $context);
- }
- /**
- * Runtime errors that do not require immediate action but should typically
- * be logged and monitored.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function error($message, array $context = [])
- {
- return $this->driver()->error($message, $context);
- }
- /**
- * Exceptional occurrences that are not errors.
- *
- * Example: Use of deprecated APIs, poor use of an API, undesirable things
- * that are not necessarily wrong.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function warning($message, array $context = [])
- {
- return $this->driver()->warning($message, $context);
- }
- /**
- * Normal but significant events.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function notice($message, array $context = [])
- {
- return $this->driver()->notice($message, $context);
- }
- /**
- * Interesting events.
- *
- * Example: User logs in, SQL logs.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function info($message, array $context = [])
- {
- return $this->driver()->info($message, $context);
- }
- /**
- * Detailed debug information.
- *
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function debug($message, array $context = [])
- {
- return $this->driver()->debug($message, $context);
- }
- /**
- * Logs with an arbitrary level.
- *
- * @param mixed $level
- * @param string $message
- * @param array $context
- *
- * @return mixed
- */
- public function log($level, $message, array $context = [])
- {
- return $this->driver()->log($level, $message, $context);
- }
- /**
- * Dynamically call the default driver instance.
- *
- * @param string $method
- * @param array $parameters
- *
- * @return mixed
- */
- public function __call($method, $parameters)
- {
- return $this->driver()->$method(...$parameters);
- }
- }
|