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

Log Bundle Laravel Package

codebender/log-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Laravel project via Composer:

    composer require codebender/log-bundle
    

    Register the bundle in config/app.php under providers:

    Codebender\LogBundle\CodebenderLogBundle::class,
    
  2. Publish Configuration Publish the default config:

    php artisan vendor:publish --provider="Codebender\LogBundle\CodebenderLogBundle" --tag="config"
    

    Edit config/codebender_log.php to define log channels, handlers, and formatters.

  3. First Use Case Inject the logger into a service/controller:

    use Psr\Log\LoggerInterface;
    
    class MyController extends Controller
    {
        protected $logger;
    
        public function __construct(LoggerInterface $logger)
        {
            $this->logger = $logger;
        }
    
        public function index()
        {
            $this->logger->info('User accessed the dashboard', ['user_id' => 123]);
        }
    }
    

Implementation Patterns

Logging Workflows

  1. Structured Logging Use context arrays for structured logs:

    $this->logger->error('Failed to process order', [
        'order_id' => $order->id,
        'user_id' => $order->user_id,
        'error' => $e->getMessage()
    ]);
    
  2. Channel-Specific Logging Configure multiple channels (e.g., stack, monolog) in config/codebender_log.php:

    'channels' => [
        'stack' => [
            'type' => 'stack',
            'channels' => ['monolog', 'syslog'],
        ],
        'monolog' => [
            'type' => 'monolog',
            'path' => storage_path('logs/app.log'),
        ],
    ],
    

    Use channels in code:

    $this->logger->channel('monolog')->debug('Debug message');
    
  3. Middleware Integration Log requests/responses in middleware:

    public function handle($request, Closure $next)
    {
        $this->logger->info('Incoming request', [
            'method' => $request->method(),
            'path' => $request->path(),
        ]);
    
        $response = $next($request);
    
        $this->logger->info('Request completed', [
            'status' => $response->getStatusCode(),
        ]);
    
        return $response;
    }
    
  4. Event Logging Log custom events:

    event(new OrderPlaced($order));
    // In EventServiceProvider:
    protected $listen = [
        OrderPlaced::class => [
            \Codebender\LogBundle\Event\LogEventListener::class,
        ],
    ];
    

Integration Tips

  • Laravel’s Built-in Logging Extend Laravel’s Log facade to use the bundle:

    use Codebender\LogBundle\Facades\CodebenderLog;
    
    CodebenderLog::info('Custom log via facade');
    
  • Queue Workers Log job processing:

    public function handle()
    {
        $this->logger->info('Job started', ['job' => $this->job]);
        // ...
        $this->logger->info('Job completed', ['job' => $this->job]);
    }
    
  • API Responses Log API errors with request/response data:

    try {
        $response = $this->callApi();
    } catch (\Exception $e) {
        $this->logger->error('API call failed', [
            'url' => $url,
            'request' => $requestData,
            'response' => $response ?? null,
            'error' => $e->getMessage(),
        ]);
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • The bundle may override Laravel’s default Log configuration. Ensure config/codebender_log.php does not conflict with config/logging.php.
    • Fix: Merge configurations explicitly:
      'logging' => array_merge(
          require __DIR__.'/logging.php',
          require __DIR__.'/codebender_log.php'
      ),
      
  2. Channel Naming Collisions

    • Avoid naming custom channels the same as Laravel’s built-in channels (e.g., single, stack).
    • Fix: Use unique names like app_stack or custom_monolog.
  3. Performance with Heavy Logging

    • Excessive logging (e.g., debug for every request) can slow down applications.
    • Fix: Use log levels appropriately and consider async handlers for production.
  4. Missing Dependencies

    • The bundle relies on monolog/monolog and symfony/console. Ensure they are installed:
      composer require monolog/monolog symfony/console
      

Debugging

  1. Log Not Appearing?

    • Check if the handler is properly configured in config/codebender_log.php.
    • Verify file permissions for log paths (e.g., storage/logs/).
    • Debug Tip: Use tail -f storage/logs/app.log to monitor logs in real-time.
  2. Channel Not Found

    • Ensure the channel name matches exactly (case-sensitive) in both config and code.
    • Debug Tip: Dump the available channels:
      dd(\Codebender\LogBundle\CodebenderLogBundle::getChannels());
      
  3. Context Data Missing

    • Context arrays must be serializable. Avoid logging non-serializable objects (e.g., closures, resources).
    • Fix: Convert objects to arrays:
      $this->logger->info('User data', [
          'user' => $user->toArray(), // Assuming a toArray() method
      ]);
      

Extension Points

  1. Custom Handlers Extend the bundle by creating a custom handler:

    use Monolog\Handler\AbstractHandler;
    
    class SlackHandler extends AbstractHandler
    {
        public function write(array $record): void
        {
            // Send log to Slack
        }
    }
    

    Register it in config/codebender_log.php:

    'handlers' => [
        'slack' => [
            'type' => 'custom',
            'class' => \App\Handlers\SlackHandler::class,
        ],
    ],
    
  2. Log Formatters Customize log formatting by extending Monolog\Formatter\FormatterInterface:

    class JsonFormatter extends \Monolog\Formatter\JsonFormatter
    {
        public function format(array $record): string
        {
            $record['extra']['custom_field'] = 'value';
            return parent::format($record);
        }
    }
    

    Attach it to a handler:

    'handlers' => [
        'monolog' => [
            'type' => 'monolog',
            'formatter' => \App\Formatters\JsonFormatter::class,
        ],
    ],
    
  3. Event Listeners Listen to log events (e.g., LogRecordCreated):

    use Codebender\LogBundle\Event\LogRecordCreated;
    
    class CustomLogListener
    {
        public function onLogRecordCreated(LogRecordCreated $event)
        {
            if ($event->getLevel() === \Monolog\Logger::ERROR) {
                // Trigger alerts, etc.
            }
        }
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        LogRecordCreated::class => [
            \App\Listeners\CustomLogListener::class,
        ],
    ];
    
  4. Laravel Service Provider Bind custom logger instances:

    public function register()
    {
        $this->app->bind(LoggerInterface::class, function ($app) {
            return $app->make('logger')->channel('custom');
        });
    }
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver