PHPackages                             hejunjie/lazylog - 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. hejunjie/lazylog

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

hejunjie/lazylog
================

轻量级 PHP 日志库，提供本地日志安全写入以及异常信息远程上报（同步/异步） | A lightweight PHP logging library providing safe local log writing and remote exception reporting (both synchronous and asynchronous)

v1.0.0(7mo ago)1185MITPHPPHP &gt;=7.4

Since Nov 11Pushed 7mo agoCompare

[ Source](https://github.com/zxc7563598/php-lazylog)[ Packagist](https://packagist.org/packages/hejunjie/lazylog)[ RSS](/packages/hejunjie-lazylog/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (1)DependenciesVersions (2)Used By (0)

hejunjie/lazylog
================

[](#hejunjielazylog)

 [English](./README.md)｜[简体中文](./README.zh-CN.md)---

A lightweight PHP logging library providing **safe local log writing** and **remote exception reporting** (both synchronous and asynchronous).

> Why this library exists:
> While working on my Go project [oh-shit-logger](https://github.com/zxc7563598/oh-shit-logger), I needed a centralized way to collect error information.
> Some friends were concerned about the performance overhead of PHP error reporting, so I wrapped my usual approach into a Composer package for easier reuse.

**This project has been parsed and summarized by Zread. For a quick overview, check here:** [Project Overview](https://zread.ai/zxc7563598/php-lazylog)

---

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

[](#installation)

```
composer require hejunjie/lazylog
```

---

Usage
-----

[](#usage)

​`lazylog` provides three core methods:

---

### Write Local Logs

[](#write-local-logs)

```
use Hejunjie\Lazylog\Logger;

/**
 * Write logs safely to local files (thread-safe + auto file rotation)
 *
 * @param string $basePath Base log directory (e.g. /var/logs or runtime/logs)
 * @param string $fileName Log filename (can include subpath like "error/app.log")
 * @param string $title Log title (e.g. "Error in Task #12")
 * @param string|array|object $content Log content (array, object, or string)
 * @param int $maxLines Max lines per file before rotation (default: 10,000)
 * @param int $maxSizeKB Max file size in KB before rotation (default: 2048 = 2MB)
 *
 * @return void
 */
Logger::write(
    '/var/logs',
    'error/app.log',
    'Task Failed',
    ['message' => 'Something went wrong']
);
```

---

### Asynchronous Exception Reporting

[](#asynchronous-exception-reporting)

- Uses `exec()` / `proc_open()` to spawn a background PHP process that sends a POST request
- Non-blocking for the main process
- **Not recommended** in long-running frameworks (Webman / Swoole)
    since they keep workers alive for a long time — frequent forking may accumulate resources (zombie processes, memory leaks, etc.)

```
try {
    // Code that may throw
} catch (\Throwable $exception) {
    /**
     * Report exception asynchronously to a remote endpoint.
     *
     * @param Throwable $exception The captured exception
     * @param string $url Remote endpoint URL
     * @param string $project Project identifier (default: unknown-project)
     * @param array $context Additional context data (e.g. request info, env vars)
     * @param string $phpBinary PHP binary path for subprocess (default: php)
     *
     * @return void
     */
    Logger::reportAsync($exception, 'https://error.example.com/collect', 'my-project');
}
```

> For low-frequency error reporting, the performance cost of forking a PHP subprocess is negligible.

---

### Synchronous Exception Reporting

[](#synchronous-exception-reporting)

- Recommended for long-running frameworks or when immediate reporting is needed
- Avoids creating subprocesses, preventing potential zombie or leaked processes Long-running workers in frameworks like Webman/Swoole are reused between requests — even if synchronous calls block, they only affect the current worker, not others.

```
try {
    // Code that may throw
} catch (\Throwable $exception) {
    /**
     * Report exception synchronously to a remote endpoint.
     *
     * @param Throwable $exception The captured exception
     * @param string $url Remote endpoint URL
     * @param string $project Project identifier (default: unknown-project)
     * @param array $context Additional context data
     * @param int $timeout Timeout in seconds
     *
     * @return void
     */
    Logger::reportSync($exception, 'https://error.example.com/collect', 'my-project');
}
```

#### Optimization Suggestion

[](#optimization-suggestion)

For long-running frameworks, it’s often better to enqueue exceptions and handle reporting via a background worker:

```
try {
    // Code that may throw
} catch (\Throwable $exception) {
    /**
     * Format exception data before sending
     *
     * @param Throwable $exception The captured exception
     * @param string $project Project name
     * @param array $context Additional context info (default: empty)
     *
     * @return array
     */
    $formatted = Logger::formatThrowable($exception, 'my-project');
    // Push $formatted into a queue
    // Then let your worker consume and send it
}
```

---

Motivation
----------

[](#motivation)

- To provide a **lightweight, unified logging solution** for quickly sending PHP exception data to my Go project **[oh-shit-logger](https://github.com/zxc7563598/oh-shit-logger)**
- To avoid writing repetitive error reporting logic across multiple projects
- Supports **safe local logging + async/sync remote reporting**, suitable for PHP-FPM, CLI, and long-running frameworks

---

Additional Notes
----------------

[](#additional-notes)

- Asynchronous reporting works by forking a PHP CLI subprocess
- For low-frequency errors, overhead is minimal and generally safe
- Under high concurrency (thousands per second), consider using a queue + worker or coroutine async (Though realistically, error reporting shouldn’t reach that volume 😅)
- Local logging includes automatic rotation to prevent oversized files during long-term use

---

Issues &amp; Contributions
--------------------------

[](#issues--contributions)

Have ideas, feedback, or bug reports?
Feel free to open an Issue or Pull Request on GitHub! 🚀

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance63

Regular maintenance activity

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

226d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b65d4b40ae456172fb38f63f84bf737ac88031484b1f228b1cc8d71baa80adf?d=identicon)[苏青安](/maintainers/%E8%8B%8F%E9%9D%92%E5%AE%89)

---

Top Contributors

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

---

Tags

async-loggingerror-reportingexception-handlinglog-collectorloggingphpphp-libraryremote-logging

### Embed Badge

![Health badge](/badges/hejunjie-lazylog/health.svg)

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

###  Alternatives

[psr/log

Common interface for logging libraries

10.4k1.2B10.9k](/packages/psr-log)[open-telemetry/api

API for OpenTelemetry PHP.

1938.5M261](/packages/open-telemetry-api)[open-telemetry/sdk

SDK for OpenTelemetry PHP.

2326.5M315](/packages/open-telemetry-sdk)[illuminated/console-logger

Logging and Notifications for Laravel Console Commands.

8676.7k](/packages/illuminated-console-logger)

PHPackages © 2026

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