onamfc/laravel-devlogger 问题修复 & 功能扩展

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

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

onamfc/laravel-devlogger

Composer 安装命令:

composer require onamfc/laravel-devlogger

包简介

A custom logging package for Laravel with database storage and automatic error catching

README 文档

README

A comprehensive logging package for Laravel that stores logs in a database with automatic error catching, advanced filtering, and management capabilities.

Features

  • Database Logging: Store logs in database with rich metadata
  • Automatic Error Catching: Automatically capture and log all application exceptions
  • Tagging System: Organize logs with custom tags
  • Advanced Filtering: Filter logs by level, date, queue, status, and more
  • Automatic Cleanup: Configurable log retention with automatic cleanup
  • Queue Support: Associate logs with specific queues
  • Request Context: Capture HTTP request information automatically
  • User Tracking: Track which user triggered each log entry
  • Flexible Configuration: Extensive configuration options via environment variables

Installation

1. Install via Composer

composer require onamfc/laravel-devlogger

2. Publish Configuration and Migrations

# Publish configuration file
php artisan vendor:publish --tag=devlogger-config

# Publish migrations (optional - they auto-load by default)
php artisan vendor:publish --tag=devlogger-migrations

3. Run Migrations

php artisan migrate

4. Configure Environment Variables (Optional)

Add these to your .env file to customize behavior:

# Enable/disable database logging
DEVLOGGER_ENABLE_DB=true

# Default log level
DEVLOGGER_LOG_LEVEL=debug

# Database connection (null = default)
DEVLOGGER_DB_CONNECTION=null

# Table name
DEVLOGGER_TABLE_NAME=developer_logs

# Auto-catch exceptions
DEVLOGGER_AUTO_CATCH=true

# Log retention (days)
DEVLOGGER_RETENTION_DAYS=30

# Fallback Laravel log channels
DEVLOGGER_FALLBACK_CHANNELS=null

Basic Usage

Manual Logging

use DevLogger;

// Basic logging
DevLogger::info('User logged in', ['user_id' => 123]);
DevLogger::error('Payment failed', ['order_id' => 456, 'error' => 'Card declined']);
DevLogger::debug('Debug information', ['data' => $debugData]);

// With queue context
DevLogger::onQueue('email-queue')->info('Email sent', ['recipient' => 'user@example.com']);

// With tags
DevLogger::withTags(['payment', 'critical'])->error('Payment gateway timeout');

// Method chaining
DevLogger::onQueue('reports')
    ->withTags(['report', 'daily'])
    ->info('Daily report generated');

Exception Logging

try {
    // Some risky operation
    $result = $this->riskyOperation();
} catch (Exception $e) {
    DevLogger::logException($e, ['context' => 'additional info']);
    throw $e; // Re-throw if needed
}

Automatic Exception Catching - Laravel 9, 10, 11

The package automatically catches and logs all unhandled exceptions when DEVLOGGER_AUTO_CATCH=true (default). To set this up:

Option 1: Extend the DevLogger Exception Handler

In your app/Exceptions/Handler.php:

<?php

namespace App\Exceptions;

use DevLoggerPackage\Exceptions\DevLoggerExceptionHandler;

class Handler extends DevLoggerExceptionHandler
{
    // Your existing exception handling code
}

Option 2: Manual Integration

If you prefer to keep your existing handler, add this to your report method:

use DevLoggerPackage\Facades\DevLogger;

public function report(Throwable $exception)
{
    if ($this->shouldReport($exception) && config('devlogger.auto_catch_exceptions', true)) {
        DevLogger::logException($exception, [
            'url' => request()->fullUrl(),
            'method' => request()->method(),
            'input' => request()->except(['password', 'password_confirmation', '_token']),
        ]);
    }

    parent::report($exception);
}

Automatic Exception Catching - Laravel 12

Integration

The bootstrap directory contains the app.php file which bootstraps the framework: bootstrap/app.php. Within the withException method, you can integrate the DevLogger package to automatically catch exceptions:

->withExceptions(function (Exceptions $exceptions) {
   
    $exceptions->report(function (Throwable $e){
        if (config('devlogger.auto_catch_exceptions', true)) {
            \DevLoggerPackage\Facades\DevLogger::logException($e, [
                'url' => request()?->fullUrl(),
                'method' => request()?->method(),
                'input' => request()?->except(['password', 'password_confirmation', '_token']),
            ]);
        }
        return true;
    });
    
})->create();

Advanced Usage

Working with Log Models

use DevLoggerPackage\Models\DeveloperLog;

// Query logs
$errorLogs = DeveloperLog::level('error')->open()->get();
$recentLogs = DeveloperLog::dateRange(now()->subDays(7), now())->get();
$queueLogs = DeveloperLog::queue('email-queue')->get();

// Manage log status
$log = DeveloperLog::find(1);
$log->markAsClosed(auth()->id());
$log->markAsOpen();

// Work with tags
$log->addTags(['reviewed', 'fixed']);
$log->removeTags(['critical']);

Log Cleanup

The package includes automatic cleanup based on your retention policy:

# Manual cleanup
php artisan devlogger:cleanup

# Cleanup with custom retention
php artisan devlogger:cleanup --days=7

# Dry run to see what would be deleted
php artisan devlogger:cleanup --dry-run

Automatic cleanup runs daily when DEVLOGGER_RETENTION_DAYS is configured.

Database Schema

The developer_logs table includes these fields:

Field Type Description
id bigint Primary key
level string Log level (debug, info, error, etc.)
log longtext The log message
context json Additional context data
file_path string File where log originated
line_number integer Line number where log originated
exception_class string Exception class name (for exceptions)
stack_trace longtext Full stack trace (for exceptions)
queue string Associated queue name
request_url string HTTP request URL
request_method string HTTP request method
user_id bigint ID of authenticated user
ip_address string Client IP address
user_agent text Client user agent
status string Log status (open/closed)
tags json Array of tags
updated_by bigint User who last updated the log
created_at timestamp When log was created
updated_at timestamp When log was last updated
deleted_at timestamp Soft delete timestamp

Configuration Options

The config/devlogger.php file provides extensive configuration:

return [
    // Default log level
    'log_level' => env('DEVLOGGER_LOG_LEVEL', 'debug'),
    
    // Database connection
    'database_connection' => env('DEVLOGGER_DB_CONNECTION', null),
    
    // Table name
    'table_name' => env('DEVLOGGER_TABLE_NAME', 'developer_logs'),
    
    // Enable database logging
    'enable_database_logging' => env('DEVLOGGER_ENABLE_DB', true),
    
    // Auto-catch exceptions
    'auto_catch_exceptions' => env('DEVLOGGER_AUTO_CATCH', true),
    
    // Fallback Laravel channels
    'fallback_channels' => env('DEVLOGGER_FALLBACK_CHANNELS', null),
    
    // Log retention in days
    'retention_days' => env('DEVLOGGER_RETENTION_DAYS', 30),
    
    // Paths to exclude from auto-logging
    'excluded_paths' => [
        'vendor/',
        'storage/framework/',
    ],
];

Performance Considerations

  • The package uses database indexes for optimal query performance
  • Automatic cleanup prevents database bloat
  • Failed database writes fall back to Laravel's default logging
  • Excluded paths prevent logging of framework internals

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is open-sourced software licensed under the MIT license.

Support

If you encounter any issues or have questions, please open an issue on the GitHub repository.

onamfc/laravel-devlogger 适用场景与选型建议

onamfc/laravel-devlogger 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30 次下载、GitHub Stars 达 16, 最近一次更新时间为 2025 年 07 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 onamfc/laravel-devlogger 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-07-08