PHP code example of ravols / lara-logs-toolkit

1. Go to this page and download the library: Download ravols/lara-logs-toolkit 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/ */

    

ravols / lara-logs-toolkit example snippets


'composer_dump_autoload_channel' => env('LARA_LOGS_TOOLKIT_COMPOSER_DUMP_AUTOLOAD_CHANNEL', 'daily'),
'comparison_cache_ttl' => env('LARA_LOGS_TOOLKIT_COMPARISON_CACHE_TTL', 600),

use Illuminate\Support\Facades\Log;
use Ravols\LaraLogsToolkit\Facades\LaraLogsToolkit;

$logger = Log::channel('daily');
$comparison = LaraLogsToolkit::getLogAnalysisComparison($logger);

// Access the results using properties
$currentCounts = $comparison->current;      // LogCountsData
$cachedCounts = $comparison->cached;        // LogCountsData
$differences = $comparison->differences;    // LogCountsData

// Example: Check if errors increased using methods
if ($comparison->isNewError()) {
    echo "Errors increased by {$comparison->getNewErrorCount()} since last check\n";
}

// Or access directly via properties
if ($comparison->differences->error > 0) {
    echo "Errors increased by {$comparison->differences->error} since last check\n";
}

// Use helper methods for convenience
if ($comparison->hasAnyNewIssues()) {
    echo "Total new issues: {$comparison->getTotalNewIssuesCount()}\n";
    echo "New errors: {$comparison->getNewErrorCount()}\n";
    echo "New warnings: {$comparison->getNewWarningCount()}\n";
}

// Check when the cache was created
if ($comparison->cachedAt !== null) {
    echo "Cache was created at: {$comparison->cachedAt}\n";
} else {
    echo "No previous cache found (first run)\n";
}

use Ravols\LaraLogsToolkit\Facades\LaraLogsToolkit;

// Analyze all channels (excluding defaults)
$analysis = LaraLogsToolkit::getAllChannelsLogAnalysis();

// Get aggregated totals across all channels
$totalErrors = $analysis->getError();
$totalWarnings = $analysis->getWarning();
$total = $analysis->getTotal();

// Get specific channel data
$carriersData = $analysis->getChannel('carriers');
if ($carriersData) {
    $carriersErrors = $carriersData->error;
}

// With caching/comparison enabled
$analysis = LaraLogsToolkit::getAllChannelsLogAnalysis(useCache: true);

// Access comparison data for specific channels
$comparison = $analysis->getComparisonChannel('carriers');
if ($comparison && $comparison->hasAnyNewIssues()) {
    $newErrors = $comparison->getNewErrorCount();
    echo "New errors in carriers channel: {$newErrors}\n";
}

// Customize excluded channels
$analysis = LaraLogsToolkit::excludeChannels(['stack', 'null', 'slack'])
    ->getAllChannelsLogAnalysis();

// Include a normally excluded channel
$analysis = LaraLogsToolkit::



namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use Ravols\LaraLogsToolkit\LaraLogsToolkit;

class MonitorLogGrowth extends Command
{
    protected $signature = 'logs:monitor {channel=daily : The log channel to monitor} {--threshold=100 : Alert threshold}';
    protected $description = 'Monitor log growth and send alerts when threshold is exceeded';

    public function handle(LaraLogsToolkit $laraLogsToolkit): int
    {
        $channel = $this->argument('channel');
        $threshold = (int) $this->option('threshold');
        
        $logger = Log::channel($channel);
        
        // Get total count
        $logCounts = $laraLogsToolkit->getLogAnalysis($logger);
        $count = $logCounts->getTotal();
        
        // Or get count for a specific log level
        // $count = $logCounts->error; // or $logCounts->warning, etc. 
        
        // Or compare with cached results to detect changes
        // $comparison = $laraLogsToolkit->getLogAnalysisComparison($logger);
        // if ($comparison->isNewError()) {
        //     $newErrors = $comparison->getNewErrorCount();
        //     // Handle new errors since last check
        // }
        
        if ($count > $threshold) {
            // Send Slack notification
            Notification::route('slack', config('services.slack.webhook_url'))
                ->notify(new LogThresholdExceeded($channel, $count, $threshold));
            
            // Or send email
            // Mail::to(config('app.admin_email'))->send(new LogAlert($channel, $count));
            
            // Or send SMS
            // Notification::route('vonage', config('app.admin_phone'))
            //     ->notify(new LogThresholdExceeded($channel, $count, $threshold));
            
            $this->warn("Alert sent! Channel '{$channel}' has {$count} records (threshold: {$threshold})");
            return self::FAILURE;
        }
        
        $this->info("Channel '{$channel}' is within limits ({$count} records)");
        return self::SUCCESS;
    }
}

protected function schedule(Schedule $schedule): void
{
    // Check every 5 minutes after deployment
    $schedule->command('logs:monitor daily --threshold=100')->everyFiveMinutes();
}

$logCounts = LaraLogsToolkit::getLogAnalysis(Log::channel('daily'));

// Access individual log level counts via properties
$errors = $logCounts->error;
$warnings = $logCounts->warning;
$info = $logCounts->info;

// Get total count across all levels
$total = $logCounts->getTotal();

$comparison = LaraLogsToolkit::getLogAnalysisComparison(Log::channel('daily'));

// Check for new errors
if ($comparison->isNewError()) {
    $newErrors = $comparison->getNewErrorCount();
}

// Access properties directly
$currentErrors = $comparison->current->error;
$cachedErrors = $comparison->cached->error;
$errorDiff = $comparison->differences->error;

// Check when cache was created
if ($comparison->cachedAt) {
    echo "Last cached at: {$comparison->cachedAt}\n";
}

$logCounts = LaraLogsToolkit::getLogAnalysis(Log::channel('daily'));

// Access individual log level counts
$errorCount = $logCounts->error;
$infoCount = $logCounts->info;
$warningCount = $logCounts->warning;

// Get total count across all levels
$total = $logCounts->getTotal();

$comparison = LaraLogsToolkit::getLogAnalysisComparison(Log::channel('daily'));

// Use helper methods
if ($comparison->isNewError()) {
    $newErrors = $comparison->getNewErrorCount();
}

// Or access directly
$newErrors = $comparison->differences->error;
$currentErrors = $comparison->current->error;

// Check for any new issues
if ($comparison->hasAnyNewIssues()) {
    $totalNewIssues = $comparison->getTotalNewIssuesCount();
}

// Check when the cache was created
if ($comparison->cachedAt) {
    echo "Cache created at: {$comparison->cachedAt}\n";
}

// Basic usage - analyze all channels (excluding defaults)
$analysis = LaraLogsToolkit::getAllChannelsLogAnalysis();

// Get aggregated totals across all channels
$totalErrors = $analysis->getError();
$totalWarnings = $analysis->getWarning();
$total = $analysis->getTotal();

// Get specific channel data
$carriersData = $analysis->getChannel('carriers');
if ($carriersData instanceof LogCountsData) {
    $carriersErrors = $carriersData->error;
}

// With caching/comparison enabled
$analysis = LaraLogsToolkit::getAllChannelsLogAnalysis(useCache: true);

// Access comparison data for a specific channel
$comparison = $analysis->getComparisonChannel('carriers');
if ($comparison) {
    $newErrors = $comparison->getNewErrorCount();
    $hasNewIssues = $comparison->hasAnyNewIssues();
}

// Check if any channels have comparison data
if ($analysis->hasComparisonData()) {
    // Handle comparison-specific logic
}

// Customize excluded channels
$analysis = LaraLogsToolkit::excludeChannels(['stack', 'null', 'slack'])
    ->getAllChannelsLogAnalysis();

// Include a normally excluded channel
$analysis = LaraLogsToolkit::

$analysis = LaraLogsToolkit::getAllChannelsLogAnalysis();

// Aggregated totals across all channels
$allErrors = $analysis->getError();        // Sum of all errors from all channels
$allWarnings = $analysis->getWarning();   // Sum of all warnings from all channels
$allInfo = $analysis->getInfo();          // Sum of all info logs from all channels
$total = $analysis->getTotal();           // Total of all log levels from all channels

// Individual channel access
foreach ($analysis->getChannels() as $channelName => $channelData) {
    if ($channelData instanceof LogCountsData) {
        echo "{$channelName}: {$channelData->error} errors\n";
    }
}

use Ravols\LaraLogsToolkit\Facades\LaraLogsToolkit;

// Get last error message only (default channel: 'stack')
$error = LaraLogsToolkit::getLastError();

// Get last error from specific channel
$error = LaraLogsToolkit::getLastError('api');

// Get last error with stack trace
$error = LaraLogsToolkit::getLastError('stack', true);

// Get last error with stack trace from specific channel
$error = LaraLogsToolkit::getLastError('api', true);

$lastError = LaraLogsToolkit::getLastError('daily');

if ($lastError !== null) {
    echo "Last error: {$lastError}\n";
} else {
    echo "No errors found in daily channel\n";
}

// With stack trace
$fullError = LaraLogsToolkit::getLastError('daily', true);
if ($fullError) {
    // Contains full error with stack trace
    echo $fullError;
}

use Ravols\LaraLogsToolkit\Facades\LaraLogsToolkit;

// Get last record (any log level) - message only
$record = LaraLogsToolkit::getLastRecord();

// Get last record from specific channel
$record = LaraLogsToolkit::getLastRecord('api');

// Get last record with stack trace
$record = LaraLogsToolkit::getLastRecord('stack', true);

// Get last record with stack trace from specific channel
$record = LaraLogsToolkit::getLastRecord('api', true);

$lastRecord = LaraLogsToolkit::getLastRecord('daily');

if ($lastRecord !== null) {
    echo "Last log entry: {$lastRecord}\n";
} else {
    echo "No log entries found in daily channel\n";
}

// With stack trace (if available)
$fullRecord = LaraLogsToolkit::getLastRecord('daily', true);
if ($fullRecord) {
    // Contains full log entry with stack trace
    echo $fullRecord;
}

php artisan tinker

>>> lastError()
=> "SQLSTATE[HY000] [2002] Connection refused"

>>> lastError('api')
=> "Route not found: GET /api/users"

>>> lastError('stack', true)
=> "[2025-01-03 10:30:45] local.ERROR: SQLSTATE[HY000] [2002] Connection refused
[stack trace]
#0 /path/to/file.php(123): function()
..."

php artisan tinker

>>> lastRecord()
=> "User logged in successfully"

>>> lastRecord('api')
=> "API request processed"

>>> lastRecord('stack', true)
=> "[2025-01-03 10:30:45] local.INFO: User logged in successfully
[stack trace]
#0 /path/to/file.php(123): function()
..."
bash
php artisan vendor:publish --tag=lara-logs-toolkit-config
json
{
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi",
            "@php artisan lara-logs:composer-dump-autoload"
        ]
    }
}
bash
php artisan lara-logs:check-records [channel]
bash
# Check the default channel (from config)
php artisan lara-logs:check-records

# Check a specific channel
php artisan lara-logs:check-records daily
php artisan lara-logs:check-records api
bash
php artisan lara-logs:delete-logs