PHP code example of tibbs / scoped-logger-laravel

1. Go to this page and download the library: Download tibbs/scoped-logger-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tibbs / scoped-logger-laravel example snippets


return [
    'default_level' => 'info',

    'scopes' => [
        'payment' => 'debug',      // Verbose logging for payments
        'auth' => 'error',         // Only errors for authentication
        'reporting' => 'debug',    // Detailed logs for reports
        'chatty-vendor' => false,  // Completely suppress
    ],
];

// Explicit scope
Log::scope('payment')->debug('Processing payment', ['amount' => 100]);
// ✅ Logs because 'payment' scope allows 'debug'

Log::scope('auth')->info('User logged in');
// ❌ Silently dropped because 'auth' 

use Illuminate\Support\Facades\Log;

// Using Log facade
Log::scope('payment')->debug('Payment details', $data);
Log::scope('api')->info('API request', $request);

// Using logger helper
logger()->scope('auth')->warning('Failed login attempt');

// Chain with other methods
Log::scope('reporting')
    ->withContext(['user_id' => 123])
    ->info('Report generated');

namespace App\Services;

class PaymentService
{
    // Option 1: Use class FQCN as scope
    // Configure: 'App\Services\PaymentService' => 'debug'

    // Option 2: Define static property
    protected static string $log_scope = 'payment';

    // Option 3: Define static method
    public static function getLogScope(): string
    {
        return 'payment';
    }

    public function processPayment()
    {
        // Automatically uses 'payment' scope
        Log::debug('Processing payment...');
    }
}

'scopes' => [
    // Match all service classes
    'App\\Services\\*' => 'debug',

    // Match specific namespaces (more specific wins)
    'App\\Services\\Payment\\*' => 'info',

    // Dot notation patterns
    'payment.*' => 'debug',

    // Suppress all vendor logs
    'vendor.*' => false,
],

'scopes' => [
    'App\\*' => 'warning',                    // Least specific
    'App\\Services\\*' => 'info',             // More specific
    'App\\Services\\Payment\\*' => 'debug',   // Most specific
    'App\\Services\\PaymentService' => 'error', // Exact (highest priority)
],

Log::scope('App\\Services\\Payment\\StripeService')->debug('...');
// Uses 'App\\Services\\Payment\\*' (most specific pattern match)

Log::scope('App\\Services\\PaymentService')->debug('...');
// Uses exact match 'App\\Services\\PaymentService'

'scopes' => [
    'noisy-vendor' => false,
    'debug-toolbar' => false,
    'vendor.*' => false,  // Suppress all vendor packages
],

Log::scope('noisy-vendor')->emergency('Critical error!');
// ❌ Completely suppressed, even emergency logs

'scopes' => [
    'payment' => 'debug',
],

Log::scope('paymnet')->info('typo!');
// ❌ Throws UnknownScopeException - helps you catch the typo

// config/scoped-logger.php
'unknown_scope_handling' => 'exception',  // Default - throw exception
// 'unknown_scope_handling' => 'log',     // Log warning and continue with default level
// 'unknown_scope_handling' => 'ignore',  // Silently use default level

// .env
SCOPED_LOG_ENABLED=false  // Bypass all scoped logging features

return [
    // Master switch - set to false to disable scoped logging globally
    'enabled' => env('SCOPED_LOG_ENABLED', true),

    // Default level when no scope matches
    'default_level' => env('SCOPED_LOG_DEFAULT_LEVEL', 'info'),

    // Scope definitions (supports exact matches, wildcards, closures, and false for suppression)
    'scopes' => [
        'payment' => 'debug',
        'auth' => 'warning',
        'App\\Services\\MailchimpApi' => 'debug',
        'App\\Services\\*' => 'info',                // Wildcard pattern
        'vendor.*' => false,                         // Suppress completely
        'api' => fn() => app()->environment('local') ? 'debug' : 'error',  // Closure
    ],

    // How to handle unknown/unconfigured scopes (exception, log, or ignore)
    'unknown_scope_handling' => env('SCOPED_LOG_UNKNOWN_SCOPE', 'exception'),

    // Per-channel scope configurations (override global scopes for specific channels)
    'channel_scopes' => [
        'daily' => [
            'payment' => 'debug',
            'api' => 'info',
        ],
        'slack' => [
            'payment' => 'error',
            'api' => 'error',
        ],
    ],

    // Auto-detection settings
    'auto_detection' => [
        'enabled' => env('SCOPED_LOG_AUTO_DETECT', true),
        'property' => 'log_scope',        // Property/method name to check
        'stack_depth' => 10,               // How deep to traverse stack
        'skip_vendor' => true,             // Skip vendor classes
        'skip_paths' => ['/vendor/', '/bootstrap/'],
    ],

    // List of channels that should NOT use scoped logging
    // By default, all channels use scoped logging (global by default)
    'disabled_channels' => [
        // 'slack',
        // 'sentry',
    ],

    // Add scope identifier to log context
    '

// config/scoped-logger.php
'scopes' => [
    'payment' => 'debug',  // You want debug logs for payments
],

// config/logging.php
'channels' => [
    'daily' => [
        'driver' => 'daily',
        'level' => 'warning',  // ⚠️ PROBLEM: Channel filters out debug/info
    ],
],

Log::scope('payment')->debug('Payment processing');
// ❌ DROPPED: Scoped logger allows it, but channel level is 'warning'

// config/logging.php
'channels' => [
    'daily' => [
        'driver' => 'daily',
        'level' => 'debug',  // ✅ Let scoped logger control filtering
    ],
],

// Temporarily increase logging for debugging
Log::setRuntimeLevel('payment', 'debug');
Log::scope('payment')->debug('Now logging'); // ✅ Logs

// Clear override
Log::clearRuntimeLevel('payment');

// Temporarily suppress a noisy scope
Log::setRuntimeLevel('chatty-service', false);

// Clear all overrides
Log::clearAllRuntimeLevels();

// config/scoped-logger.php
'scopes' => [
    // Environment-based
    'api' => fn() => app()->environment('local') ? 'debug' : 'error',

    // Time-based (verbose logging during off-peak hours)
    'batch-import' => fn() => now()->hour >= 2 && now()->hour < 6 ? 'debug' : 'info',

    // Feature flag-based
    'experimental' => fn() => config('features.verbose_experimental') ? 'debug' : 'warning',

    // Custom logic
    'performance' => fn() => app('metrics')->isUnderLoad() ? 'error' : 'info',
],

// config/scoped-logger.php
'scopes' => [
    // Global defaults
    'payment' => 'error',
    'api' => 'warning',
],

'channel_scopes' => [
    // Verbose logging on daily file
    'daily' => [
        'payment' => 'debug',
        'api' => 'info',
    ],

    // Errors only on Slack
    'slack' => [
        'payment' => 'error',
        'api' => 'error',
    ],
],

Log::channel('daily')->scope('payment')->debug('Processing payment');
// ✅ Logs (daily channel allows debug for payment)

Log::channel('slack')->scope('payment')->debug('Processing payment');
// ❌ Dropped (slack channel 

'channel_scopes' => [
    'audit' => ['payment' => 'debug'],
],

'disabled_channels' => ['ondemand'], // Leave Log::build() channels unfiltered

Log::stack(['single', 'daily'], 'audit')->scope('payment')->debug('Refund issued');
// ✅ Logs (audit allows debug for payment)

Log::scope(['payment', 'api'])->debug('Payment via API');

// config/scoped-logger.php
'scopes' => [
    'payment' => 'debug',  // Most verbose
    'api' => 'error',      // Least verbose
],

Log::scope(['payment', 'api'])->debug('test');
// ✅ Logs because payment allows debug (most verbose wins)

Log::scope(['payment', 'api'])->info('test');
// ✅ Logs because payment allows info

Log::scope('api')->debug('test');
// ❌ Dropped because api 

[
    'scoped_logger_debug' => [
        'resolved_scope' => 'payment',
        'log_level' => 'debug',
        'configured_level' => 'debug',
        'resolution_method' => 'explicit (scope() method)',
        'runtime_override' => 'no',
        'matched_pattern' => 'App\\Services\\*',  // If applicable
    ],
]
bash
php artisan vendor:publish --tag="scoped-logger-config"