核心库新增公共helpers与LogHelper

This commit is contained in:
堂吉诃德拉曼查的英豪
2026-08-06 11:37:04 +08:00
parent dd2b32cc95
commit 977a42d40c
3 changed files with 241 additions and 1 deletions

80
src/Library/LogHelper.php Normal file
View 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;
}
}