PHPackages                             maatify/psr-logger - 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. maatify/psr-logger

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

maatify/psr-logger
==================

PSR-3 compatible logger with dynamic file naming and hourly rotation, powered by Monolog

v1.0.3(5mo ago)24.3k↑31.7%14MITPHPPHP ^8.2CI passing

Since Nov 5Pushed 5mo agoCompare

[ Source](https://github.com/Maatify/psr-logger)[ Packagist](https://packagist.org/packages/maatify/psr-logger)[ Docs](https://github.com/Maatify/psr-logger)[ RSS](/packages/maatify-psr-logger/feed)WikiDiscussions main Synced today

READMEChangelog (4)Dependencies (5)Versions (5)Used By (4)

[![Maatify.dev](https://camo.githubusercontent.com/bb8bf9ee079d7f823c9d5e94061d1d4c11dc0898e2b1b5cc9a8a7b04d8bfdd7d/68747470733a2f2f7777772e6d6161746966792e6465762f6173736574732f696d672f696d672f6d6161746966795f6c6f676f5f77686974652e737667)](https://camo.githubusercontent.com/bb8bf9ee079d7f823c9d5e94061d1d4c11dc0898e2b1b5cc9a8a7b04d8bfdd7d/68747470733a2f2f7777772e6d6161746966792e6465762f6173736574732f696d672f696d672f6d6161746966795f6c6f676f5f77686974652e737667)

---

🧾 maatify/psr-logger
====================

[](#-maatifypsr-logger)

[![Version](https://camo.githubusercontent.com/7876183bc670391b64c7818fa929ae5b167dc5ea479d7ba7c4e16be9ac0715f8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6161746966792f7073722d6c6f676765723f6c6162656c3d56657273696f6e26636f6c6f723d344331)](https://packagist.org/packages/maatify/psr-logger)[![PHP](https://camo.githubusercontent.com/4b4ad2587708963e21a58f3ca5f3c0da46d790838b38ac1dce17723d19b17af6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6d6161746966792f7073722d6c6f676765723f6c6162656c3d50485026636f6c6f723d373737424233)](https://packagist.org/packages/maatify/psr-logger)[![Build](https://github.com/Maatify/psr-logger/actions/workflows/ci.yml/badge.svg?label=Build&color=brightgreen)](https://github.com/Maatify/psr-logger/actions/workflows/ci.yml)[![Monthly Downloads](https://camo.githubusercontent.com/6fa255d912dc2a78b243c187bc896a42af2d72f782544ffa0cdd73076b341c91/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6d6161746966792f7073722d6c6f676765723f6c6162656c3d4d6f6e74686c79253230446f776e6c6f61647326636f6c6f723d303041384538)](https://packagist.org/packages/maatify/psr-logger)[![Total Downloads](https://camo.githubusercontent.com/99486e70aba7f39143cdf80d0d0c80d85c1b83a9ff9e7bc38f08650fb752e8ee/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6161746966792f7073722d6c6f676765723f6c6162656c3d546f74616c253230446f776e6c6f61647326636f6c6f723d324141)](https://packagist.org/packages/maatify/psr-logger)[![Stars](https://camo.githubusercontent.com/5261da42d03bdf15afb1ff1ea56a4f008a58882a07c323fd571fb4f218a17bb6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f4d6161746966792f7073722d6c6f676765723f6c6162656c3d537461727326636f6c6f723d464644343342)](https://github.com/Maatify/psr-logger/stargazers)[![License](https://camo.githubusercontent.com/1b07b8641e0137b1157c41103a5cddf074592020979f205145df382099c394b4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f4d6161746966792f7073722d6c6f676765723f6c6162656c3d4c6963656e736526636f6c6f723d626c756576696f6c6574)](LICENSE)![Status](https://camo.githubusercontent.com/2128a821a9f55f8f5e5806efa8de7dfe863140215ec85b68a1d4301610cfdd32/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d737563636573733f7374796c653d666c61742d737175617265)[![Code Quality](https://camo.githubusercontent.com/2f6b20848f98f2bbbc69d18010d6332c18a13169156ad59fdd044379cd879620/68747470733a2f2f696d672e736869656c64732e696f2f636f6465666163746f722f67726164652f6769746875622f4d6161746966792f7073722d6c6f676765722f6d61696e)](https://www.codefactor.io/repository/github/Maatify/psr-logger)

---

A **PSR-3 compatible logger** powered by **Monolog**, supporting **dynamic file naming**, **hourly log rotation**, and **project-aware path detection**. Built for professional PHP projects that need organized, flexible, and standards-compliant logging.

> 🔗 [بالعربي 🇸🇦 ](./README-AR.md)

---

### 🧱 Built on Monolog

[](#-built-on-monolog)

This package is powered by [**Monolog v3**](https://github.com/Seldaek/monolog) — the industry-standard logging library for PHP.
It extends Monolog with **automatic path detection**, **hourly rotation**, and **project-aware file structure**, making it ideal for scalable and professional PHP applications.

---

📦 Installation
--------------

[](#-installation)

Install via Composer:

```
composer require maatify/psr-logger
```

---

### 📦 Dependencies

[](#-dependencies)

This library relies on:

DependencyPurposeLink**monolog/monolog**Core logging framework for PHP (v3)[github.com/Seldaek/monolog](https://github.com/Seldaek/monolog)**psr/log**PSR-3 compliant interface for logging interoperability[php-fig.org/psr/psr-3](https://www.php-fig.org/psr/psr-3/)**vlucas/phpdotenv**Environment variable management for dynamic log paths[github.com/vlucas/phpdotenv](https://github.com/vlucas/phpdotenv)**phpunit/phpunit**Unit testing framework (development only)[phpunit.de](https://phpunit.de)> 🧱 `maatify/psr-logger` builds upon these open-source libraries to provide a **unified**, **context-aware**, and **developer-friendly** logging experience across all Maatify packages.

---

⚙️ Features
-----------

[](#️-features)

- ✅ PSR-3 compatible (`Psr\Log\LoggerInterface`)
- ✅ Built on **Monolog v3**
- ✅ Smart file rotation by date/hour (`Y/m/d/H`)
- ✅ Dynamic file naming by class or custom context
- ✅ Works both standalone or inside any Composer project
- ✅ Optional log cleanup (manual or via cron)
- ✅ Zero configuration — auto-detects project root

---

🧩 Usage
-------

[](#-usage)

### Basic Example

[](#basic-example)

```
use Maatify\PsrLogger\LoggerFactory;

$logger = LoggerFactory::create('services/payment');
$logger->info('Payment started', ['order_id' => 501]);
```

Resulting file:

```
storage/logs/2025/11/05/10/services/payment.log

```

### ⚙️ Auto Context Detection (Class-based Logging)

[](#️-auto-context-detection-class-based-logging)

Automatically detects and uses the calling class name as the logging context — no need to specify it manually.

```
use Maatify\PsrLogger\Traits\LoggerContextTrait;

class UserService
{
    use LoggerContextTrait;

    public function __construct()
    {
        // Option 1️⃣ — Initialize once and use via $this->logger
        $this->initLogger(); // auto context → logs/UserService.log
        $this->logger->info('User service initialized.');

        // Option 2️⃣ — (New in v1.0.1) Get the logger instance directly
        $logger = $this->initLogger('services/user');
        $logger->debug('Inline logger usage example.');
    }
}
```

**Resulting files:**

```
storage/logs/2025/11/05/10/UserService.log
storage/logs/2025/11/05/10/services/user.log

```

---

### 🧱 Custom Context Example

[](#-custom-context-example)

You can override the automatic context by specifying a custom path or namespace. This is useful for grouping logs by module or feature (e.g., `services/payment`, `queue/worker`, etc.).

```
use Maatify\PsrLogger\Traits\LoggerContextTrait;

class PaymentProcessor
{
    use LoggerContextTrait;

    public function __construct()
    {
        // Initialize logger with a custom context
        $this->initLogger('services/payment');
        $this->logger->info('Payment processor initialized.');
    }

    public function process(int $orderId): void
    {
        // Direct inline usage — available since v1.0.1
        $logger = $this->initLogger('services/payment/process');
        $logger->info('Processing order', ['order_id' => $orderId]);
    }
}
```

**Resulting file:**

```
storage/logs/2025/11/05/10/services/payment/process.log

```

---

### ⚡ Static Logger for Utility &amp; Bootstrap Classes (New in v1.0.2)

[](#-static-logger-for-utility--bootstrap-classes-new-in-v102)

When working with **static classes**, such as `Bootstrap`, `CronRunner`, or `FileLockManager`, you can now use the **StaticLoggerTrait** to obtain PSR-3 loggers without class instantiation.

```
use Maatify\PsrLogger\Traits\StaticLoggerTrait;

final class Bootstrap
{
    use StaticLoggerTrait;

    public static function init(): void
    {
        $logger = self::getLogger('bootstrap/init');
        $logger->info('Bootstrap initialized successfully');
    }
}
```

**Resulting file:**

```
storage/logs/2025/11/10/10/bootstrap/init.log

```

This makes it easy to integrate consistent logging even inside global initializers, CLI runners, or static utility helpers.

---

ModeDescriptionExampleSince**Static Trait**For static classes (no instantiation)`self::getLogger('bootstrap/init')`**v1.0.2**---

### 🧩 Summary

[](#-summary)

ModeDescriptionExampleSince**Factory-based**Create standalone logger`LoggerFactory::create('context')`v1.0.0**Trait (init-only)**Initializes `$this->logger` for class-wide use`$this->initLogger()`v1.0.0**Trait (return)**Returns logger instance directly for inline use`$logger = $this->initLogger('context')`**v1.0.1**---

🧱 Folder Structure
------------------

[](#-folder-structure)

```
maatify-psr-logger/
├── src/
│   ├── Config/
│   │   └── LoggerConfig.php
│   ├── Helpers/
│   │   └── PathHelper.php
│   ├── Rotation/
│   │   └── LogCleaner.php
│   ├── Traits/
│   │   └── LoggerContextTrait.php
│   └── LoggerFactory.php
├── scripts/
│   └── clean_logs.php
├── .env.example
├── composer.json
└── README.md

```

---

🧹 Log Cleanup (manual or cron)
------------------------------

[](#-log-cleanup-manual-or-cron)

You can run the provided script to delete old log files manually or via cron.

### 1. Manual Cleanup

[](#1-manual-cleanup)

```
php vendor/maatify/psr-logger/scripts/clean_logs.php
```

### 2. Composer Shortcut

[](#2-composer-shortcut)

Add to your project’s `composer.json`:

```
"scripts": {
  "logs:clean": "php vendor/maatify/psr-logger/scripts/clean_logs.php"
}

```

Then run:

```
composer logs:clean
```

### 3. Cron Job Example

[](#3-cron-job-example)

```
0 3 * * * php /var/www/project/vendor/maatify/psr-logger/scripts/clean_logs.php >> /var/log/log_cleanup.log 2>&1
```

---

⚙️ Environment Variables
------------------------

[](#️-environment-variables)

VariableDefaultDescription`LOG_PATH``storage/logs`Base directory for log files`LOG_RETENTION_DAYS``14`Number of days to keep logs (used by cleanup)Example `.env` file:

```
LOG_PATH=storage/logs
LOG_RETENTION_DAYS=14
```

### 🌿 Optional: Environment Initialization

[](#-optional-environment-initialization)

This package ships with [**vlucas/phpdotenv**](https://github.com/vlucas/phpdotenv)
to simplify environment configuration management.

> The logger itself **does not automatically load** your `.env` file. You should initialize it at the project level before using the logger.

Example:

```
use Dotenv\Dotenv;
use Maatify\PsrLogger\LoggerFactory;

require __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();

$logger = LoggerFactory::create('bootstrap/test');
$logger->info('Logger initialized successfully!');
```

---

🧭 Project Root Detection
------------------------

[](#-project-root-detection)

If the library is installed inside:

```
vendor/maatify/psr-logger

```

it automatically goes **3 levels up** to the project root. If running standalone (during development), it uses its own root directory.

---

🔌 Integration Examples
----------------------

[](#-integration-examples)

### 🪶 Slim Framework

[](#-slim-framework)

```
use Maatify\PsrLogger\LoggerFactory;

$container->set('logger', function() {
    return LoggerFactory::create('slim/app');
});

// Example usage inside a route:
$app->get('/ping', function ($request, $response) {
    $this->get('logger')->info('Ping request received');
    return $response->write('pong');
});
```

---

### 🧱 Laravel

[](#-laravel)

In `app/Providers/AppServiceProvider.php`:

```
use Maatify\PsrLogger\LoggerFactory;

public function register()
{
    $this->app->singleton('maatify.logger', function () {
        return LoggerFactory::create('laravel/app');
    });
}
```

Usage anywhere:

```
app('maatify.logger')->info('Laravel integration working!');
```

---

### ⚙️ Native PHP Project

[](#️-native-php-project)

```
require __DIR__ . '/vendor/autoload.php';

use Maatify\PsrLogger\LoggerFactory;

$logger = LoggerFactory::create('custom/project');
$logger->error('Something went wrong', ['code' => 500]);
```

---

📚 Built Upon
------------

[](#-built-upon)

`maatify/psr-logger` proudly builds upon several mature and industry-standard open-source foundations:

LibraryDescriptionUsage in Project**[monolog/monolog](https://github.com/Seldaek/monolog)**Industry-standard PHP logging library (v3)Core logging engine used for structured logging, channel management, and handler pipeline.**[psr/log](https://www.php-fig.org/psr/psr-3/)**PSR-3 logging interfaceDefines the standardized logger interface used by all Maatify components.**[vlucas/phpdotenv](https://github.com/vlucas/phpdotenv)**Environment configuration managerLoads and manages environment variables for dynamic log paths and environment detection.**[phpunit/phpunit](https://phpunit.de)**PHP unit testing frameworkPowers the automated test suite and CI/CD validation through GitHub Actions.> Huge thanks to the open-source community for their continued contributions, enabling Maatify to build reliable, scalable, and developer-friendly PHP infrastructure. ❤️

---

🔗 Documentation &amp; Resources
-------------------------------

[](#-documentation--resources)

FileDescription[📘 CHANGELOG.md](./CHANGELOG.md)Version history and release notes[📄 LICENSE](./LICENSE)Project license (MIT)[📦 composer.json](./composer.json)Package metadata and dependencies[🧱 CONTRIBUTING.md](./CONTRIBUTING.md)Contribution and coding standards[🧾 VERSION](./VERSION)Current release version---

🪪 License
---------

[](#-license)

**[MIT License](LICENSE)** © [Maatify.dev](https://www.maatify.dev)
You’re free to use, modify, and distribute this library with proper attribution.

---

👥 Authors &amp; Credits
-----------------------

[](#-authors--credits)

This library is part of the **Maatify.dev Core Ecosystem**, developed and maintained under the technical leadership of:

**👤 Mohamed Abdulalim** — *Backend Lead &amp; Technical Architect*
Lead architect of the **Maatify Backend Infrastructure**, overseeing the architecture, core library design, and technical standardization across all backend modules within the Maatify ecosystem.
🔗 [Maatify.dev](https://www.maatify.dev) | ✉️

**🤝 Contributors**
The **Maatify.dev Engineering Team** and open-source collaborators who continuously refine, test, and extend the capabilities of this library across multiple Maatify projects.

> 🧩 This project represents a unified engineering effort led by Mohamed Abdulalim, ensuring that every Maatify backend component adheres to the same secure, consistent, and maintainable foundation.

---

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance70

Regular maintenance activity

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~22 days

Total

4

Last Release

173d ago

PHP version history (2 changes)1.0.0PHP ^8.4

v1.0.3PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/1a885a0810f2762586520ab284c9019aaf0b650b53cdf2a6c13ea10931bb7795?d=identicon)[Maatify](/maintainers/Maatify)

---

Top Contributors

[![megyptm](https://avatars.githubusercontent.com/u/33574895?v=4)](https://github.com/megyptm "megyptm (26 commits)")

---

Tags

psr-3phploggingloggermonologmaatifymaatify.devhourly-rotation

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/maatify-psr-logger/health.svg)

```
[![Health](https://phpackages.com/badges/maatify-psr-logger/health.svg)](https://phpackages.com/packages/maatify-psr-logger)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k38.9k](/packages/matomo-matomo)[illuminate/log

The Illuminate Log package.

6225.3M623](/packages/illuminate-log)[inpsyde/wonolog

Monolog-based logging package for WordPress.

184637.3k7](/packages/inpsyde-wonolog)

PHPackages © 2026

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