This commit is contained in:
2021-08-24 18:10:07 +08:00
parent 2db271dab3
commit 575f4b8520
80 changed files with 6 additions and 6 deletions
+156
View File
@@ -0,0 +1,156 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/26 0026
* Time: 10:00
*/
declare(strict_types=1);
namespace Kiri\Error;
use Exception;
use Http\IInterface\IFormatter;
use Kiri\Abstracts\Component;
use Kiri\Core\Json;
use Kiri\Events\EventDispatch;
use Kiri\Kiri;
use Server\Events\OnAfterRequest;
/**
* Class ErrorHandler
*
* @package Kiri\Kiri\Base
* @property-read $asError
*/
class ErrorHandler extends Component implements ErrorInterface
{
/** @var ?IFormatter $message */
private ?IFormatter $message = NULL;
public string $category = 'app';
/**
* 错误处理注册
*/
public function register()
{
// ini_set('display_errors', '1');
set_exception_handler([$this, 'exceptionHandler']);
if (defined('HHVM_VERSION')) {
set_error_handler([$this, 'errorHandler']);
} else {
set_error_handler([$this, 'errorHandler']);
}
register_shutdown_function([$this, 'shutdown']);
}
/**
* @throws Exception
*/
public function shutdown()
{
$lastError = error_get_last();
if (empty($lastError) || $lastError['type'] !== E_ERROR) {
return;
}
$this->category = 'shutdown';
$messages = explode(PHP_EOL, $lastError['message']);
$message = array_shift($messages);
$this->sendError($message, $lastError['file'], $lastError['line']);
}
/**
* @param \Throwable $exception
*
* @throws Exception
*/
public function exceptionHandler(\Throwable $exception)
{
$this->category = 'exception';
di(EventDispatch::class)->dispatch(new OnAfterRequest());
$this->sendError($exception->getMessage(), $exception->getFile(), $exception->getLine());
}
/**
* @throws Exception
*
* 以异常形式抛出错误,防止执行后续程序
*/
public function errorHandler()
{
$error = func_get_args();
$path = ['file' => $error[2], 'line' => $error[3]];
if ($error[0] === 0) {
$error[0] = 500;
}
$data = Json::to(500, $error[1], $path);
Kiri::app()->error($data, 'error');
di(EventDispatch::class)->dispatch(new OnAfterRequest());
throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]);
}
/**
* @param $message
* @param $file
* @param $line
* @param int $code
* @return false|string
* @throws Exception
*/
public function sendError($message, $file, $line, $code = 500): bool|string
{
$path = ['file' => $file, 'line' => $line];
$data = Json::to($code, $this->category . ': ' . $message, $path);
write($data, $this->category);
return $data;
}
/**
* @return mixed
*/
public function getErrorMessage(): mixed
{
$message = $this->message;
$this->message = NULL;
return $message->getData();
}
/**
* @return bool
*/
public function getAsError(): bool
{
return $this->message !== NULL;
}
/**
* @param $message
* @param string $category
*
* @throws Exception
*/
public function writer($message, string $category = 'app')
{
Kiri::app()->debug($message, $category);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019-03-20
* Time: 10:25
*/
declare(strict_types=1);
namespace Kiri\Error;
/**
* Interface ErrorInterface
* @package Kiri\Kiri\Error
*/
interface ErrorInterface
{
/**
* @param $message
* @param $file
* @param $line
* @param int $code
* @return mixed
*/
public function sendError($message, $file, $line, $code = 500): mixed;
}
+279
View File
@@ -0,0 +1,279 @@
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019-03-22
* Time: 14:36
*/
declare(strict_types=1);
namespace Kiri\Error;
use Annotation\Inject;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Abstracts\Config;
use Kiri\Core\Json;
use Kiri\Events\EventProvider;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Server\Events\OnAfterRequest;
use Swoole\Coroutine;
use Throwable;
/**
* Class Logger
* @package Kiri\Kiri\Error
*/
class Logger extends Component
{
private array $logs = [];
/** @var EventProvider */
#[Inject(EventProvider::class)]
public EventProvider $eventProvider;
private array $sources = [];
/**
*
*/
public function init()
{
$this->eventProvider->on(OnAfterRequest::class, [$this, 'insert']);
}
/**
* @param mixed $message
* @param string $method
* @param null $file
* @throws Exception
*/
public function debug(mixed $message, string $method = 'app', $file = null)
{
if (Config::get('environment', 'pro') == 'pro') {
return;
}
$this->output($message);
}
/**
* @param mixed $message
* @param string $method
* @throws Exception
*/
public function trance(mixed $message, string $method = 'app')
{
if (Config::get('environment', 'pro') == 'pro') {
return;
}
$this->output($message);
}
/**
* @param mixed $message
* @param string $method
* @param null $file
* @throws Exception
*/
public function error(mixed $message, $method = 'error', $file = null)
{
$this->writer($message, $method);
}
/**
* @param mixed $message
* @param string $method
* @param null $file
* @throws Exception
*/
public function success(mixed $message, string $method = 'app', $file = null)
{
if (Config::get('environment', 'pro') == 'pro') {
return;
}
$this->output($message);
}
/**
* @param $message
* @param string $method
* @return void
* @throws Exception
*/
private function writer($message, string $method = 'app'): void
{
if (empty($message)) {
return;
}
$message = print_r($message, true);
$this->print_r($message, $method);
if (!is_array($this->logs)) {
$this->logs = [];
}
$this->logs[$method] = $message;
}
/**
* @param $message
* @param string $method
* @throws Exception
*/
public function print_r($message, string $method = '')
{
$debug = Config::get('debug', ['enable' => false]);
if ((bool)$debug['enable'] === true) {
if (!is_callable($debug['callback'] ?? null, true)) {
return;
}
call_user_func($debug['callback'], $message, $method);
}
}
/**
* @param $message
* @param string $method
* @throws ConfigException
*/
public function output($message, string $method = 'default')
{
if (Config::get('environment', 'dev') == 'pro') {
if ($method === 'error') {
echo $message;
}
return;
}
if (str_contains($message, 'Event::rshutdown(): Event::wait()')) {
return;
}
echo $message;
}
/**
* @param string $application
* @return mixed
*/
public function getLastError(string $application = 'app'): mixed
{
return $this->logs[$application] ?? 'Unknown error.';
}
/**
* @param string $messages
* @param string $method
* @throws Exception
*/
public function write(string $messages, string $method = 'app')
{
if (empty($messages)) {
return;
}
$to_day = date('Y-m-d');
$fileName = storage('server-' . $to_day . '.log', $dirName = 'log/' . ($method ?? 'app'));
file_put_contents($fileName, '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL);
}
/**
* @param $logFile
* @return string
*/
private function getSource($logFile): string
{
if (!file_exists($logFile)) {
Coroutine\System::exec('echo 3 > /proc/sys/vm/drop_caches');
touch($logFile);
}
if (is_writeable($logFile)) {
$logFile = realpath($logFile);
}
return $logFile;
}
/**
* @throws Exception
* 写入日志
*/
public function insert()
{
if (empty($this->logs)) {
return;
}
foreach ($this->logs as $method => $message) {
$this->write($message, $method);
}
$this->logs = [];
}
/**
* @return array
*/
public function clear(): array
{
return $this->logs = [];
}
/**
* @param $data
* @return string
*/
private function arrayFormat($data): string
{
if (is_string($data)) {
return $data;
}
if ($data instanceof Throwable) {
$data = $this->getException($data);
} else if (is_object($data)) {
$data = get_object_vars($data);
}
return Json::encode($data);
}
/**
* @param Throwable $exception
* @return mixed
* @throws Exception
*/
public function exception(Throwable $exception): mixed
{
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
$logger = Kiri::app()->getLogger();
$logger->write(jTraceEx($exception), 'exception');
return Json::to($code, $exception->getMessage(), [
'file' => $exception->getFile(),
'line' => $exception->getLine()
]);
}
/**
* @param Throwable $exception
* @return array
*/
private function getException(Throwable $exception): array
{
$filetype = [$exception->getMessage()];
$filetype[] = $exception->getFile() . ' on line ' . $exception->getLine();
$filetype[] = $exception->getTrace();
return $filetype;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace Kiri\Error;
use Kiri\IAspect;
/**
* Class LoggerAspect
* @package Kiri\Error
*/
class LoggerAspect implements IAspect
{
private string $className = '';
private string $methodName = '';
/**
* @param mixed $handler
* @param array $params
* @return mixed
*/
public function invoke(mixed $handler, array $params = []): mixed
{
$startTime = microtime(true);
$data = call_user_func($handler, ...$params);
$this->print_runtime($handler, $startTime);
return $data;
}
/**
* @param $handler
* @param $startTime
*/
private function print_runtime($handler, $startTime)
{
$className = $handler[0]::class;
$methodName = $handler[1];
$runTime = round(microtime(true) - $startTime, 6);
echo sprintf('run %s::%s use time %6f', $className, $methodName, $runTime);
echo PHP_EOL;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace Kiri\Error;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Core\Json;
use Kiri\Exception\ComponentException;
use Kiri\Kiri;
use Swoole\Coroutine;
use Swoole\Process;
use Server\Abstracts\CustomProcess;
/**
* Class LoggerProcess
* @package Kiri\Error
*/
class LoggerProcess extends CustomProcess
{
/**
* @param Process $process
* @return string
*/
#[Pure] public function getProcessName(Process $process): string
{
// TODO: Implement getProcessName() method.
return get_called_class();
}
/**
* @param Process $process
* @throws ComponentException
*/
public function onHandler(Process $process): void
{
// TODO: Implement onHandler() method.
$this->message($process);
}
/**
* @param Process $process
* @throws ComponentException
* @throws Exception
*/
public function message(Process $process)
{
if ($this->checkProcessIsStop()) {
$this->exit();
return;
}
$message = Json::decode($process->read());
if (!empty($message)) {
Kiri::writeFile($this->getDirName($message), $message[0], FILE_APPEND);
$this->checkLogFile($message[1]);
}
Coroutine\System::sleep(1);
$this->message($process);
}
/**
* @param $message
* @return string
* @throws Exception
*/
private function getDirName($message): string
{
return storage('server-' . date('Y-m-d') . '.log', $message[1]);
}
/**
* @param $dirName
* @throws Exception
*/
private function checkLogFile($dirName)
{
$files = new \DirectoryIterator(storage(null, $dirName));
if ($files->getSize() < 15) {
return;
}
Coroutine\System::exec('find ' . storage(null, $dirName) . '/ -mtime +15 -name "*.log" -exec rm -rf {} \;');
}
}