核心库新增公共helpers与LogHelper
This commit is contained in:
80
src/Library/LogHelper.php
Normal file
80
src/Library/LogHelper.php
Normal file
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Dhd\Micro\Core\Library;
|
||||
|
||||
use Hyperf\Context\ApplicationContext;
|
||||
use Hyperf\Logger\LoggerFactory;
|
||||
use Hyperf\Rpc\Context as RpcContext;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* 统一日志静态入口,支持 trace_id 注入与多通道.
|
||||
*/
|
||||
class LogHelper
|
||||
{
|
||||
public static function error(string $message, array $context = []): void
|
||||
{
|
||||
self::log('error', $message, $context, 'error');
|
||||
}
|
||||
|
||||
public static function warning(string $message, array $context = []): void
|
||||
{
|
||||
self::log('warning', $message, $context);
|
||||
}
|
||||
|
||||
public static function info(string $message, array $context = []): void
|
||||
{
|
||||
self::log('info', $message, $context);
|
||||
}
|
||||
|
||||
public static function debug(string $message, array $context = []): void
|
||||
{
|
||||
self::log('debug', $message, $context);
|
||||
}
|
||||
|
||||
public static function business(string $message, array $context = []): void
|
||||
{
|
||||
self::log('info', $message, $context, 'business');
|
||||
}
|
||||
|
||||
public static function sql(string $sql, array $bindings = [], float $time = 0): void
|
||||
{
|
||||
$message = sprintf('SQL: %s | Bindings: %s | Time: %.2fms', $sql, json_encode($bindings), $time);
|
||||
self::log('debug', $message, [], 'sql');
|
||||
}
|
||||
|
||||
protected static function log(string $level, string $message, array $context = [], string $channel = 'default'): void
|
||||
{
|
||||
$logger = self::getLogger($channel);
|
||||
$enrichedContext = array_merge($context, self::getTraceContext());
|
||||
$logger->log($level, $message, $enrichedContext);
|
||||
}
|
||||
|
||||
protected static function getLogger(string $channel = 'default'): LoggerInterface
|
||||
{
|
||||
$container = ApplicationContext::getContainer();
|
||||
$loggerFactory = $container->get(LoggerFactory::class);
|
||||
return $loggerFactory->get($channel);
|
||||
}
|
||||
|
||||
protected static function getTraceContext(): array
|
||||
{
|
||||
$context = [];
|
||||
|
||||
try {
|
||||
$container = ApplicationContext::getContainer();
|
||||
$rpcContext = $container->get(RpcContext::class);
|
||||
|
||||
$traceId = $rpcContext->get('trace_id');
|
||||
if ($traceId) {
|
||||
$context['trace_id'] = $traceId;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// 上下文不可用时静默降级
|
||||
}
|
||||
|
||||
return $context;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user