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

Dw Log Bundle Laravel Package

dragonwize/dw-log-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Log

  1. Installation

    composer require dragonwize/dw-log-bundle
    
  2. Configure DBAL Connection Add a connection in config/packages/dw_log.yaml:

    dw_log:
        db_connection: default  # or your custom connection name
        table_name: app_logs
    
  3. Create Log Table Run the console command:

    bin/console dw:log:create-table
    
  4. Configure Monolog Update config/packages/monolog.yaml to use the custom handler:

    monolog:
        handlers:
            dw_log:
                type: service
                id: DwLogBundle\Monolog\DwLogHandler
                level: debug  # or your preferred level
                channels: ["app", "doctrine"]  # channels to log
    
  5. First Log Test Trigger a log entry (e.g., via a route or CLI):

    $this->addLog('test', 'This is a test log message', ['context' => 'key' => 'value']);
    

    Verify logs appear in the /admin/logs route.


First Use Case: Debugging a Route

  1. Log a Request In your controller:

    use Psr\Log\LoggerInterface;
    
    public function index(LoggerInterface $logger)
    {
        $logger->info('User accessed route', ['user_id' => 123, 'route' => 'home']);
        return response()->json(['status' => 'success']);
    }
    
  2. View Logs Navigate to /admin/logs and search for user_id:123 to inspect the request.


Implementation Patterns

Workflows

1. Structured Logging

Use arrays for context to maintain consistency:

$logger->debug('Processing order', [
    'order_id' => $order->id,
    'status'   => $order->status,
    'user'     => $user->email,
]);

2. Channel-Specific Logging

Configure Monolog channels in monolog.yaml to separate logs (e.g., app, security, cli):

handlers:
    dw_log_app:
        type: service
        id: DwLogBundle\Monolog\DwLogHandler
        channels: ["app"]
    dw_log_security:
        type: service
        id: DwLogBundle\Monolog\DwLogHandler
        channels: ["security"]

3. Searching Logs Programmatically

Use the DwLogBundle\Repository\LogRepository service:

$logs = $logRepository->findBy([
    'level' => 'ERROR',
    'message' => '%timeout%',
    'context' => json_encode(['exception' => '%SQLSTATE%']),
]);

4. Custom Log Levels

Extend the bundle’s log levels by modifying the DwLogBundle\Monolog\DwLogHandler or adding a custom level to Monolog:

monolog:
    handlers:
        dw_log:
            level: custom_level  # Add to Monolog's levels in config

Integration Tips

Laravel-Specific Adaptations

  1. Service Container Binding Bind the Monolog handler to Laravel’s container in config/services.php:

    $app->bind('DwLogBundle\Monolog\DwLogHandler', function ($app) {
        return new \DwLogBundle\Monolog\DwLogHandler(
            $app['dw_log.connection'],
            $app['monolog.logger']
        );
    });
    
  2. Laravel Log Channel Create a custom Monolog channel in config/logging.php:

    'channels' => [
        'dw_log' => [
            'driver' => 'monolog',
            'handler' => 'DwLogBundle\Monolog\DwLogHandler',
            'with' => [
                'channels' => ['app', 'queue'],
            ],
        ],
    ],
    
  3. Queue Workers Log queue job processing:

    public function handle(Job $job, LoggerInterface $logger)
    {
        $logger->info('Job started', ['job_id' => $job->id, 'queue' => $job->queue]);
        // Process job...
        $logger->info('Job completed', ['job_id' => $job->id, 'duration' => '100ms']);
    }
    

Performance Considerations

  • Batch Writes: For high-volume logging, consider batching writes by extending DwLogBundle\Monolog\DwLogHandler to buffer logs and flush periodically.
  • Indexing: Ensure the message and context columns are indexed in the database for fast searches:
    ALTER TABLE app_logs ADD INDEX idx_message_context (message, context);
    

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch

    • Issue: Running dw:log:create-table after modifying the bundle’s schema (e.g., adding columns) may not update the table.
    • Fix: Drop and recreate the table or manually alter it:
      bin/console dw:log:drop-table
      bin/console dw:log:create-table
      
  2. Context Serialization

    • Issue: The context column stores JSON, but malformed data (e.g., circular references) may break logging.
    • Fix: Sanitize context data before logging:
      $context = json_decode(json_encode($context), true);
      $logger->info('Event', $context);
      
  3. Monolog Handler Conflicts

    • Issue: Multiple DwLogHandler instances may cause duplicate logs or conflicts.
    • Fix: Ensure only one handler is configured per channel in monolog.yaml.
  4. Tailwind CSS Conflicts

    • Issue: The admin UI may clash with existing Tailwind configurations.
    • Fix: Override Tailwind classes in your CSS or isolate the bundle’s styles:
      /* Disable Tailwind in the log UI */
      .dw-log-ui *[class*="tw-"] { all: unset; }
      

Debugging

  1. Log Handler Not Writing

    • Check: Verify the handler is registered in Monolog:
      bin/console debug:config monolog
      
    • Fix: Ensure the handler’s id matches the service definition.
  2. Empty Log Table

    • Check: Confirm the DBAL connection is correct in dw_log.yaml:
      dw_log:
          db_connection: default  # Must match your Doctrine connection
      
    • Fix: Test the connection manually:
      $connection = $this->get('dw_log.connection');
      var_dump($connection->getWrappedConnection()->getDatabasePlatform());
      
  3. Search Not Returning Results

    • Check: Raw SQL queries to ensure data exists:
      SELECT * FROM app_logs WHERE message LIKE '%test%';
      
    • Fix: Adjust the search syntax in the admin UI or repository methods.

Extension Points

  1. Custom Log Fields Extend the schema by overriding the DwLogBundle\Doctrine\DbalSchemaManager:

    // src/DwLogBundle/Doctrine/CustomSchemaManager.php
    class CustomSchemaManager extends DbalSchemaManager
    {
        public function getSchema(): Schema
        {
            $schema = parent::getSchema();
            $table = $schema->getTable('app_logs');
            $table->addColumn('custom_field', 'string', ['notnull' => false]);
            return $schema;
        }
    }
    

    Bind the service in config/services.yaml:

    services:
        DwLogBundle\Doctrine\DbalSchemaManager:
            class: App\DwLogBundle\Doctrine\CustomSchemaManager
    
  2. Webhook Notifications Add a post-log hook to send logs to an external service:

    // src/EventListener/LogWebhookListener.php
    class LogWebhookListener implements ContainerAwareInterface
    {
        public function onLogEntry(PostLogEntryEvent $event)
        {
            $log = $event->getLogEntry();
            // Send to webhook...
        }
    }
    

    Register the listener in config/services.yaml:

    services:
        App\EventListener\LogWebhookListener:
            tags:
                - { name: kernel.event_listener, event: dw_log.post_entry, method: onLogEntry }
    
  3. Log Retention Policy Implement a cron job to purge old logs using DBAL:

    $connection = $this->get('dw_log.connection');
    $connection->executeStatement(
        'DELETE FROM app_logs WHERE created_at < ?',
        [new \DateTime('-30 days')]
    );
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle