定制 hejunjie/error-log 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

hejunjie/error-log

Composer 安装命令:

composer require hejunjie/error-log

包简介

基于责任链模式的错误日志处理组件,支持多通道日志处理(如本地文件、远程 API、控制台输出),适用于复杂日志策略场景 | An error logging component using the Chain of Responsibility pattern. Supports multiple output channels like local files, remote APIs, and console logs—ideal for flexible and scalable logging strategies.

README 文档

README

English简体中文

An error logging component using the Chain of Responsibility pattern. Supports multiple output channels like local files, remote APIs, and console logs—ideal for flexible and scalable logging strategies.

This project has been parsed by Zread. If you need a quick overview of the project, you can click here to view it:Understand this project

Installation

Install via Composer:

composer require hejunjie/error-log

Usage

<?php

use Hejunjie\ErrorLog\Logger;
use Hejunjie\ErrorLog\Handlers;

$log = new Logger([
    new Handlers\ConsoleHandler(),                // Print to console
    new Handlers\FileHandler('path'),  // Save to file
    new Handlers\RemoteApiHandler('url')       // Send to a specific address
]);

$log->info('title','content',['Context']);     // INFO Level
$log->warning('title','content',['Context']);  // WARNING Level
$log->error('title','content',['Context']);    // ERROR Level

$log->log('level','title','content',['Context']);

Purpose & Original Intent

The origin of this component is actually quite simple: The code runs on different servers, some are as quiet as retired old men, while others explode into fireworks at the slightest provocation — but they're all running "the same code," and every time something breaks, they come looking for me.

The most absurd part is that everyone claims they’re running the "latest version," but whether it's a code issue, an environment issue, or a deployment issue, who knows? So, I wrote this little tool: to flexibly output logs to files, consoles, and remote servers, with customizable formats. This way, I can find the problem before I'm questioned.

Later, I also wrote a small log receiving script. Combined with this component, it can directly display remote logs, allowing me to receive, display, filter, and manage log error information.

👉 oh-shit-logger

Corresponding complete custom error handling (from webman)

<?php

namespace app\exception;

use Carbon\Carbon;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;
use support\exception\BusinessException;
use Hejunjie\ErrorLog\Logger;
use Hejunjie\ErrorLog\Handlers;

/**
 * Class Handler
 * @package support\exception
 */
class Handler extends ExceptionHandler
{
    public $dontReport = [
        BusinessException::class,
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
        if ($this->shouldntReport($exception)) {
            return;
        }
        $request = request();
        $date = Carbon::now()->timezone(config('app')['default_timezone'])->format('Y-m-d');
        (new Logger([
            new Handlers\FileHandler(runtime_path("logs/{$date}/critical")),
            new Handlers\RemoteApiHandler(config('app')['log_report_url'])
        ]))->error(get_class($exception), $exception->getMessage(), [
            'project' => config('app')['app_name'],
            'ip' => $request->getRealIp(),
            'method' => $request->method(),
            'full_url' => $request->fullUrl(),
            'trace' => $this->getDebugData($exception)
        ]);
    }

    public function render(Request $request, Throwable $exception): Response
    {
        $isDebug = config('app')['debug'] == 1;
        $statusCode = $this->getHttpStatusCode($exception);
        $response = [
            'code' => $this->getErrorCode($exception),
            'message' => $isDebug ? $exception->getMessage() : 'Server Error',
            'data' => $isDebug ? $this->getDebugData($exception) : new \stdClass()
        ];
        if ($requestId = $request->header('X-Request-ID')) {
            $response['request_id'] = $requestId;
        }
        return new Response(
            $statusCode,
            ['Content-Type' => 'application/json'],
            json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        );
    }

    protected function getHttpStatusCode(Throwable $exception): int
    {
        $code = $exception->getCode();
        return ($code >= 100 && $code < 600) ? $code : 500;
    }

    protected function getErrorCode(Throwable $exception): int
    {
        return $exception->getCode() ?: 500;
    }

    protected function getDebugData(Throwable $exception): array
    {
        $trace = $exception->getTrace();
        $simplifiedTrace = array_map(function ($frame) {
            return [
                'file' => $frame['file'] ?? '[internal function]',
                'line' => $frame['line'] ?? 0,
                'function' => $frame['function'] ?? null,
                'class' => $frame['class'] ?? null,
                'type' => $frame['type'] ?? null
            ];
        }, $trace);
        return [
            'class' => get_class($exception),
            'message' => $exception->getMessage(),
            'code' => $exception->getCode(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => config('app')['debug'] == 1 ? $simplifiedTrace : array_slice($simplifiedTrace, 0, 5),
            'previous' => $exception->getPrevious() ? [
                'class' => get_class($exception->getPrevious()),
                'message' => $exception->getPrevious()->getMessage()
            ] : null
        ];
    }
}

🔧 Additional Toolkits (Can be used independently or installed together)

This project was originally extracted from hejunjie/tools. To install all features in one go, feel free to use the all-in-one package:

composer require hejunjie/tools

Alternatively, feel free to install only the modules you need:

hejunjie/utils - A lightweight and practical PHP utility library that offers a collection of commonly used helper functions for files, strings, arrays, and HTTP requests—designed to streamline development and support everyday PHP projects.

hejunjie/cache - A layered caching system built with the decorator pattern. Supports combining memory, file, local, and remote caches to improve hit rates and simplify cache logic.

hejunjie/china-division - Regularly updated dataset of China's administrative divisions with ID-card address parsing. Distributed via Composer and versioned for use in forms, validation, and address-related features

hejunjie/error-log - An error logging component using the Chain of Responsibility pattern. Supports multiple output channels like local files, remote APIs, and console logs—ideal for flexible and scalable logging strategies.

hejunjie/mobile-locator - A mobile number lookup library based on Chinese carrier rules. Identifies carriers and regions, suitable for registration checks, user profiling, and data archiving.

hejunjie/address-parser - An intelligent address parser that extracts name, phone number, ID number, region, and detailed address from unstructured text—perfect for e-commerce, logistics, and CRM systems.

hejunjie/url-signer - A PHP library for generating URLs with encryption and signature protection—useful for secure resource access and tamper-proof links.

hejunjie/google-authenticator - A PHP library for generating and verifying Time-Based One-Time Passwords (TOTP). Compatible with Google Authenticator and similar apps, with features like secret generation, QR code creation, and OTP verification.

hejunjie/simple-rule-engine - A lightweight and flexible PHP rule engine supporting complex conditions and dynamic rule execution—ideal for business logic evaluation and data validation.

👀 All packages follow the principles of being lightweight and practical — designed to save you time and effort. They can be used individually or combined flexibly. Feel free to ⭐ star the project or open an issue anytime!

This library will continue to be updated with more practical features. Suggestions and feedback are always welcome — I’ll prioritize new functionality based on community input to help improve development efficiency together.

hejunjie/error-log 适用场景与选型建议

hejunjie/error-log 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 816 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 04 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 hejunjie/error-log 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 hejunjie/error-log 我们能提供哪些服务?
定制开发 / 二次开发

基于 hejunjie/error-log 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 816
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 28
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-12