香洲二院小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mini_xzey/app/Utils/Traits/Logger.php

115 lines
2.3 KiB

<?php
declare(strict_types=1);
namespace App\Utils\Traits;
use Illuminate\Support\Facades\Log;
use Monolog\Level;
use Psr\Log\LoggerInterface;
trait Logger
{
/**
* Logger channel name.
*
* @var string
*/
public string $channel = 'default';
/**
* Logger 实例
*
* @var LoggerInterface|null
*/
public LoggerInterface|null $logger = NULL;
/**
* UUID
* @var string
*/
protected string $uuid = '';
/**
* Get Logger
*
* @return LoggerInterface
*/
public function getLogger(): LoggerInterface
{
if (is_null($this->logger)) {
$this->logger = $this->createLogger();
$this->uuid = $this->uuid();
}
return $this->logger;
}
/**
* Create Logger.
*
* @return LoggerInterface
*/
public function createLogger(): LoggerInterface
{
return Log::channel($this->channel);
}
/**
* Set Channel.
*
* @param string $channel
*
* @return void
*/
public function setChannel(string $channel): void
{
$this->channel = $channel;
}
/**
* Create uuid
* @return string
*/
protected function uuid(): string
{
$chars = md5(uniqid((string)mt_rand(), true));
return substr ( $chars, 0, 8 ) . '-'
. substr ( $chars, 8, 4 ) . '-'
. substr ( $chars, 12, 4 ) . '-'
. substr ( $chars, 16, 4 ) . '-'
. substr ( $chars, 20, 12 );
}
public function debug(string $message, array $context = []): void
{
$this->getLogger()->debug('['. $this->uuid. ']'.$message, $context);
}
public function info(string $message, array $context = []): void
{
$this->getLogger()->info('['. $this->uuid. ']'.$message, $context);
}
public function notice(string $message, array $context = []): void
{
$this->getLogger()->notice('['. $this->uuid. ']'.$message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->getLogger()->warning('['. $this->uuid. ']'.$message, $context);
}
public function error(string $message, array $context = []): void
{
$this->getLogger()->error('['. $this->uuid. ']'.$message, $context);
}
}