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 Laravel Package

pear/log

PEAR Log provides a simple, standardized logging system for PHP. It supports multiple backends (file, console, syslog, database, mail, etc.), configurable priorities and formatting, and a consistent API to route application messages wherever you need.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require pear/log
    

    Ensure pear/pear_exception (v1.0.1–1.0.2) is installed if not already present.

  2. Basic Logger Setup:

    use PEAR\Log;
    
    // Initialize logger with default level (e.g., PEAR_LOG_INFO)
    $logger = Log::singleton(PEAR_LOG_INFO);
    
    // Log a message
    $logger->log("Application started", PEAR_LOG_NOTICE);
    
  3. First Use Case: File Logging

    $logger = Log::singleton(PEAR_LOG_DEBUG);
    $logger->addHandler(new Log\Handler\File('/var/log/myapp.log'));
    $logger->log("Debugging mode enabled", PEAR_LOG_DEBUG);
    
  4. Laravel Integration (Wrapper Class): Create a facade or service provider to bridge Laravel’s Log facade with pear/log:

    // app/Services/PearLogger.php
    class PearLogger {
        public static function info($message, array $context = []) {
            $log = Log::singleton(PEAR_LOG_INFO);
            $log->log($message . (count($context) ? ' - ' . json_encode($context) : ''), PEAR_LOG_INFO);
        }
    }
    

    Register in AppServiceProvider:

    Log::extend('pear', function () {
        return new PearLogger();
    });
    

    Usage:

    Log::channel('pear')->info('User logged in', ['user_id' => 1]);
    

Implementation Patterns

Core Workflows

  1. Handler-Based Logging:

    • Attach multiple handlers (file, syslog, email) to a single logger instance:
      $logger = Log::singleton(PEAR_LOG_ALL);
      $logger->addHandler(new Log\Handler\File('/var/log/app.log'));
      $logger->addHandler(new Log\Handler\Syslog('myapp'));
      
  2. Contextual Logging:

    • Manually encode context into messages (no built-in structured logging):
      $userId = 123;
      $logger->log("User action", PEAR_LOG_INFO, [
          'user_id' => $userId,
          'action' => 'profile_update'
      ]);
      // Output: "User action - {"user_id":123,"action":"profile_update"}"
      
  3. Log Level Filtering:

    • Use bitmask levels (e.g., PEAR_LOG_ALL or PEAR_LOG_ERR | PEAR_LOG_WARNING):
      $logger = Log::singleton(PEAR_LOG_ERR | PEAR_LOG_WARNING);
      $logger->log("This won't appear in debug logs", PEAR_LOG_DEBUG);
      
  4. Custom Handlers:

    • Extend Log\Handler for specialized outputs (e.g., database, HTTP):
      class DatabaseHandler extends Log\Handler {
          public function handle($message, $priority) {
              DB::table('logs')->insert([
                  'message' => $message,
                  'level' => $priority,
                  'created_at' => now()
              ]);
          }
      }
      

Laravel-Specific Patterns

  1. Channel Integration:

    • Register pear/log as a custom channel in config/logging.php:
      'pear' => [
          'driver' => 'custom',
          'path' => env('LOG_PATH', storage_path('logs/pear.log')),
          'level' => env('LOG_LEVEL', 'debug'),
      ],
      
    • Create a custom driver in app/Providers/AppServiceProvider:
      Log::extend('pear', function ($config) {
          $logger = Log::singleton($config['level']);
          $logger->addHandler(new Log\Handler\File($config['path']));
          return new PearLogDriver($logger);
      });
      
  2. Queue-Based Async Logging:

    • Dispatch log messages to a queue for async processing:
      Log::channel('pear')->info('Async log message');
      // In a queue worker:
      while ($message = queue()->pop('logs')) {
          $logger = Log::singleton(PEAR_LOG_INFO);
          $logger->log($message['message'], $message['level']);
      }
      
  3. Log Rotation:

    • Use Laravel’s Log::rotateStorages() with a custom handler:
      $handler = new Log\Handler\File('/var/log/app.log');
      $handler->setRotation(7); // Rotate weekly
      $logger->addHandler($handler);
      

Gotchas and Tips

Pitfalls

  1. PEAR Autoloader Conflicts:

    • If using PEAR’s autoloader alongside Composer, ensure pear/log is loaded via Composer’s classmap:
      {
          "autoload": {
              "classmap": ["vendor/pear/log"]
          }
      }
      
  2. Log Level Mismatches:

    • Laravel’s Log::debug() maps to PEAR_LOG_DEBUG, but ensure bitmask levels align (e.g., PEAR_LOG_ALL may not work on 32-bit systems; use PEAR_LOG_DEBUG | PEAR_LOG_INFO | ... explicitly).
  3. Context Data Loss:

    • pear/log does not natively support structured logging. Manually encode context:
      // Bad: Context is ignored
      $logger->log("User data", PEAR_LOG_INFO, ['user_id' => 1]);
      
      // Good: Encode context into message
      $logger->log("User data: " . json_encode(['user_id' => 1]), PEAR_LOG_INFO);
      
  4. Syslog Handler Quirks:

    • The SyslogHandler requires the $name parameter to be non-null (fixed in v1.14.4). Ensure you pass a valid identifier:
      $logger->addHandler(new Log\Handler\Syslog('myapp')); // Valid
      $logger->addHandler(new Log\Handler\Syslog(null));   // Throws error
      
  5. PHP 7.4+ Strictness:

    • Older code using PHP4-style constructors (e.g., new Log()) may trigger deprecation warnings. Use the singleton pattern:
      $logger = Log::singleton(PEAR_LOG_INFO); // Preferred
      // $logger = new Log(); // Deprecated
      
  6. Handler Return Values:

    • Composite handlers (e.g., multiple handlers on one logger) may return boolean values inconsistently (fixed in v1.14.6). Check return values if relying on them:
      if ($logger->log("Test", PEAR_LOG_INFO)) {
          // Handler may return false on failure
      }
      

Debugging Tips

  1. Log Level Tracing:

    • Use PEAR_LOG_ALL to capture all messages during debugging, then narrow down:
      $logger = Log::singleton(PEAR_LOG_ALL);
      
  2. Handler-Specific Issues:

    • Isolate handlers to identify misconfigurations:
      $fileHandler = new Log\Handler\File('/tmp/debug.log');
      $logger->addHandler($fileHandler);
      $logger->log("Test file handler", PEAR_LOG_DEBUG);
      
  3. PEAR Exception Handling:

    • Wrap pear/log calls in try-catch blocks to handle pear_exception:
      try {
          $logger->log("Critical error", PEAR_LOG_ERR);
      } catch (pear_exception $e) {
          error_log("Logging failed: " . $e->getMessage());
      }
      
  4. Performance Bottlenecks:

    • Profile file handler I/O with storage_path('logs/laravel.log') as a fallback:
      $handler = new Log\Handler\File('/tmp/app.log');
      $handler->setMode(0644); // Ensure writable permissions
      

Extension Points

  1. Custom Formatters:

    • Extend Log\Formatter to add structured logging (e.g., JSON):
      class JsonFormatter extends Log\Formatter {
          public function format($message, $priority) {
              return json_encode([
                  'message' => $message,
                  'level' => $priority,
                  'timestamp' => date('c')
              ]);
          }
      }
      
  2. Laravel Event Listeners:

    • Hook into Laravel events to log automatically:
      // app/Listeners/LogUserActivity.php
      public function handle($event) {
          Log::channel('pear')->info('User activity', $event->data);
      }
      
  3. Dynamic Handler Configuration:

    • Load handlers from environment variables:
      $handlers = [];
      if (env('LOG_TO_FILE')) {
          $handlers[] = new Log\Handler\File(env('LOG_PATH'));
      }
      if (env('LOG_TO_SYSLOG')) {
          $handlers[] = new Log\
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky