This commit is contained in:
2021-07-12 11:24:33 +08:00
parent 20fbbeb666
commit 99f7ebd712
+286 -262
View File
@@ -10,15 +10,12 @@ declare(strict_types=1);
namespace Snowflake\Error; namespace Snowflake\Error;
use Exception; use Exception;
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\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use Swoole\Process;
use Throwable; use Throwable;
/** /**
@@ -28,301 +25,328 @@ use Throwable;
class Logger extends Component class Logger extends Component
{ {
private array $logs = []; private array $logs = [];
private array $sources = []; private array $sources = [];
public function init() public function init()
{ {
Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'insert']); Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'insert']);
Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'closeSource']); Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'closeSource']);
Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'closeSource']); Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'closeSource']);
Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'insert']); Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'insert']);
} }
/** /**
* @param mixed $message * @param mixed $message
* @param string $method * @param string $method
* @param null $file * @param null $file
* @throws Exception * @throws Exception
*/ */
public function debug(mixed $message, string $method = 'app', $file = null) public function debug(mixed $message, string $method = 'app', $file = null)
{ {
$this->writer($message, $method); $this->writer($message, $method);
} }
/** /**
* @param mixed $message * @param mixed $message
* @param string $method * @param string $method
* @throws Exception * @throws Exception
*/ */
public function trance(mixed $message, string $method = 'app') public function trance(mixed $message, string $method = 'app')
{ {
$this->writer($message, $method); $this->writer($message, $method);
} }
/** /**
* @param mixed $message * @param mixed $message
* @param string $method * @param string $method
* @param null $file * @param null $file
* @throws Exception * @throws Exception
*/ */
public function error(mixed $message, $method = 'error', $file = null) public function error(mixed $message, $method = 'error', $file = null)
{ {
$this->writer($message, $method); $this->writer($message, $method);
} }
/** /**
* @param mixed $message * @param mixed $message
* @param string $method * @param string $method
* @param null $file * @param null $file
* @throws Exception * @throws Exception
*/ */
public function success(mixed $message, string $method = 'app', $file = null) public function success(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
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function writer($message, string $method = 'app'): string private function writer($message, string $method = 'app'): string
{ {
$this->print_r($message, $method); $this->print_r($message, $method);
if ($message instanceof Throwable) { if ($message instanceof Throwable) {
$message = $message->getMessage(); $message = $message->getMessage();
} else { } else {
if (is_array($message) || is_object($message)) { if (is_array($message) || is_object($message)) {
$message = $this->arrayFormat($message); $message = $this->arrayFormat($message);
} }
} }
if (is_array($message)) { if (is_array($message)) {
$message = $this->arrayFormat($message); $message = $this->arrayFormat($message);
} }
if (!empty($message)) { if (!empty($message)) {
if (!is_array($this->logs)) { if (!is_array($this->logs)) {
$this->logs = []; $this->logs = [];
} }
$this->logs[] = [$method, $message]; $this->logs[] = [$method, $message];
} }
return $message; return $message;
} }
/** /**
* @param $message * @param $message
* @param string $method * @param string $method
* @throws Exception * @throws Exception
*/ */
public function print_r($message, string $method = '') public function print_r($message, string $method = '')
{ {
$debug = Config::get('debug', ['enable' => false]); $debug = Config::get('debug', ['enable' => false]);
if ((bool)$debug['enable'] === true) { if ((bool)$debug['enable'] === true) {
if (!is_callable($debug['callback'] ?? null, true)) { if (!is_callable($debug['callback'] ?? null, true)) {
return; return;
} }
call_user_func($debug['callback'], $message, $method); call_user_func($debug['callback'], $message, $method);
} }
} }
/** /**
* @param $message * @param $message
*/ */
public function output($message) public function output($message)
{ {
if (str_contains($message, 'Event::rshutdown(): Event::wait()')) { if (str_contains($message, 'Event::rshutdown(): Event::wait()')) {
return; return;
} }
echo $message; echo $message;
} }
/** /**
* @param string $application * @param string $application
* @return mixed * @return mixed
*/ */
public function getLastError(string $application = 'app'): mixed public function getLastError(string $application = 'app'): mixed
{ {
$filetype = []; $filetype = [];
foreach ($this->logs as $key => $val) { foreach ($this->logs as $key => $val) {
if ($val[0] != $application) { if ($val[0] != $application) {
continue; continue;
} }
$filetype[] = $val[1]; $filetype[] = $val[1];
} }
if (empty($filetype)) { if (empty($filetype)) {
return 'Unknown error.'; return 'Unknown error.';
} }
return end($filetype); return end($filetype);
} }
/** /**
* @param string $messages * @param string $messages
* @param string $method * @param string $method
* @throws Exception * @throws Exception
*/ */
public function write(string $messages, string $method = 'app') public function write(string $messages, string $method = 'app')
{ {
return; if (empty($messages)) {
if (empty($messages)) { return;
} }
$dirName = 'log/' . ($method ?? 'app'); $to_day = date('Y-m-d');
$fileName = storage('server-' . date('Y-m-d') . '.log', $dirName); $dirName = 'log/' . ($method ?? 'app');
if (!isset($this->sources[$fileName])) { if (!isset($this->sources[$to_day])) {
$this->sources[$fileName] = fopen($fileName, 'rw'); $this->sources[$to_day] = [];
} }
fwrite($this->sources[$fileName], '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL);
$this->clearHistoryFile($dirName); $fileName = storage('server-' . $to_day . '.log', $dirName);
} if (!isset($this->sources[$to_day][$fileName])) {
$this->sources[$to_day][$fileName] = fopen($fileName, 'rw');
}
fwrite($this->sources[$fileName], '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL);
$this->clearHistoryFile($dirName);
$this->clearPrevLog($to_day);
}
/** /**
* 清理文件资源 * 清理文件资源
*/ */
public function closeSource() public function closeSource()
{ {
foreach ($this->sources as $source) { foreach ($this->sources as $source) {
fclose($source); fclose($source);
} }
$this->sources = []; $this->sources = [];
} }
/** /**
* @param string $dirName * @param $to_day
* @throws \Exception */
*/ public function clearPrevLog($to_day)
private function clearHistoryFile(string $dirName) {
{ if (count($this->sources) > 1) {
$command = 'find ' . storage(null, $dirName) . '/ -mtime +15 -name "*.log" -exec rm -rf {} \;'; foreach ($this->sources as $day => $source) {
if ($day == $to_day) {
Coroutine::getCid() !== -1 ? Coroutine\System::exec($command) : \shell_exec($command); continue;
} }
foreach ($source as $value) {
fclose($value);
}
unset($this->sources[$day]);
}
}
}
/** /**
* @param $logFile * @param string $dirName
* @return string * @throws \Exception
*/ */
private function getSource($logFile): string private function clearHistoryFile(string $dirName)
{ {
if (!file_exists($logFile)) { $command = 'find ' . storage(null, $dirName) . '/ -mtime +15 -name "*.log" -exec rm -rf {} \;';
Coroutine\System::exec('echo 3 > /proc/sys/vm/drop_caches');
touch($logFile); Coroutine::getCid() !== -1 ? Coroutine\System::exec($command) : \shell_exec($command);
} }
if (is_writeable($logFile)) {
$logFile = realpath($logFile);
}
return $logFile;
}
/** /**
* @throws Exception * @param $logFile
* 写入日志 * @return string
*/ */
public function insert() private function getSource($logFile): string
{ {
if (empty($this->logs)) { if (!file_exists($logFile)) {
return; Coroutine\System::exec('echo 3 > /proc/sys/vm/drop_caches');
} touch($logFile);
foreach ($this->logs as $log) { }
[$method, $message] = $log; if (is_writeable($logFile)) {
$this->write($message, $method); $logFile = realpath($logFile);
} }
$this->logs = []; return $logFile;
} }
/**
* @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);
}
$filetype = [];
foreach ($data as $key => $val) {
if (is_array($val)) {
$filetype[] = $this->arrayFormat($val);
} else {
$filetype[] = (is_string($key) ? $key . ' : ' : '') . $val;
}
}
return implode(PHP_EOL, $filetype);
}
/** /**
* @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;
}
} }