PHPackages                             jiordiviera/laravel-log-cleaner - 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. jiordiviera/laravel-log-cleaner

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

jiordiviera/laravel-log-cleaner
===============================

A Laravel package to easily clean the log files.

2.2.0(3mo ago)72.7k↑266.1%2MITPHPPHP ^8.2|^8.3CI passing

Since Oct 6Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/jiordiviera/laravel-log-cleaner)[ Packagist](https://packagist.org/packages/jiordiviera/laravel-log-cleaner)[ RSS](/packages/jiordiviera-laravel-log-cleaner/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (3)Dependencies (12)Versions (14)Used By (0)

██╗ █████╗ ██████╗ █████╗ ██╗ ██╗███████╗██╗ ██║ ██╔══██╗██╔══██╗██╔══██╗██║ ██║██╔════╝██║ ██║ ███████║██████╔╝███████║██║ ██║█████╗ ██║ ██║ ██╔══██║██╔══██╗██╔══██║╚██╗ ██╔╝██╔══╝ ██║ ███████╗██║ ██║██║ ██║██║ ██║ ╚████╔╝ ███████╗███████╗ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚══════╝

██╗ ██████╗ ██████╗ ██║ ██╔═══██╗██╔════╝ ██║ ██║ ██║██║ ███╗ ██║ ██║ ██║██║ ██║ ███████╗╚██████╔╝╚██████╔╝ ╚══════╝ ╚═════╝ ╚═════╝

██████╗██╗ ███████╗ █████╗ ███╗ ██╗███████╗██████╗ ██╔════╝██║ ██╔════╝██╔══██╗████╗ ██║██╔════╝██╔══██╗ ██║ ██║ █████╗ ███████║██╔██╗ ██║█████╗ ██████╔╝ ██║ ██║ ██╔══╝ ██╔══██║██║╚██╗██║██╔══╝ ██╔══██╗ ╚██████╗███████╗███████╗██║ ██║██║ ╚████║███████╗██║ ██║ ╚═════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝

 [![Latest Stable Version](https://camo.githubusercontent.com/47293b311d1a8341d98cfe844c0f99a5640731b9adf333cedd706d7cdcddff13/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a696f72646976696572612f6c61726176656c2d6c6f672d636c65616e65723f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/jiordiviera/laravel-log-cleaner) [![Total Downloads](https://camo.githubusercontent.com/3d195c2e4e9c512323b387820949d9e110003801bffb4f501010370a11d26b20/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a696f72646976696572612f6c61726176656c2d6c6f672d636c65616e65723f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/jiordiviera/laravel-log-cleaner) [![Latest Unstable Version](https://camo.githubusercontent.com/c3eed65d90f84c10dc6591df7dd02f1cb5c5bfa1ce42eebefb0ea59bdc2a5758/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a696f72646976696572612f6c61726176656c2d6c6f672d636c65616e65723f696e636c7564655f70726572656c6561736573267374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/jiordiviera/laravel-log-cleaner) [![License](https://camo.githubusercontent.com/1557c5b5df788be9b64fe0b04c18ea1c6a609d9cd6c11b20f1d6c5204e063238/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a696f72646976696572612f6c61726176656c2d6c6f672d636c65616e65723f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/jiordiviera/laravel-log-cleaner) [![Tests Status](https://github.com/jiordiviera/laravel-log-cleaner/actions/workflows/tests.yml/badge.svg)](https://github.com/jiordiviera/laravel-log-cleaner/actions/workflows/tests.yml)

**Laravel Log Cleaner** is a utility package designed for the efficient management of Laravel log files. It allows developers to quickly clear log data using an Artisan command, enhancing application performance and management. This tool is compatible with Laravel versions 9, 10, 11, 12, and 13.

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

[](#installation)

You can install the package via **Composer** by executing the following command:

```
composer require jiordiviera/laravel-log-cleaner
```

### Publishing Configuration (Optional)

[](#publishing-configuration-optional)

To customize default behavior, publish the configuration file:

```
php artisan vendor:publish --provider="JiordiViera\LaravelLogCleaner\LaravelLogCleanerServiceProvider" --tag="log-cleaner-config"
```

Compatibility
-------------

[](#compatibility)

### Version 2.2+ (Current)

[](#version-22-current)

**PHP Requirements:**

- PHP 8.2+
- PHP 8.3+

**Laravel Support:**

- Laravel 9.x
- Laravel 10.x
- Laravel 11.x
- Laravel 12.x
- Laravel 13.x ✨

### Version 2.1 and below

[](#version-21-and-below)

For PHP 8.1:

- Use version 2.1.x or below
- Laravel 9.x to 12.x support

### Version 1.x (Legacy)

[](#version-1x-legacy)

For older PHP versions, use version 1.x:

- PHP 7.0+ to 8.2
- Laravel 7.x to 11.x

```
composer require jiordiviera/laravel-log-cleaner:^1.0
```

Usage
-----

[](#usage)

After installation, an Artisan command is available to clear the Laravel log file with advanced options:

### Basic Usage

[](#basic-usage)

1. **Clear all logs:**

    ```
    php artisan log:clear
    ```
2. **Clear logs older than specific days:**

    ```
    php artisan log:clear --days=30
    ```

### Advanced Features

[](#advanced-features)

#### 🔒 Safe Operations

[](#-safe-operations)

```
# Preview what would be deleted (dry run)
php artisan log:clear --days=30 --dry-run

# Create backup before cleaning
php artisan log:clear --days=30 --backup
```

#### 🎯 Targeted Cleaning

[](#-targeted-cleaning)

```
# Keep only ERROR level logs
php artisan log:clear --days=0 --level=ERROR

# Clean with custom date pattern
php artisan log:clear --days=30 --pattern="/^(\d{4}-\d{2}-\d{2})/"

# Clean only specific log file
php artisan log:clear --days=30 --file=laravel.log
```

#### 📦 Compression &amp; Memory

[](#-compression--memory)

```
# Compress old logs instead of deleting
php artisan log:clear --days=30 --compress

# Force memory-efficient processing for large files
php artisan log:clear --days=30 --memory-efficient
```

#### 🔧 Advanced Options

[](#-advanced-options)

```
# Disable file locking (for scripted operations)
php artisan log:clear --days=30 --no-lock

# Disable event dispatching (for performance)
php artisan log:clear --days=30 --no-events
```

#### 🚀 Combined Options

[](#-combined-options)

```
# Complete workflow with all safety features
php artisan log:clear --days=30 --backup --compress --level=ERROR --dry-run
```

### Programmatic Usage with Facade

[](#programmatic-usage-with-facade)

You can also use the `LogCleaner` facade to clear logs programmatically in your code:

```
use JiordiViera\LaravelLogCleaner\LogCleanerFacade as LogCleaner;

// Clear all logs
LogCleaner::clearAll();

// Clear logs older than 30 days
LogCleaner::clearOld(30);

// Clear with backup
LogCleaner::clearWithBackup(30);

// Clear with compression
LogCleaner::clearWithCompression(30);

// Clear only specific log file
LogCleaner::clearOld(30, 'laravel.log');

// Advanced usage with all options
LogCleaner::clear(
    days: 30,
    backup: true,
    compress: true,
    level: 'ERROR',
    pattern: '/^(\d{4}-\d{2}-\d{2})/',
    memoryEfficient: true,
    file: 'laravel.log'
);
```

### Available Options

[](#available-options)

OptionDescriptionExample`--days=N`Keep logs from last N days`--days=30``--backup`Create backup before cleaning`--backup``--dry-run`Preview changes without applying`--dry-run``--level=LEVEL`Filter by log level (ERROR, WARNING, INFO, DEBUG)`--level=ERROR``--pattern=REGEX`Custom date pattern matching`--pattern="/^(\d{4}-\d{2}-\d{2})/"``--compress`Compress old logs instead of deleting`--compress``--memory-efficient`Force memory-efficient processing`--memory-efficient``--file=FILENAME`Clean only specific log file`--file=laravel.log``--no-lock`Disable file locking`--no-lock``--no-events`Disable event dispatching`--no-events`### Examples

[](#examples)

- **Clear all logs:**

    ```
    $ php artisan log:clear
    ✅ All logs cleared - 1,250 lines removed, 45.2 MB freed
    ```
- **Clear logs older than 30 days:**

    ```
    $ php artisan log:clear --days=30
    ✅ Logs older than 30 days cleared - 850 lines removed, 32.1 MB freed
    ```
- **Preview changes (dry run):**

    ```
    $ php artisan log:clear --days=30 --dry-run
    🔍 Dry Run Mode - No changes will be made

    ┌─────────────┬───────────────┬───────────────┐
    │ File        │ Lines to Remove │ Space to Free │
    ├─────────────┼───────────────┼───────────────┤
    │ laravel.log │ 850           │ 32.1 MB       │
    └─────────────┴───────────────┴───────────────┘

    Total: 850 lines to be removed
    ```
- **Create backup and compress:**

    ```
    $ php artisan log:clear --days=30 --backup --compress

    ┌─────────────┬───────────────┬─────────────┬────────┬────────────┐
    │ File        │ Lines Removed │ Space Freed │ Backup │ Compressed │
    ├─────────────┼───────────────┼─────────────┼────────┼────────────┤
    │ laravel.log │ 850           │ 32.1 MB     │ ✓      │ ✓          │
    └─────────────┴───────────────┴─────────────┴────────┴────────────┘

    ✅ Logs older than 30 days cleared - 850 lines removed, 32.1 MB freed
    📦 1 backup(s) created
    🗜️ 1 file(s) compressed
    ```
- **Keep only ERROR logs:**

    ```
    $ php artisan log:clear --days=0 --level=ERROR
    ✅ All logs cleared - 1,100 lines removed, 38.5 MB freed
    ```

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

[](#configuration)

The package provides a comprehensive configuration file with sensible defaults. Publish it with:

```
php artisan vendor:publish --tag="log-cleaner-config"
```

### Configuration Options

[](#configuration-options)

```
return [
    // Default number of days to keep (0 = clear all)
    'days' => 0,

    // Memory threshold for automatic memory-efficient processing (50MB default)
    'memory_threshold' => 50 * 1024 * 1024,

    // Backup settings
    'backup' => [
        'enabled' => false,        // Enable backups by default
        'max_backups' => 5,        // Maximum backups to keep
        'auto_cleanup' => true,    // Auto-delete old backups
    ],

    // Compression settings
    'compression' => [
        'enabled' => false,        // Enable compression by default
        'level' => 9,              // Compression level (1-9)
    ],

    // Default log level filter (null = all levels)
    'level' => null,

    // Custom date pattern for parsing logs
    'pattern' => null,

    // Minimum free disk space (MB) required for backups
    'min_free_disk_space_mb' => 100,

    // File locking settings
    'locking' => [
        'enabled' => true,         // Enable file locking
        'timeout' => 30,           // Lock timeout in seconds
    ],

    // Event dispatching
    'events' => [
        'enabled' => true,         // Enable Laravel events
    ],
];
```

Events
------

[](#events)

The package dispatches Laravel events that you can listen to:

```
use JiordiViera\LaravelLogCleaner\Events\LogCleaning;
use JiordiViera\LaravelLogCleaner\Events\LogCleaned;
use JiordiViera\LaravelLogCleaner\Events\LogFileCleaned;

// In EventServiceProvider or elsewhere:
protected $listen = [
    LogCleaning::class => [
        LogCleaningListener::class,
    ],
    LogCleaned::class => [
        LogCleanedListener::class,
    ],
    LogFileCleaned::class => [
        LogFileCleanedListener::class,
    ],
];
```

### Event Properties

[](#event-properties)

**LogCleaning** (dispatched before cleaning starts):

- `$days`, `$backup`, `$compress`, `$level`, `$pattern`, `$memoryEfficient`, `$file`, `$dryRun`

**LogCleaned** (dispatched after cleaning completes):

- All properties from LogCleaning + `$results` (array of cleaning results)

**LogFileCleaned** (dispatched for each file cleaned):

- `$file`, `$linesRemoved`, `$bytesFreed`, `$backupPath`, `$compressedPath`

Exception Handling
------------------

[](#exception-handling)

The package uses custom exceptions for precise error handling:

```
use JiordiViera\LaravelLogCleaner\Exceptions\InvalidDaysException;
use JiordiViera\LaravelLogCleaner\Exceptions\NoLogFilesException;
use JiordiViera\LaravelLogCleaner\Exceptions\InvalidLogLevelException;
use JiordiViera\LaravelLogCleaner\Exceptions\InvalidPatternException;
use JiordiViera\LaravelLogCleaner\Exceptions\PermissionException;
use JiordiViera\LaravelLogCleaner\Exceptions\BackupException;
use JiordiViera\LaravelLogCleaner\Exceptions\DiskSpaceException;
use JiordiViera\LaravelLogCleaner\Exceptions\FileLockException;
use JiordiViera\LaravelLogCleaner\Exceptions\ZlibException;

try {
    LogCleaner::clear(days: -1);
} catch (InvalidDaysException $e) {
    // Handle invalid days parameter
}
```

Running Tests
-------------

[](#running-tests)

This package uses **Pest** for testing. You can run tests with the following command:

```
./vendor/bin/pest
```

### Static Analysis

[](#static-analysis)

The package includes PHPStan configuration for static analysis (level 4):

```
composer analyse
# or
./vendor/bin/phpstan analyse
```

### Code Formatting

[](#code-formatting)

The package uses Laravel Pint for code formatting:

```
# Format all files
composer format

# Check formatting without modifying
composer lint
```

Ensure your tests are organized correctly within the `tests/` directory.

Contributing
------------

[](#contributing)

Contributions are welcomed! Feel free to submit **Issues** or **Pull Requests** on [GitHub](https://github.com/jiordiviera/laravel-log-cleaner).

### Development Workflow

[](#development-workflow)

For contributors:

1. **Clone the repository:**

    ```
    git clone https://github.com/jiordiviera/laravel-log-cleaner.git
    ```
2. **Install dependencies:**

    ```
    composer install
    ```
3. **Run tests and static analysis:**

    ```
    ./vendor/bin/pest
    composer phpstan
    ```

What's New in v2.1
------------------

[](#whats-new-in-v21)

### 🎯 Configuration System

[](#-configuration-system)

- **Publishable config file** - Customize defaults without code changes
- **Default values** for days, backup, compression, log levels
- **Memory threshold** configuration
- **Lock timeout** settings

### 🔒 Enhanced Safety

[](#-enhanced-safety)

- **File locking** - Prevent concurrent cleaning operations
- **Disk space validation** - Ensure sufficient space before backups
- **Backup retention** - Auto-cleanup old backups (configurable)
- **Custom exceptions** - Precise error handling

### 📡 Events System

[](#-events-system)

- **LogCleaning** - Dispatched before cleaning starts
- **LogCleaned** - Dispatched after cleaning completes
- **LogFileCleaned** - Dispatched for each file cleaned
- **Configurable** - Disable events with `--no-events`

### 🎨 Improved CLI

[](#-improved-cli)

- **Beautiful table output** - Clear summary of operations
- **Emoji indicators** - Easy visual scanning
- **Detailed statistics** - Lines removed, space freed
- **Backup/compression status** - See what was created

### 🧪 Enhanced Testing

[](#-enhanced-testing)

- **Test helpers trait** - Reusable test utilities
- **Edge case coverage** - Empty files, unicode, large files
- **Event testing** - Verify event dispatching
- **Exception testing** - Comprehensive error coverage

### 📊 Code Quality

[](#-code-quality)

- **PHPStan level 8** - Strict static analysis
- **Custom exceptions** - Type-safe error handling
- **Better architecture** - Clean separation of concerns

About
-----

[](#about)

This package was created to streamline the management of log files in Laravel applications. Instead of manually clearing the log files, you can achieve this efficiently with a single command, with the option to selectively remove older logs.

License
-------

[](#license)

The Laravel Log Cleaner is open-source software licensed under the [MIT License](https://opensource.org/licenses/MIT).

---

> **Note:** This package requires PHP 8.1+ and Laravel 9.x or higher.

For further information, visit the [GitHub repository](https://github.com/jiordiviera/laravel-log-cleaner).

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance81

Actively maintained with recent releases

Popularity28

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 96.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~67 days

Recently: every ~76 days

Total

9

Last Release

99d ago

Major Versions

v1.0.4 → v2.0.02025-07-18

PHP version history (4 changes)v1.0.0PHP ^8.0

v1.0.3PHP ^7.0|^8.0|^8.1|^8.2

v2.0.0PHP ^8.1|^8.2|^8.3

2.2.0PHP ^8.2|^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/809a4ada50fc54fe02b1956bc85fbf9e403f3a8de208faf27dc5fd19b84d4035?d=identicon)[jiordiviera](/maintainers/jiordiviera)

---

Top Contributors

[![jiordiviera](https://avatars.githubusercontent.com/u/157500676?v=4)](https://github.com/jiordiviera "jiordiviera (152 commits)")[![karimalik](https://avatars.githubusercontent.com/u/40320510?v=4)](https://github.com/karimalik "karimalik (6 commits)")

---

Tags

loglaravelloggingartisanlaravel-packagemaintenancecleanerlog fileslog management

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jiordiviera-laravel-log-cleaner/health.svg)

```
[![Health](https://phpackages.com/badges/jiordiviera-laravel-log-cleaner/health.svg)](https://phpackages.com/packages/jiordiviera-laravel-log-cleaner)
```

###  Alternatives

[sentry/sentry-laravel

Laravel SDK for Sentry (https://sentry.io)

1.3k127.1M203](/packages/sentry-sentry-laravel)[laravel/sail

Docker files for running a basic Laravel application.

1.9k205.7M1.3k](/packages/laravel-sail)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M195](/packages/laravel-ai)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M165](/packages/spatie-laravel-health)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M7](/packages/propaganistas-laravel-disposable-email)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
