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

Logger Bundle Laravel Package

domtomproject/logger-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require domtomproject/logger-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    DomTomProject\LoggerBundle\DomtomLoggerBundle::class => ['all' => true],
    
  2. Configure Database Connection Define a dedicated DB connection for logs in config/packages/doctrine.yaml:

    doctrine:
        dbal:
            connections:
                log:
                    url: '%env(DATABASE_URL_LOG)%'
                    driver: pdo_mysql
                    server_version: '5.7'
    
  3. Bundle Configuration Add to config/packages/domtom_logger.yaml:

    domtom_logger:
        writer: "domtom_logger.writer_mysql"
        mysql:
            manager: "log"  # Matches the connection name above
    
  4. First Log Entry Create a custom log entity (see Using Example) and log via:

    $logger = $this->get('domtom_logger.logger');
    $logger->log('user.action', 'User updated profile', ['user_id' => 123]);
    

Implementation Patterns

Core Workflows

  1. Logging Actions Use the service domtom_logger.logger to log structured events:

    $logger->log('auth.login', 'User logged in', [
        'ip' => $request->getClientIp(),
        'user_agent' => $request->headers->get('User-Agent')
    ]);
    
  2. Custom Log Entities Extend DomTomProject\LoggerBundle\Model\Log to add fields:

    /**
     * @ORM\Entity(repositoryClass="AppBundle\Repository\CustomLogRepository")
     */
    class CustomLog extends Log {
        /**
         * @Column(type="string", length=255)
         */
        private $severity;
    
        public function setSeverity(string $severity): self {
            $this->severity = $severity;
            return $this;
        }
    }
    
  3. Bulk Logging For performance, batch logs before persisting:

    $logger->batchLog([
        ['action' => 'order.created', 'data' => ['order_id' => 1]],
        ['action' => 'email.sent', 'data' => ['to' => 'user@example.com']]
    ]);
    
  4. Querying Logs Use the repository to fetch logs:

    $logs = $this->getDoctrine()
        ->getRepository('AppBundle:CustomLog')
        ->findBy(['action' => 'auth.login'], ['createdAt' => 'DESC']);
    

Integration Tips

  • Symfony Events: Log events in event listeners:
    public function onKernelRequest(GetResponseEvent $event) {
        $logger->log('http.request', 'Incoming request', [
            'method' => $event->getRequest()->getMethod(),
            'uri' => $event->getRequest()->getUri()
        ]);
    }
    
  • Doctrine Lifecycle: Log entity changes via prePersist, preUpdate, etc.
  • API Responses: Log API calls with request/response data:
    $logger->log('api.call', 'GET /users', [
        'status' => $response->getStatusCode(),
        'duration_ms' => $stopwatch->lap()
    ]);
    

Gotchas and Tips

Pitfalls

  1. Database Connection

    • Ensure the log connection in doctrine.yaml is properly configured. A misconfigured connection will silently fail.
    • Fix: Test the connection manually:
      php bin/console doctrine:query:sql "SELECT 1" --connection=log
      
  2. Entity Mapping

    • Custom log entities must extend DomTomProject\LoggerBundle\Model\Log and be mapped to the log entity manager.
    • Fix: Verify the manager: log setting in domtom_logger.yaml matches your doctrine.yaml connection name.
  3. Performance

    • Bulk logging (batchLog) is not transactional by default. Wrap in a transaction if data integrity is critical:
      $entityManager = $this->getDoctrine()->getManager('log');
      $entityManager->beginTransaction();
      try {
          $logger->batchLog($logs);
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      
  4. Deprecated Methods

    • The create() static method in the example is not part of the public API. Use the logger service directly:
      // Avoid:
      CustomLog::create('text');
      // Use:
      $logger->log('custom.action', 'text');
      

Debugging

  1. Log Storage

    • Check if logs are saved by querying the database directly:
      SELECT * FROM log WHERE action = 'test.action';
      
    • Enable SQL logging in config/packages/dev/doctrine.yaml to debug queries:
      doctrine:
          dbal:
              logging: true
              profiling: true
      
  2. Service Availability

    • Verify the logger service is registered:
      php bin/console debug:container domtom_logger.logger
      
    • If missing, clear the cache:
      php bin/console cache:clear
      

Extension Points

  1. Custom Writers

    • Extend DomTomProject\LoggerBundle\Writer\WriterInterface to support new storage backends (e.g., Elasticsearch, MongoDB):
      class ElasticsearchWriter implements WriterInterface {
          public function write(Log $log) {
              // Custom logic to index in Elasticsearch
          }
      }
      
    • Register the writer in domtom_logger.yaml:
      domtom_logger:
          writer: "app.writer_elasticsearch"
      
  2. Log Filters

    • Implement DomTomProject\LoggerBundle\Filter\FilterInterface to filter logs before storage:
      class SensitiveDataFilter implements FilterInterface {
          public function filter(Log $log) {
              if (isset($log->getData()['password'])) {
                  $log->setData(array_merge($log->getData(), ['password' => '***']));
              }
              return $log;
          }
      }
      
    • Bind the filter in services.yaml:
      DomTomProject\LoggerBundle\Filter\FilterInterface:
          tags: ['domtom_logger.filter']
          class: App\Filter\SensitiveDataFilter
      
  3. Event Listeners

    • Subscribe to domtom_logger.log events to react to log entries:
      use DomTomProject\LoggerBundle\Event\LogEvent;
      
      public function onLog(LogEvent $event) {
          if ($event->getLog()->getAction() === 'auth.login') {
              // Trigger a welcome email, etc.
          }
      }
      
    • Tag the listener in services.yaml:
      App\EventListener\AuthListener:
          tags: ['kernel.event_listener', { event: 'domtom_logger.log', method: 'onLog' }]
      

Configuration Quirks

  • Case Sensitivity: The writer key in domtom_logger.yaml must match the exact service ID (e.g., domtom_logger.writer_mysql).
  • Entity Manager: The manager setting refers to the Doctrine entity manager name, not the connection name. Ensure it matches your doctrine.yaml:
    # Correct:
    domtom_logger:
        mysql:
            manager: "log"  # Must match the EM name in doctrine.yaml
    
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.
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
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