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

Loggable Bundle Laravel Package

dmp/loggable-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dmp/loggable-bundle
    

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

    Dmp\LoggableBundle\LoggableServiceProvider::class,
    
  2. Enable Annotation Processing Ensure your Laravel application supports annotations (e.g., via ramsey/uuid or doctrine/annotations). If not, install:

    composer require doctrine/annotations
    
  3. First Use Case Annotate a method in a service/controller:

    use Dmp\LoggableBundle\Annotation\Loggable;
    
    class UserService {
        /**
         * @Loggable
         */
        public function updateUser($userId, $data) {
            // Your logic here
        }
    }
    

    The method execution will now be logged automatically, including input parameters, return values, and exceptions.


Implementation Patterns

Core Workflow

  1. Annotation Placement Apply @Loggable to methods where you want execution logging:

    /**
     * @Loggable
     */
    public function processOrder(Order $order) { ... }
    
    • Supports class-level annotations (logs all methods in the class):
      /**
       * @Loggable
       */
      class OrderProcessor { ... }
      
  2. Integration with Laravel Logging The bundle uses Laravel’s default logger (Log::channel()). Customize logging channels in config/logging.php for structured logs (e.g., Monolog handlers).

  3. Dynamic Logging Override log behavior via method arguments:

    /**
     * @Loggable(logLevel="debug", skipParams=["password"])
     */
    public function login($email, $password) { ... }
    
    • Supported Attributes:
      • logLevel: debug, info, warning, error (default: info).
      • skipParams: Array of parameter names to exclude from logs.
      • logResponse: Boolean to log return values (default: true).
  4. Middleware/Event Integration Use the bundle alongside Laravel’s middleware or events for layered logging:

    // Log before/after middleware
    public function handle($request, Closure $next) {
        Log::info('Request started', ['url' => $request->url()]);
        $response = $next($request);
        Log::info('Request completed', ['status' => $response->status()]);
        return $response;
    }
    
  5. Testing Mock the logger in tests to verify logs:

    $mock = Mockery::mock('overload:Log');
    $mock->shouldReceive('info')->once();
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing

    • Issue: Annotations may not be detected if the doctrine/annotations cache is stale.
    • Fix: Clear the cache after adding the bundle:
      php artisan cache:clear
      php artisan config:clear
      
  2. Performance Overhead

    • Issue: Logging every method call can slow down production.
    • Fix: Use environment-based logging (e.g., disable in config/logging.php for production):
      'default' => env('LOG_CHANNEL', 'stack'),
      'channels' => [
          'stack' => [
              'driver' => 'stack',
              'channels' => ['single'],
              'ignore_exceptions' => false,
          ],
          'single' => [
              'driver' => 'single',
              'path' => storage_path('logs/laravel.log'),
              'level' => env('APP_ENV') === 'production' ? 'warning' : 'debug',
          ],
      ],
      
  3. Circular Dependencies

    • Issue: Logging services with circular dependencies (e.g., UserService logging OrderService which logs UserService) may cause infinite loops.
    • Fix: Exclude specific classes from logging via a config option (if supported in future updates) or use a whitelist.
  4. Parameter Serialization

    • Issue: Complex objects (e.g., Eloquent models, closures) may not serialize cleanly.
    • Fix: Implement __toString() or use skipParams to exclude problematic parameters.

Debugging Tips

  1. Verify Annotation Processing Check if annotations are registered:

    $reflection = new ReflectionClass(UserService::class);
    $method = $reflection->getMethod('updateUser');
    $annotations = \Doctrine\Common\Annotations\Reader::getInstance()->getMethodAnnotation($method, Loggable::class);
    
  2. Log Bundle Initialization Add debug logs in LoggableServiceProvider to confirm the bundle loads:

    public function boot() {
        Log::debug('LoggableBundle initialized');
    }
    
  3. Check for Conflicts Ensure no other packages override the Loggable annotation or aspect-oriented logic.

Extension Points

  1. Custom Log Formatters Override the default log format by binding a custom formatter to the container:

    $this->app->bind(LogFormatterInterface::class, CustomLogFormatter::class);
    
  2. Add Conditional Logging Extend the Loggable annotation to support dynamic conditions:

    /**
     * @Loggable(condition="request()->user()->isAdmin()")
     */
    public function adminAction() { ... }
    

    (Requires custom implementation of the condition attribute parser.)

  3. Integrate with Monitoring Tools Pipe logs to external services (e.g., Sentry, Datadog) by extending the logger channel:

    'channels' => [
        'loggable' => [
            'driver' => 'monolog',
            'handler' => \Monolog\Handler\PushHandler::class,
            'with' => [
                'bubble' => false,
                'handler' => new \Monolog\Handler\SyslogHandler('loggable'),
            ],
        ],
    ],
    
  4. Support for Async Logging Use Laravel’s queue-based logging to offload I/O:

    'channels' => [
        'loggable' => [
            'driver' => 'async',
            'queue' => 'logs',
        ],
    ],
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
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
agtp/mod-php
centraldesktop/protobuf-php