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

antonchernik/logging-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require antonchernik/logging-bundle
    

    Ensure symfony/monolog-bundle (≥3.6) is installed (required dependency).

  2. Register the Bundle: Add to config/app.php under providers:

    AntonChernik\LoggingBundle\LoggingBundle::class,
    
  3. First Use Case: Inject the LoggerInterface into a service/controller:

    use AntonChernik\LoggingBundle\Logger\LoggerInterface;
    
    class ExampleController
    {
        public function __construct(private LoggerInterface $logger)
        {
        }
    
        public function index()
        {
            $this->logger->info('User accessed the homepage');
        }
    }
    
  4. Configuration: Check config/logging.php (auto-generated by Monolog) for channel setup. The bundle extends Monolog’s capabilities—verify handlers/formatters are configured.


Implementation Patterns

Core Workflows

  1. Structured Logging: Use named loggers for context (e.g., logger('auth')):

    $this->logger->withContext(['user_id' => 123])->debug('Login attempt');
    
  2. Log Levels: Leverage all Monolog levels (emergency(), alert(), ..., debug()) with bundle-specific extensions:

    $this->logger->warning('Disk space low', ['space_left' => 10]);
    
  3. Custom Handlers: Extend the bundle’s AbstractHandler to create domain-specific loggers (e.g., DatabaseHandler):

    class AuditHandler extends AbstractHandler
    {
        protected function write(array $record): void
        {
            // Custom logic (e.g., store in DB)
        }
    }
    
  4. Middleware Integration: Log requests/responses in middleware:

    public function handle($request, Closure $next)
    {
        $this->logger->info('Request started', ['path' => $request->path()]);
        $response = $next($request);
        $this->logger->info('Request completed', ['status' => $response->status()]);
        return $response;
    }
    
  5. Command Logging: Log CLI command execution:

    $this->logger->command('php artisan migrate', ['exit_code' => 0]);
    

Integration Tips

  • Laravel-Specific: Use the Log facade as a fallback if dependency injection feels verbose:

    use Illuminate\Support\Facades\Log;
    Log::channel('custom')->info('Message');
    

    (Note: Ensure the channel is configured in config/logging.php.)

  • Queue Workers: Log job processing:

    $this->logger->job('SendEmail', ['user_id' => 123, 'status' => 'queued']);
    
  • Exception Handling: Override render() in App\Exceptions\Handler to log errors:

    public function render($request, Throwable $exception)
    {
        $this->logger->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
        return parent::render($request, $exception);
    }
    

Gotchas and Tips

Pitfalls

  1. Missing Monolog Bundle: The package requires symfony/monolog-bundle. Install it first or face autoloading errors:

    composer require symfony/monolog-bundle
    
  2. Channel Configuration: The bundle assumes Monolog channels exist. If logs disappear, verify config/logging.php:

    'channels' => [
        'custom' => [
            'driver' => 'single',
            'path' => storage_path('logs/custom.log'),
        ],
    ],
    
  3. PHP 8.0+ Only: The package enforces PHP 8.0+. Downgrading will trigger autoload errors.

  4. Logger Naming Collisions: Avoid naming custom loggers the same as Laravel’s built-in channels (e.g., single, stack). Use unique names like app.audit.

  5. Handler Priorities: Handlers are processed in order. Place critical handlers (e.g., DatabaseHandler) before file handlers to avoid race conditions.

Debugging

  • Log Not Appearing? Check:

    • The channel is enabled in config/logging.php.
    • The handler’s level matches the log level (e.g., debug won’t trigger an error handler).
    • Permissions on log files (e.g., storage/logs/).
  • Context Data Missing: Use withContext() before logging:

    // ❌ Won't work
    $this->logger->info($this->logger->withContext(['key' => 'value']));
    
    // ✅ Correct
    $this->logger->withContext(['key' => 'value'])->info('Message');
    

Extension Points

  1. Custom Handlers: Extend AntonChernik\LoggingBundle\Handler\AbstractHandler to add logic (e.g., Slack notifications):

    class SlackHandler extends AbstractHandler
    {
        protected function write(array $record): void
        {
            $this->sendToSlack($record['message'], $record['context']);
        }
    }
    
  2. Log Formatters: Override AntonChernik\LoggingBundle\Formatter\JsonFormatter to customize output:

    class CustomJsonFormatter extends JsonFormatter
    {
        public function format(array $record): string
        {
            $record['extra']['custom_field'] = 'value';
            return parent::format($record);
        }
    }
    
  3. Service Provider Hooks: Bind custom loggers in the bundle’s service provider (AntonChernik\LoggingBundle\LoggingBundle):

    $this->app->bind('custom.logger', function ($app) {
        return new CustomLogger($app['logger']);
    });
    
  4. Event Listeners: Listen for log events (e.g., AntonChernik\LoggingBundle\Events\LogRecord):

    public function handle(LogRecord $event)
    {
        if ($event->level === Logger::ERROR) {
            // Trigger alert
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware