PHPackages                             ravols/lara-logs-toolkit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. ravols/lara-logs-toolkit

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

ravols/lara-logs-toolkit
========================

LaraLogsToolkit is a package that allows you to analyze your logs and get the count of errors, info and warnings.

1.1.0(4mo ago)03[1 PRs](https://github.com/ravols/lara-logs-toolkit/pulls)MITPHPPHP ^8.2CI passing

Since Dec 26Pushed 1mo agoCompare

[ Source](https://github.com/ravols/lara-logs-toolkit)[ Packagist](https://packagist.org/packages/ravols/lara-logs-toolkit)[ Docs](https://github.com/ravols/lara-logs-toolkit)[ GitHub Sponsors](https://github.com/:vendor_name)[ RSS](/packages/ravols-lara-logs-toolkit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (3)Versions (6)Used By (0)

Lara Logs Toolkit
=================

[](#lara-logs-toolkit)

A Laravel package that helps you track deployments and monitor log file growth by providing deployment markers and log record counting capabilities.

Problems This Package Solves
----------------------------

[](#problems-this-package-solves)

### Problem 1: Log Files Filling Up After Deployment

[](#problem-1-log-files-filling-up-after-deployment)

**The Issue:** After a deployment, your logs might start filling up with errors, but if you're distracted or not actively monitoring, you might miss critical issues until they become severe.

**The Solution:** This package provides a command to quickly check how many log records exist in any specified log channel from your `config/logging.php`. Run it after deployments or set it up in monitoring to get instant visibility into log growth.

**Extended Possibilities:** You can create your own custom commands that check for new log records and send notifications (Slack, email, or SMS) when a threshold is met. This allows you to set up automated alerting that triggers when log growth exceeds acceptable levels after deployments.

### Problem 2: When Did Errors Occur?

[](#problem-2-when-did-errors-occur)

**The Issue:** When you see errors in your logs, it's often impossible to tell if they happened before or after your latest deployment. This makes debugging much harder, especially when you need to determine if a deployment introduced new issues.

**The Solution:** This package automatically logs a timestamp marker whenever `composer dump-autoload` finishes. By adding a single line to your `composer.json`, you'll have clear deployment markers in your logs, making it easy to see which errors occurred before or after each deployment.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require ravols/lara-logs-toolkit
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=lara-logs-toolkit-config
```

This will create `config/lara-logs-toolkit.php` where you can configure the composer dump-autoload log channel and cache settings:

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

**Configuration Options:**

- `composer_dump_autoload_channel` - The log channel where the composer dump-autoload notification will be written. This should match one of the channels defined in your application's logging configuration (default: `daily`)
- `comparison_cache_ttl` - Cache time-to-live in seconds for storing log analysis comparison results (default: `600` seconds / 10 minutes)

Usage
-----

[](#usage)

### Deployment Tracking

[](#deployment-tracking)

To automatically log when `composer dump-autoload` finishes, you need to add the command to your `composer.json` file.

**Step 1:** Open your `composer.json` file in the root of your Laravel project.

**Step 2:** Find the `scripts` section. If it doesn't exist, create it at the root level of your JSON.

**Step 3:** Add or update the `post-autoload-dump` array. Add `"@php artisan lara-logs:composer-dump-autoload"` as the last item in the array.

**Example - of a `post-autoload-dump` script:**

```
{
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi",
            "@php artisan lara-logs:composer-dump-autoload"
        ]
    }
}
```

**Important:** The line `"@php artisan lara-logs:composer-dump-autoload"` should be added as the **last item** in the `post-autoload-dump` array, after the existing Laravel commands.

Now, every time you run `composer dump-autoload` (which happens automatically during deployments), you'll see a log entry like:

```
[2025-12-25 11:01:23] local.INFO: Composer dump-autoload finished at 2025-12-25 11:01:23

```

This creates a clear marker in your logs, making it easy to identify which errors occurred before or after each deployment.

### Checking Log Record Counts

[](#checking-log-record-counts)

To check how many log records exist in a specific channel:

```
php artisan lara-logs:check-records [channel]
```

If no channel is specified, it defaults to `daily`.

**Examples:**

```
# 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
```

The command will output:

```
Channel 'daily' contains 1523 log record(s).

```

This is especially useful after deployments to quickly see if error counts have increased, or you can integrate it into your monitoring/alerting system.

### Deleting Log Records

[](#deleting-log-records)

To delete log records from configured log channels:

```
php artisan lara-logs:delete-logs
```

**Options:**

- `--channels=*` - Comma-separated list of log channel names to delete (e.g., `--channels=daily,api`)
- `--action=` - Delete action: `latest` or `all` (defaults to interactive selection)

**Examples:**

```
# Interactive mode - select channels and action
php artisan lara-logs:delete-logs

# Delete all logs from specific channels
php artisan lara-logs:delete-logs --channels=daily,api --action=all

# Delete latest record from a single channel
php artisan lara-logs:delete-logs --channels=single --action=latest

# Multiple channels with comma-separated list
php artisan lara-logs:delete-logs --channels=daily,api --action=all
```

**Interactive Features:**

- If no channels are specified, you'll be prompted with an interactive multisearch to select one or more channels
- If no action is specified, you'll be prompted to choose between:
    - **Delete only latest record** - Deletes the latest log file
    - **Delete all logs** - Deletes all log files for the selected channel(s)

**Safety Features:**

- In production environment, you'll be prompted for confirmation before deletion
- The command validates that selected channels exist in your logging configuration
- Provides success/error counts for batch operations

**Delete Actions:**

- `latest` - Deletes the latest log file for each selected channel
- `all` - Deletes all log files for each selected channel (handles both single and daily log file formats)

### Comparing Log Analysis with Cached Results

[](#comparing-log-analysis-with-cached-results)

The package provides a method to compare current log analysis with previously cached results. This is useful for detecting changes in log counts over time:

```
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";
}
```

The method automatically caches the current analysis results for comparison on the next call. The cache TTL is configurable via `config/lara-logs-toolkit.php` using the `comparison_cache_ttl` key (default: 600 seconds).

**Return Type:** `LogAnalysisComparisonData` containing:

- `current` - `LogCountsData` with current log counts by level
- `cached` - `LogCountsData` with previously cached log counts
- `differences` - `LogCountsData` showing the difference between current and cached (current - cached)
- `logFileName` - The log file name used for caching
- `cachedAt` - DateTime string (e.g., "2025-01-15 10:30:45") indicating when the cache was created, or `null` if no cache existed

**LogCountsData Properties:**

- `error`, `info`, `warning`, `emergency`, `alert`, `critical`, `debug`, `notice` - Individual log level counts
- `getTotal()` - Get total count across all levels

### Analyzing All Log Channels

[](#analyzing-all-log-channels)

You can analyze all log channels at once using `getAllChannelsLogAnalysis()`. This method automatically excludes certain channels by default (like `stack`, `null`, `single`, `daily`, etc.) but allows you to customize which channels to include or exclude.

```
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::includeChannels('stack')
    ->getAllChannelsLogAnalysis();

// Chain configuration methods
$analysis = LaraLogsToolkit::excludeChannels(['carriers'])
    ->includeChannels('stack')
    ->getAllChannelsLogAnalysis(useCache: true);
```

**Default Excluded Channels:** `single`, `daily`, `null`, `papertrail`, `stderr`, `syslog`, `errorlog`, `slack`, `emergency`

**AllChannelsLogAnalysisData Methods:**

- `getChannel(string $channelName)` - Get data for a specific channel
- `getChannels()` - Get all channels data
- `getError()`, `getInfo()`, `getWarning()`, etc. - Aggregated totals across all channels
- `getTotal()` - Total count across all channels and log levels
- `getComparisonChannel(string $channelName)` - Get comparison data for a channel
- `hasComparisonData()` - Check if any channels have comparison data
- `toArray()` - Convert to array format

### Creating Custom Alert Commands

[](#creating-custom-alert-commands)

You can create your own commands that monitor log growth and send notifications when thresholds are exceeded. Here's an example:

```
