Files
kiri-core/core/Error/Logger.php
T
2021-08-24 19:11:14 +08:00

119 lines
2.0 KiB
PHP

<?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 Psr\Log\LoggerInterface;
use Swoole\Coroutine;
use Throwable;
/**
* Class Logger
* @package Kiri\Kiri\Error
* @mixin \Kiri\Abstracts\Logger
*/
class Logger extends Component
{
private array $logs = [];
/** @var EventProvider */
#[Inject(EventProvider::class)]
public EventProvider $eventProvider;
/**
* inject logger
*
* @var LoggerInterface
*/
#[Inject(LoggerInterface::class)]
public LoggerInterface $logger;
private array $sources = [];
/**
* @param string $application
* @return string
*/
public function getLastError(string $application = 'app'): string
{
return '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);
}
/**
* @throws Exception
* 写入日志
*/
public function insert()
{
if (empty($this->logs)) {
return;
}
foreach ($this->logs as $method => $message) {
$this->write($message, $method);
}
$this->logs = [];
}
/**
* @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()
]);
}
}