This commit is contained in:
as2252258@163.com
2021-04-23 03:38:26 +08:00
parent a5a607495f
commit 1edd8c5429
15 changed files with 264 additions and 278 deletions
-1
View File
@@ -29,7 +29,6 @@ class OnClose extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
logger_insert();
}); });
$clientInfo = $server->getClientInfo($fd); $clientInfo = $server->getClientInfo($fd);
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
-1
View File
@@ -28,7 +28,6 @@ class OnConnect extends Callback
{ {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
logger_insert();
}); });
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
-1
View File
@@ -29,7 +29,6 @@ class OnFinish extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
logger_insert();
}); });
fire(Event::TASK_FINISH, [$task_id, $data]); fire(Event::TASK_FINISH, [$task_id, $data]);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
-1
View File
@@ -99,7 +99,6 @@ class OnHandshake extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_CLEAN); fire(Event::SYSTEM_RESOURCE_CLEAN);
logger_insert();
}); });
$this->execute($request, $response); $this->execute($request, $response);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
-1
View File
@@ -40,7 +40,6 @@ class OnMessage extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_CLEAN); fire(Event::SYSTEM_RESOURCE_CLEAN);
logger_insert();
}); });
if ($frame->opcode === 0x08) { if ($frame->opcode === 0x08) {
return; return;
-1
View File
@@ -38,7 +38,6 @@ class OnPacket extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
\logger_insert();
}); });
$request = $this->_request($clientInfo, $server, $data); $request = $this->_request($clientInfo, $server, $data);
-1
View File
@@ -28,7 +28,6 @@ class OnPipeMessage extends Callback
{ {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
logger_insert();
}); });
match ($swollen_universalize['action'] ?? null) { match ($swollen_universalize['action'] ?? null) {
'kafka' => $this->onKafkaWorker($swollen_universalize), 'kafka' => $this->onKafkaWorker($swollen_universalize),
-1
View File
@@ -50,7 +50,6 @@ class OnReceive extends Callback
try { try {
defer(function (){ defer(function (){
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
\logger_insert();
}); });
$request = $this->_request($fd, $data, $reID); $request = $this->_request($fd, $data, $reID);
if (($node = $this->router->find_path($request)) === null) { if (($node = $this->router->find_path($request)) === null) {
+1 -3
View File
@@ -34,7 +34,6 @@ class OnRequest extends Callback
public function init() public function init()
{ {
$this->event = Snowflake::app()->getEvent(); $this->event = Snowflake::app()->getEvent();
$this->logger = Snowflake::app()->getLogger();
} }
@@ -48,8 +47,7 @@ class OnRequest extends Callback
{ {
try { try {
defer(function () { defer(function () {
$this->event->trigger(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
$this->logger->insert();
}); });
/** @var HRequest $request */ /** @var HRequest $request */
[$request, $response] = OnRequest::createContext($request, $response); [$request, $response] = OnRequest::createContext($request, $response);
-1
View File
@@ -104,7 +104,6 @@ class OnTask extends Callback
try { try {
defer(function () { defer(function () {
fire(Event::SYSTEM_RESOURCE_CLEAN); fire(Event::SYSTEM_RESOURCE_CLEAN);
logger_insert();
}); });
$serialize = $this->before($data); $serialize = $this->before($data);
if ($serialize === null) { if ($serialize === null) {
-2
View File
@@ -36,8 +36,6 @@ class OnWorkerError extends Callback
); );
write($message, 'worker-exit'); write($message, 'worker-exit');
logger_insert();
} }
} }
+12 -13
View File
@@ -17,22 +17,21 @@ use Swoole\Timer;
class OnWorkerExit extends Callback class OnWorkerExit extends Callback
{ {
/** /**
* @param $server * @param $server
* @param $worker_id * @param $worker_id
* @throws Exception * @throws Exception
*/ */
public function onHandler($server, $worker_id) public function onHandler($server, $worker_id)
{ {
putenv('state=exit'); putenv('state=exit');
$event = Snowflake::app()->getEvent();
$channel = Snowflake::app()->getChannel(); $channel = Snowflake::app()->getChannel();
$channel->cleanAll(); $channel->cleanAll();
$event = Snowflake::app()->getEvent(); $event->trigger(Event::SERVER_WORKER_EXIT);
$event->trigger(Event::SERVER_WORKER_EXIT);
logger_insert(); logger()->insert();
} }
} }
+2 -2
View File
@@ -32,9 +32,9 @@ class OnWorkerStop extends Callback
$this->clearMysqlClient(); $this->clearMysqlClient();
$this->clearRedisClient(); $this->clearRedisClient();
Timer::clearAll(); fire(Event::SYSTEM_RESOURCE_CLEAN);
logger_insert(); Timer::clearAll();
} }
} }
+249 -237
View File
@@ -14,6 +14,7 @@ use HttpServer\Http\Context;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Core\Json; use Snowflake\Core\Json;
use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Coroutine\Channel; use Swoole\Coroutine\Channel;
@@ -27,266 +28,277 @@ use Throwable;
class Logger extends Component class Logger extends Component
{ {
private array $logs = []; private array $logs = [];
/** public function init()
* @param $message {
* @param string $method $event = Snowflake::app()->getEvent();
* @param null $file $event->on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'insert']);
* @throws Exception $event->on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'insert']);
*/ }
public function debug(mixed $message, string $method = 'app', $file = null)
{
$this->writer($message, $method);
}
/** /**
* @param $message * @param $message
* @param string $method * @param string $method
* @throws Exception * @param null $file
*/ * @throws Exception
public function trance($message, $method = 'app') */
{ public function debug(mixed $message, string $method = 'app', $file = null)
$this->writer($message, $method); {
} $this->writer($message, $method);
}
/** /**
* @param $message * @param $message
* @param string $method * @param string $method
* @param null $file * @throws Exception
* @throws Exception */
*/ public function trance($message, $method = 'app')
public function error(mixed $message, $method = 'error', $file = null) {
{ $this->writer($message, $method);
$this->writer($message, $method); }
}
/**
* @param $message
* @param string $method
* @param null $file
* @throws Exception
*/
public function success(mixed $message, $method = 'app', $file = null)
{
$this->writer($message, $method);
}
/**
* @param $message
* @param string $method
* @return string
* @throws Exception
*/
private function writer($message, $method = 'app'): string
{
$this->print_r($message, $method);
if ($message instanceof Throwable) {
$message = $message->getMessage();
} else {
if (is_array($message) || is_object($message)) {
$message = $this->arrayFormat($message);
}
}
if (is_array($message)) {
$message = $this->arrayFormat($message);
}
if (!empty($message)) {
$this->write($message, $method);
}
return $message;
}
/** /**
* @param $message * @param $message
* @param $method * @param string $method
* @throws Exception * @param null $file
*/ * @throws Exception
public function print_r($message, $method = '') */
{ public function error(mixed $message, $method = 'error', $file = null)
$debug = Config::get('debug', ['enable' => false]); {
if ((bool)$debug['enable'] === true) { $this->writer($message, $method);
if (!is_callable($debug['callback'] ?? null, true)) { }
return;
} /**
call_user_func($debug['callback'], $message, $method); * @param $message
} * @param string $method
} * @param null $file
* @throws Exception
*/
public function success(mixed $message, $method = 'app', $file = null)
{
$this->writer($message, $method);
}
/**
* @param $message
* @param string $method
* @return string
* @throws Exception
*/
private function writer($message, $method = 'app'): string
{
$this->print_r($message, $method);
if ($message instanceof Throwable) {
$message = $message->getMessage();
} else {
if (is_array($message) || is_object($message)) {
$message = $this->arrayFormat($message);
}
}
if (is_array($message)) {
$message = $this->arrayFormat($message);
}
if (!empty($message)) {
if (!is_array($this->logs)) {
$this->logs = [];
}
$this->logs[] = [$method, $message];
}
return $message;
}
/** /**
* @param $message * @param $message
*/ * @param $method
public function output($message) * @throws Exception
{ */
if (str_contains($message, 'Event::rshutdown(): Event::wait()')) { public function print_r($message, $method = '')
return; {
} $debug = Config::get('debug', ['enable' => false]);
echo $message; if ((bool)$debug['enable'] === true) {
} if (!is_callable($debug['callback'] ?? null, true)) {
return;
}
call_user_func($debug['callback'], $message, $method);
}
}
/** /**
* @param string $application * @param $message
* @return mixed */
*/ public function output($message)
public function getLastError($application = 'app'): mixed {
{ if (str_contains($message, 'Event::rshutdown(): Event::wait()')) {
$filetype = []; return;
foreach ($this->logs as $key => $val) { }
if ($val[0] != $application) { echo $message;
continue; }
}
$filetype[] = $val[1];
}
if (empty($filetype)) {
return 'Unknown error.';
}
return end($filetype);
}
/**
* @param $messages
* @param string $method
* @throws
*/
public function write(string $messages, $method = 'app')
{
if (empty($messages)) {
return;
}
$fileName = 'server-' . date('Y-m-d') . '.log';
$dirName = 'log/' . (empty($method) ? 'app' : $method);
$logFile = '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL;
Snowflake::writeFile(storage($fileName, $dirName), $logFile, FILE_APPEND);
$files = glob(storage(null, $dirName) . '/*');
if (count($files) >= 15) {
$command = 'find ' . storage(null, $dirName) . '/ -mtime +15 -name "*.log" -exec rm -rf {} \;';
if (Context::inCoroutine()) {
Coroutine\System::exec($command);
} else {
\shell_exec($command);
}
}
}
/**
* @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 * @param string $application
* 写入日志 * @return mixed
*/ */
public function insert() public function getLastError($application = 'app'): mixed
{ {
if (empty($this->logs)) { $filetype = [];
return; foreach ($this->logs as $key => $val) {
} if ($val[0] != $application) {
foreach ($this->logs as $log) { continue;
[$method, $message] = $log; }
$this->write($message, $method); $filetype[] = $val[1];
} }
$this->logs = []; if (empty($filetype)) {
} return 'Unknown error.';
}
return end($filetype);
}
/** /**
* @return array * @param $messages
*/ * @param string $method
public function clear(): array * @throws
{ */
return $this->logs = []; public function write(string $messages, $method = 'app')
} {
if (empty($messages)) {
return;
}
/** $fileName = 'server-' . date('Y-m-d') . '.log';
* @param $data $dirName = 'log/' . (empty($method) ? 'app' : $method);
* @return string $logFile = '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL;
*/ Snowflake::writeFile(storage($fileName, $dirName), $logFile, FILE_APPEND);
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);
}
$filetype = []; $files = glob(storage(null, $dirName) . '/*');
foreach ($data as $key => $val) { if (count($files) >= 15) {
if (is_array($val)) { $command = 'find ' . storage(null, $dirName) . '/ -mtime +15 -name "*.log" -exec rm -rf {} \;';
$filetype[] = $this->arrayFormat($val); if (Context::inCoroutine()) {
} else { Coroutine\System::exec($command);
$filetype[] = (is_string($key) ? $key . ' : ' : '') . $val; } else {
} \shell_exec($command);
} }
return implode(PHP_EOL, $filetype); }
} }
/**
* @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;
}
/** /**
* @param Throwable $exception * @throws Exception
* @return mixed * 写入日志
* @throws Exception */
*/ public function insert()
public function exception(Throwable $exception): mixed {
{ if (empty($this->logs)) {
$errorInfo = [ return;
'message' => $exception->getMessage(), }
'file' => $exception->getFile(), foreach ($this->logs as $log) {
'line' => $exception->getLine() [$method, $message] = $log;
]; $this->write($message, $method);
$this->error(var_export($errorInfo, true)); }
$this->logs = [];
}
$code = $exception->getCode() == 0 ? 500 : $exception->getCode(); /**
* @return array
*/
public function clear(): array
{
return $this->logs = [];
}
$logger = Snowflake::app()->getLogger(); /**
* @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);
}
$string = 'Exception: ' . PHP_EOL; $filetype = [];
$string .= '#. message: ' . $errorInfo['message'] . PHP_EOL; foreach ($data as $key => $val) {
$string .= '#. file: ' . $errorInfo['file'] . PHP_EOL; if (is_array($val)) {
$string .= '#. line: ' . $errorInfo['line'] . PHP_EOL; $filetype[] = $this->arrayFormat($val);
} else {
$logger->write($string . $exception->getTraceAsString(), 'trace'); $filetype[] = (is_string($key) ? $key . ' : ' : '') . $val;
$logger->write(jTraceEx($exception), 'exception'); }
}
return Json::to($code, $errorInfo['message'], [ return implode(PHP_EOL, $filetype);
'file' => $exception->getFile(), }
'line' => $exception->getLine()
]);
}
/** /**
* @param Throwable $exception * @param Throwable $exception
* @return array * @return mixed
*/ * @throws Exception
private function getException(Throwable $exception): array */
{ public function exception(Throwable $exception): mixed
$filetype = [$exception->getMessage()]; {
$filetype[] = $exception->getFile() . ' on line ' . $exception->getLine(); $errorInfo = [
$filetype[] = $exception->getTrace(); 'message' => $exception->getMessage(),
return $filetype; 'file' => $exception->getFile(),
} 'line' => $exception->getLine()
];
$this->error(var_export($errorInfo, true));
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
$logger = Snowflake::app()->getLogger();
$string = 'Exception: ' . PHP_EOL;
$string .= '#. message: ' . $errorInfo['message'] . PHP_EOL;
$string .= '#. file: ' . $errorInfo['file'] . PHP_EOL;
$string .= '#. line: ' . $errorInfo['line'] . PHP_EOL;
$logger->write($string . $exception->getTraceAsString(), 'trace');
$logger->write(jTraceEx($exception), 'exception');
return Json::to($code, $errorInfo['message'], [
'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;
}
} }
-12
View File
@@ -426,18 +426,6 @@ if (!function_exists('logger')) {
} }
} }
if (!function_exists('logger_insert')) {
/**
* @throws Exception
*/
function logger_insert(): void
{
Snowflake::app()->getLogger()->insert();
}
}
if (!function_exists('get_file_extension')) { if (!function_exists('get_file_extension')) {
function get_file_extension($filename) function get_file_extension($filename)