amjad-ah/larascope 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

amjad-ah/larascope

Composer 安装命令:

composer require amjad-ah/larascope

包简介

A Laravel package that logs HTTP requests, duration, status, SQL queries, and memory usage.

README 文档

README

A Laravel package that logs HTTP requests, duration, status, SQL queries, and memory usage — with a built-in web dashboard to browse and inspect them.

Features

  • Zero-config setup — auto-discovered and auto-registered into the web and api middleware groups
  • Request metadata — method, URL, path, named route, IP address, authenticated user ID, status code
  • Performance data — request duration (ms) and peak memory usage (MB)
  • SQL query logging — captures all queries with bindings and execution time; automatically flags slow queries
  • Sensitive header redaction — strips Authorization, Cookie, and X-CSRF-Token headers before persisting
  • Privacy-first — request and response bodies are off by default
  • Built-in dashboard — paginated, filterable log browser at /larascope
  • Log pruningphp artisan larascope:prune removes logs older than a configurable retention period
  • Database fallback — if a DB insert fails, the payload is written to the Laravel log so nothing is silently lost
  • Octane-safe — per-request state is reset on every handle() call to prevent bleed between requests

Requirements

Dependency Version
PHP ^8.1
Laravel ^10.0 | ^11.0 | ^12.0 | ^13.0

Installation

Install the package via Composer:

composer require amjad-ah/larascope

The package is auto-discovered — no manual provider registration needed.

Run the migration to create the larascope_request_logs table:

php artisan migrate

That's it. LaraScope is now logging every HTTP request in the web and api middleware groups.

Dashboard

Open /larascope in your browser to browse captured logs.

The list view supports filtering by HTTP method, status code, and path substring. The detail view shows the full SQL query log (with bindings and slow-query flags), request headers, memory peak, and duration.

Tailwind CSS is loaded via CDN — no asset pipeline required.

Protecting the dashboard in production

Add Laravel's auth middleware (or any middleware you prefer) to the dashboard:

// config/larascope.php
'dashboard' => [
    'middleware' => ['web', 'auth'],
],

Configuration

Publish the config file to customise any option:

php artisan vendor:publish --tag=larascope-config

Environment variables

Variable Default Description
LARASCOPE_ENABLED true Master switch — disables all logging and middleware registration when false
LARASCOPE_DB_CONNECTION null (Laravel default) Database connection to use for storing logs
LARASCOPE_DB_TABLE larascope_request_logs Table name for log storage
LARASCOPE_DASHBOARD_ENABLED true Enable or disable the web dashboard
LARASCOPE_DASHBOARD_PATH larascope URL path for the dashboard

Full config reference

// config/larascope.php

return [

    // Master switch — set to false to disable everything
    'enabled' => env('LARASCOPE_ENABLED', true),

    'database' => [
        'connection' => env('LARASCOPE_DB_CONNECTION', null),
        'table'      => env('LARASCOPE_DB_TABLE', 'larascope_request_logs'),
    ],

    // Middleware groups to auto-register the logging middleware into
    'middleware_groups' => ['web', 'api'],

    'dashboard' => [
        'enabled'    => env('LARASCOPE_DASHBOARD_ENABLED', true),
        'path'       => env('LARASCOPE_DASHBOARD_PATH', 'larascope'),
        'middleware' => ['web'],   // add 'auth' to restrict access
        'per_page'   => 25,
    ],

    'logging' => [
        'include_request_headers' => true,
        'include_request_body'    => false,  // off by default for privacy
        'include_response_body'   => false,  // off by default for privacy

        // Headers stripped before storing (case-insensitive)
        'exclude_headers' => [
            'authorization',
            'cookie',
            'x-csrf-token',
        ],

        // Paths to skip — supports Str::is() wildcards e.g. '_debugbar/*'
        'exclude_paths' => [],

        // HTTP methods to skip entirely e.g. ['OPTIONS']
        'exclude_methods' => [],
    ],

    'queries' => [
        'enabled'           => true,
        'slow_threshold_ms' => 100,  // queries >= this value are flagged as slow
    ],

    'pruning' => [
        'enabled'     => true,
        'retain_days' => 30,
    ],

];

Excluding paths and methods

Skip specific routes using wildcards (powered by Str::is()):

'exclude_paths' => [
    'health',
    '_debugbar/*',
    'telescope/*',
    'horizon/*',
],

'exclude_methods' => ['OPTIONS'],

The dashboard's own routes are always excluded automatically to prevent recursive log growth.

Captured data

Each log entry stores 15 fields:

Field Type Description
method string HTTP verb (GET, POST, …)
url string Full request URL including query string
path string URL path segment only
route_name string|null Named route, if resolved
ip_address string|null Client IP address
user_id int|null Authenticated user ID (Auth::id())
status_code int HTTP response status code
duration_ms float Request duration in milliseconds
memory_peak_mb float Peak memory usage in megabytes
query_count int Number of SQL queries executed
queries json Array of queries with sql, bindings, time_ms, and slow flag
request_headers json|null Sanitised request headers
request_body json|null Request input (opt-in)
response_body string|null Response content (opt-in)
created_at timestamp When the log entry was created

Artisan commands

Prune old logs

php artisan larascope:prune

Deletes all log entries older than pruning.retain_days (default: 30 days). Schedule this command to keep your table from growing unbounded:

// routes/console.php (Laravel 11+)
Schedule::command('larascope:prune')->daily();

Publishing assets

# Publish config
php artisan vendor:publish --tag=larascope-config

# Publish migration (to customise the table schema)
php artisan vendor:publish --tag=larascope-migrations

# Publish Blade views (to customise the dashboard UI)
php artisan vendor:publish --tag=larascope-views

Architecture

HTTP Request
  → LaraScopeMiddleware   (resets state, captures start time, registers DB::listen)
    → RequestLogger       (builds structured 15-field payload)
      → DatabaseDriver    (persists to DB; falls back to Laravel log on failure)
        → RequestLog      (Eloquent model consumed by the dashboard)
          → DashboardController / PruneLogsCommand

Both LaraScopeMiddleware and RequestLogger are bound as singletons so the same instance handles both handle() and terminate(). Per-request state ($collectedQueries, $shouldSkip) is reset at the top of every handle() call, making the package safe under persistent runtimes like Laravel Octane.

amjad-ah/larascope 适用场景与选型建议

amjad-ah/larascope 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5 次下载、GitHub Stars 达 6, 最近一次更新时间为 2026 年 04 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「logging」 「performance」 「sql」 「http」 「debugging」 「monitoring」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 amjad-ah/larascope 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 5
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 39
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-17