Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Logging Bundle Laravel Package

dayspring-tech/logging-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require dayspring-tech/logging-bundle
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="DayspringTech\LoggingBundle\LoggingServiceProvider"
    
  2. Basic Usage Inject the LoggingContext class into your service/controller:

    use DayspringTech\LoggingBundle\LoggingContext;
    
    class UserController extends Controller
    {
        public function __construct(private LoggingContext $loggingContext) {}
    
        public function store(Request $request)
        {
            $this->loggingContext->addContext('user_id', auth()->id());
            // Logs will now include this context
            \Log::info('User created', ['request_data' => $request->all()]);
        }
    }
    
  3. Default Context Check config/logging-bundle.php for predefined context keys (e.g., user_id, request_id).


Implementation Patterns

1. Context Propagation

  • Request Scoping: Use middleware to auto-add context (e.g., request_id, ip_address):

    public function handle(Request $request, Closure $next)
    {
        $loggingContext->addContext('request_id', $request->header('X-Request-ID'));
        return $next($request);
    }
    
  • Service-Level Context:

    class OrderService {
        public function __construct(private LoggingContext $loggingContext) {}
    
        public function createOrder(Order $order) {
            $this->loggingContext->addContext('order_id', $order->id);
            // All logs in this method will include `order_id`
        }
    }
    

2. Dynamic Context

  • Conditional Context:

    if ($user->isAdmin()) {
        $loggingContext->addContext('user_role', 'admin');
    }
    
  • Temporary Context (scoped to a block):

    $loggingContext->pushContext(['scope' => 'temporary']);
    try {
        // Logs here include `scope: temporary`
    } finally {
        $loggingContext->popContext();
    }
    

3. Integration with Monolog

  • Custom Processors: Extend Monolog’s ProcessorInterface to inject context:
    $processor = new class implements ProcessorInterface {
        public function __invoke(array $record): array {
            $record['extra']['context'] = $loggingContext->getAll();
            return $record;
        }
    };
    $logger->pushProcessor($processor);
    

4. Structured Logging

  • JSON Output: Configure Monolog to output structured logs:
    'monolog' => [
        'handlers' => [
            'stack' => [
                'formatter' => \Monolog\Formatter\JsonFormatter::class,
            ],
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Memory Leaks

    • Avoid adding context in long-running processes (e.g., queues) without cleanup:
      $loggingContext->clear(); // Reset after heavy operations
      
  2. Overhead

    • Excessive context keys slow down logging. Use sparingly in high-traffic endpoints.
  3. Thread Safety

    • The bundle assumes single-threaded execution. For queues/workers, reset context per job:
      dispatch(function () use ($loggingContext) {
          $loggingContext->clear(); // Reset for new job
      });
      

Debugging

  • Inspect Context:
    \Log::debug('Current context', ['context' => $loggingContext->getAll()]);
    
  • Check Middleware Order: Ensure context-setting middleware runs before logging middleware.

Extension Points

  1. Custom Context Providers Register a service to auto-populate context:

    $this->app->bind(ContextProviderInterface::class, function () {
        return new class implements ContextProviderInterface {
            public function get(): array {
                return ['custom_key' => 'value'];
            }
        };
    });
    
  2. Override Default Keys Modify config/logging-bundle.php to exclude/include keys:

    'default_context' => [
        'exclude' => ['password'], // Never log passwords
    ],
    
  3. Log Levels

    • Context is added to all log levels (debug, info, error, etc.). Filter selectively if needed:
      if (\Log::shouldLog(Logger::DEBUG)) {
          $loggingContext->addContext('debug_only', true);
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php