PHPackages                             larsgmortensen/litelog - 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. larsgmortensen/litelog

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

larsgmortensen/litelog
======================

Ultra-fast, lightweight JSON logger for PHP with atomic append and safe log rotation.

v1.0.1(9mo ago)0221GPL-3.0-or-laterPHPPHP &gt;=8.0

Since Sep 18Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/LarsGMortensen/LiteLog)[ Packagist](https://packagist.org/packages/larsgmortensen/litelog)[ Docs](https://github.com/LarsGMortensen/LiteLog)[ RSS](/packages/larsgmortensen-litelog/feed)WikiDiscussions main Synced today

READMEChangelog (1)DependenciesVersions (3)Used By (1)

LiteLog – A Lightweight &amp; High-Performance JSON Logger for PHP
==================================================================

[](#litelog--a-lightweight--high-performance-json-logger-for-php)

LiteLog is a **fast, minimal, efficient, single-file JSON logger** focused on **robustness** and **runtime performance**.
It provides **atomic appends**, **safe log rotation**, and **strict error handling** with zero dependencies.
Designed for high-traffic PHP applications that require **reliable logging** without external bloat (**PHP 8.0+**).

---

🚀 Features that make LiteLog stand out
--------------------------------------

[](#-features-that-make-litelog-stand-out)

- **Blazing-fast writes** – Appends JSON lines with atomic `LOCK_EX` safety.
- **Safe concurrency** – Multiple processes can write concurrently without losing lines.
- **Log rotation** – Automatically rotates logs when file size exceeds threshold.
- **Retention policy** – Configurable pruning of old rotated logs.
- **JSON by default** – Structured, machine-readable logs with `timestamp`, `category`, `message`, and optional `context`.
- **Error-hardening** – Fails fast if directory is missing, not writable, or JSON encoding fails.
- **Minimal overhead** – One file, static API, no runtime dependencies.
- **Secure by default** – Filenames are sanitized to prevent path traversal attacks.
- **Production-ready** – Verified by functional, benchmark, and concurrency tests.

---

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

[](#-installation)

Via Composer (recommended):

```
composer require larsgmortensen/litelog
```

Or manually include the class file (e.g. `src/LiteLog/LiteLog.php`) with Composer’s autoloader or `require_once`:

```
use LiteLog\LiteLog;
require_once __DIR__.'/src/LiteLog/LiteLog.php';
```

> **Tip:** Always place your log directory **outside webroot**, or protect it with `.htaccess`.

---

🚀 Quick Start
-------------

[](#-quick-start)

```
use LiteLog\LiteLog;

// Configure once at bootstrap
LiteLog::setDefaultDir('/path/to/logs');
LiteLog::setMaxFileSize(10 * 1024 * 1024); // 10 MB
LiteLog::setMaxRotatedFiles(5);            // keep 5 rotated files

// Write a log line
LiteLog::log(
    'app.json',  // Log filename (relative to log dir)
    'info',  // Category
    'Coffee supply is critically low',  // Message (string or array)
    ['cups_left' => 1, 'developer' => 'Sleepy']  // Context (optional)
);
```

### Example log output (JSON line)

[](#example-log-output-json-line)

```
{
  "timestamp": "2025-09-18 02:53:18",
  "category": "warning",
  "message": "Coffee supply is critically low",
  "context": {
    "cups_left": 1,
    "developer": "Sleepy"
  }
}
```

---

🧰 API
-----

[](#-api)

```
LiteLog::setDefaultDir(string $dir, bool $createIfMissing = false): void
LiteLog::setMaxFileSize(int $bytes): void
LiteLog::setMaxRotatedFiles(?int $count): void
LiteLog::log(string $file, string $category, string|array|object $message, array $context = []): void
```

**Parameters**

- **$dir**: Log directory (must exist unless `$createIfMissing=true`).
- **$file**: Filename (e.g. `app.json`). Must be a clean name, no path traversal.
- **$category**: Category string (`error`, `info`, etc.).
- **$message**: String, array, or object. Arrays/objects are JSON-encoded automatically.
- **$context**: Optional associative array with extra metadata (e.g., request id, ip).
- **$bytes**: Maximum file size before rotation. Default: 10 MB.
- **$count**: Number of rotated logs to keep. `null` disables pruning.

---

📖 Usage Notes
-------------

[](#-usage-notes)

- All log entries are **one JSON line per entry** → easy to parse with tools like `jq` or ELK.
- Rotation creates files like `app_1695030618123.json`.
- If retention is set, only the latest N rotated logs are kept; older are pruned.
- Fail-fast philosophy: if directory is missing or not writable, LiteLog throws immediately.

---

🧪 Tests
-------

[](#-tests)

LiteLog is verified by three test suites:

1. **Sanity tests** (`test_litelog_new.php`) Validates JSON encoding, rotation, retention, and path sanitization.
2. **Benchmarks** (`bench_litelog.php`, `bench_litelog_web.php`) Measures performance vs. old implementation. Results (shared hosting, 100k lines):

    - OLD: ~1643 ops/s
    - NEW: ~1476 ops/s (≈10% overhead for safe locking)
3. **Concurrency test** (`concurrency_run.php`) Spawns multiple parallel PHP processes writing to the same log file. ✅ 400 000 lines written without loss or duplication under rotation.

---

💡 Why LiteLog?
--------------

[](#-why-litelog)

LiteLog exists for developers who want **reliable structured logging** without dragging in heavy frameworks.

✨ **Fast** – 1.5–2k ops/s even on modest hardware.

✨ **Safe** – Atomic writes, no lost lines under concurrency.

✨ **Structured** – JSON lines are machine-readable.

✨ **Lightweight** – One file, static API, no dependencies.

✨ **Robust** – Strict error handling, sanitization, rotation + retention built-in.

---

📦 Packagist
-----------

[](#-packagist)

LiteLog on Packagist: 👉

---

📜 License
---------

[](#-license)

LiteLog is released under the **GNU General Public License v3.0**. See [LICENSE](LICENSE) for details.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Fork, submit issues, or open a pull request.

---

✍️ Author
---------

[](#️-author)

Developed by **Lars Grove Mortensen** © 2025. Feel free to reach out or contribute!

---

LiteLog – the lightweight JSON logger you can trust 🚀

---

🌟 **If you find this library useful, give it a star on GitHub!** 🌟

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance58

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

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 ~10 days

Total

2

Last Release

278d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e00ea2f83af8b74d6813e4a7e97f3095308fd56d1047f3a791b50f699798c5ca?d=identicon)[LarsGMortensen](/maintainers/LarsGMortensen)

---

Top Contributors

[![LarsGMortensen](https://avatars.githubusercontent.com/u/26773745?v=4)](https://github.com/LarsGMortensen "LarsGMortensen (9 commits)")

---

Tags

phpjsonconcurrencyloggingloggerlightweightPSR-4rotation

### Embed Badge

![Health badge](/badges/larsgmortensen-litelog/health.svg)

```
[![Health](https://phpackages.com/badges/larsgmortensen-litelog/health.svg)](https://phpackages.com/packages/larsgmortensen-litelog)
```

###  Alternatives

[justbetter/magento2-sentry

Magento 2 Logger for Sentry

1861.6M3](/packages/justbetter-magento2-sentry)[logtail/monolog-logtail

Logtail handler for Monolog

243.6M3](/packages/logtail-monolog-logtail)

PHPackages © 2026

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