scau009/deferred-logger-bundle
Composer 安装命令:
composer require scau009/deferred-logger-bundle
包简介
Symfony bundle for deferred logging with distributed tracing support (W3C Trace Context, Jaeger, Zipkin compatible)
关键字:
README 文档
README
Install
Require the bundle via composer (when published) or add to your composer.json and composer install.
Register bundle in config/bundles.php:
return [ Barry\DeferredLoggerBundle\BarryDeferredLoggerBundle::class => ['all' => true], ];
Configure (optional)
# config/packages/barry_deferred_logger.yaml barry_deferred_logger: logger_channel: app auto_flush_on_exception: true auto_flush_on_request: true enable_sql_logging: false # Enable automatic Doctrine SQL logging inject_trace_id_in_response: true # Inject trace ID in response headers enable_messenger_trace: true # Enable Messenger trace propagation
Features
1. Automatic SQL Logging
When enable_sql_logging: true, the bundle automatically captures all Doctrine SQL queries with:
- Original SQL statement
- Query parameters
- Formatted SQL (with parameters interpolated for readability)
- Execution time in milliseconds
No need to manually call DeferredLogger::contextSql() anymore!
2. Distributed Tracing Support
The bundle provides production-ready distributed tracing with the following features:
Trace Context Propagation
Automatically extracts trace IDs from incoming requests, supporting multiple standards:
- W3C Trace Context (
traceparentheader) - Industry standard - X-Trace-ID - Common in microservices
- X-Request-ID - Used by Nginx, load balancers
- X-Correlation-ID - Alternative correlation header
If no trace ID is found, a new one is automatically generated.
Response Header Injection
When inject_trace_id_in_response: true (default), the bundle adds trace headers to every response:
X-Trace-ID: 550e8400e29b41d4a716446655440000 X-Span-ID: 7f3a9e4c6b2d8f1a traceparent: 00-550e8400e29b41d4a716446655440000-7f3a9e4c6b2d8f1a-01
This allows:
- Frontend clients to correlate requests with logs
- API consumers to trace requests across microservices
- Debugging tools to link distributed operations
Microservices Integration
Service A → Service B example:
// Service A: Making a request to Service B $traceId = DeferredLogger::getTraceId(); $response = $httpClient->request('POST', 'https://service-b/api/endpoint', [ 'headers' => [ 'X-Trace-ID' => $traceId, // Pass trace ID to downstream service ], ]);
Service B will automatically pick up the trace ID from the header and use it in its logs!
Long-Running Process Support (Swoole/RoadRunner)
The bundle properly resets trace context on each request:
// StartRequestSubscriber automatically calls: $instance->reset(); // Clear buffer and trace context $traceContext = TraceContext::fromHeaders($request->headers->all()); $instance->setTraceContext($traceContext);
Log Output Format
All logs include comprehensive trace information:
{
"trace_id": "550e8400e29b41d4a716446655440000",
"span_id": "7f3a9e4c6b2d8f1a",
"parent_span_id": null,
"sampled": true,
"info": [...]
}
Integration with Tracing Systems
The trace format is compatible with:
- Jaeger - Uber's distributed tracing system
- Zipkin - Twitter's distributed tracing system
- AWS X-Ray - Amazon's tracing service
- Google Cloud Trace - GCP tracing service
- Any system supporting W3C Trace Context
Best Practices
- API Gateway: Extract trace ID from incoming requests or generate at the edge
- Propagate Downstream: Always pass
X-Trace-IDto downstream services - Log Aggregation: Use trace_id to group logs across services (e.g., ELK, Datadog)
- Frontend Integration: Return trace ID to clients for support tickets
- Monitoring: Create dashboards grouped by trace_id for request flow visualization
3. Symfony Messenger Integration
Automatic trace propagation across async messages!
When enable_messenger_trace: true (default), the bundle automatically:
How It Works
- Message Dispatch: When you dispatch a message, the current trace context is automatically attached as a
TraceContextStamp - Async Processing: When a worker processes the message, the trace context is restored
- Child Spans: Async operations create child spans, maintaining the parent-child relationship
Example
// In your HTTP controller (Request A) use Symfony\Component\Messenger\MessageBusInterface; public function processOrder(MessageBusInterface $bus): Response { // Current trace_id: 550e8400-e29b-41d4-a716-446655440000 // Current span_id: 7f3a9e4c6b2d8f1a DeferredLogger::contextInfo('Dispatching order processing'); // Dispatch async message - trace context is AUTOMATICALLY attached $bus->dispatch(new ProcessOrderMessage($orderId)); return new JsonResponse(['status' => 'queued']); }
// In your Message Handler (Async Worker) use Symfony\Component\Messenger\Attribute\AsMessageHandler; #[AsMessageHandler] class ProcessOrderHandler { public function __invoke(ProcessOrderMessage $message): void { // Trace context is AUTOMATICALLY restored! // trace_id: 550e8400-e29b-41d4-a716-446655440000 (SAME as parent) // span_id: a1b2c3d4e5f6g7h8 (NEW child span) // parent_span_id: 7f3a9e4c6b2d8f1a (points to parent) DeferredLogger::contextInfo('Processing order in async worker'); // All logs here will have the SAME trace_id as the original request! } }
Benefits
- Cross-Process Tracing: Track requests from HTTP handler through async workers
- No Manual Work: Zero code changes needed, works automatically
- Worker Isolation: Each message gets its own span, properly cleaned up after processing
- Queue Debugging: Find all logs related to a specific message across multiple workers
Configuration
barry_deferred_logger: enable_messenger_trace: true # Enabled by default
Advanced: Manual Trace Control
If needed, you can access trace info in handlers:
#[AsMessageHandler] class MyHandler { public function __invoke(MyMessage $message): void { $traceId = DeferredLogger::getTraceId(); // Make external API call with trace propagation $this->httpClient->request('POST', 'https://external-api.com', [ 'headers' => ['X-Trace-ID' => $traceId], ]); } }
Trace Flow Visualization
HTTP Request (trace: 550e8400)
└─ span: 7f3a9e4c
├─ Log: "Order received"
├─ Dispatch Message ✉
└─ Response sent
Async Worker (trace: 550e8400) ← SAME trace_id!
└─ span: a1b2c3d4 (parent: 7f3a9e4c)
├─ Log: "Processing order"
├─ SQL: UPDATE orders...
└─ Log: "Order completed"
All logs searchable by trace_id: 550e8400 in your log aggregation system!
scau009/deferred-logger-bundle 适用场景与选型建议
scau009/deferred-logger-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 10 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「logging」 「symfony」 「monolog」 「doctrine」 「W3C」 「Messenger」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 scau009/deferred-logger-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 scau009/deferred-logger-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 scau009/deferred-logger-bundle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A GeoIP decorator/processor for monolog
The bundle for easy using json-rpc api on your project
A Zend Framework module that sets up Monolog for logging in applications.
Laravel 5.6 Monolog custom telegram channel
A Monolog processor to add X-Request-Id or UNIQUE_ID env to monolog stack if present, provide a default one otherwise. Optionally, add a forwarded request-id list.
PSR-3 compatible logger with dynamic file naming and hourly rotation, powered by Monolog
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 33
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-29