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

Logs Laravel Package

colbeh/logs

A Laravel logging helper package that aims to simplify writing and managing application logs. Provides convenient utilities for recording messages and events so you can debug issues and track activity more easily within your Laravel app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require colbeh/logs
    

    Publish the config file:

    php artisan vendor:publish --provider="Colbeh\Logs\LogsServiceProvider"
    
  2. Configuration Edit config/logs.php to define:

    • log_path: Directory for storing daily logs (default: storage/logs/daily).
    • log_level: Minimum log level to capture (e.g., debug, info, warning).
    • max_files: Number of log files to retain before rotation.
  3. First Use Case Log a daily entry in a controller or service:

    use Colbeh\Logs\Facades\Logs;
    
    Logs::info('User created', ['user_id' => 123]);
    

    Check the generated log at storage/logs/daily/{date}.log.


Implementation Patterns

Core Workflows

  1. Structured Logging Use context arrays for metadata:

    Logs::debug('API request', [
        'method' => 'GET',
        'endpoint' => '/users',
        'params' => ['page' => 1]
    ]);
    
  2. Conditional Logging Leverage log levels for debugging vs. production:

    if (app()->environment('local')) {
        Logs::debug('Debugging user flow', ['user_id' => $user->id]);
    }
    Logs::info('User action', ['action' => 'login']);
    
  3. Integration with Laravel Events Attach logging to events in EventServiceProvider:

    protected $listen = [
        'user.created' => [
            function ($user) {
                Logs::info('New user registered', ['email' => $user->email]);
            },
        ],
    ];
    
  4. Custom Log Channels Extend the package by creating a custom channel (see extension tips):

    // app/Providers/LogsServiceProvider.php
    public function register()
    {
        Logs::extend('slack', function () {
            return new SlackChannel();
        });
    }
    

Integration Tips

  • Monolog Compatibility The package uses Monolog under the hood. Reuse Monolog handlers (e.g., StreamHandler) by configuring config/logs.php:

    'handlers' => [
        'daily_file' => [
            'class' => 'Monolog\Handler\StreamHandler',
            'path' => storage_path('logs/daily.log'),
            'level' => 'debug',
        ],
    ],
    
  • Log Rotation Combine with Laravel’s built-in log rotation (via config/logging.php) for unified retention policies.

  • API Responses Log API request/response pairs in middleware:

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        Logs::info('API response', [
            'status' => $response->status(),
            'data' => $response->getContent(),
        ]);
        return $response;
    }
    

Gotchas and Tips

Pitfalls

  1. File Permissions Ensure storage/logs/daily is writable:

    chmod -R 775 storage/logs/daily
    

    Symptom: Logs fail silently if permissions are incorrect.

  2. Date Format Assumption The package assumes YYYY-MM-DD log filenames. Override in config/logs.php if needed:

    'date_format' => 'Y-m-d_His', // Custom format
    
  3. Level Filtering Logs below the configured log_level are discarded. Verify config/logs.php:

    'log_level' => env('LOG_LEVEL', 'info'), // Defaults to 'info'
    
  4. No Built-in Querying The package stores logs as flat files. For searchability, pair with:

    • Laravel Scout: Index logs in Elasticsearch.
    • Custom Parser: Use Log::getLogs() to fetch raw log data (see below).

Debugging

  1. Check Log Existence Verify logs are written to the correct path:

    $logs = Logs::getLogs(); // Returns array of log entries
    dd($logs);
    
  2. Handler Misconfiguration If logs disappear, inspect Monolog handlers:

    dd(Logs::getHandler()); // Debug the active handler
    
  3. Environment-Specific Issues Use app()->environment() to debug environment-specific behavior:

    if (app()->environment('staging')) {
        Logs::warning('Staging environment detected');
    }
    

Extension Points

  1. Custom Log Formatter Override the default formatter in LogsServiceProvider:

    public function boot()
    {
        Logs::formatter(function ($log) {
            return sprintf(
                "[%s] %s | %s | %s\n",
                $log['datetime']->format('Y-m-d H:i:s'),
                $log['level_name'],
                $log['context']['user_id'] ?? 'N/A',
                $log['message']
            );
        });
    }
    
  2. Add Log Channels Register new channels in LogsServiceProvider:

    public function register()
    {
        Logs::extend('database', function () {
            return new DatabaseHandler(config('logs.connection'));
        });
    }
    

    Use via:

    Logs::channel('database')->info('Database log entry');
    
  3. Hook into Log Rotation Extend the LogRotation class to customize cleanup logic:

    // app/Extensions/CustomLogRotation.php
    namespace App\Extensions;
    
    use Colbeh\Logs\LogRotation;
    
    class CustomLogRotation extends LogRotation
    {
        protected function shouldDelete($file)
        {
            // Custom logic (e.g., delete only files older than 30 days)
            return $file->getMTime() < strtotime('-30 days');
        }
    }
    

    Bind it in LogsServiceProvider:

    $this->app->bind(LogRotation::class, CustomLogRotation::class);
    
  4. Log to External Services Use Monolog’s BufferHandler to batch logs before sending to external APIs:

    Logs::useStack(function () {
        $stack = new \Monolog\Logger('name');
        $stack->pushHandler(new \Monolog\Handler\BufferHandler(
            new \Monolog\Handler\HttpHandler('https://api.example.com/logs')
        ));
        return $stack;
    });
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle