frddl / laravel-simple-logging
A simple, elegant logging package for Laravel with automatic method wrapping and beautiful web interface
Installs: 26
Dependents: 0
Suggesters: 0
Security: 0
Stars: 8
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/frddl/laravel-simple-logging
Requires
- php: ^8.0
- illuminate/database: ^9.0|^10.0|^11.0|^12.0
- illuminate/http: ^9.0|^10.0|^11.0|^12.0
- illuminate/routing: ^9.0|^10.0|^11.0|^12.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
- illuminate/view: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.0|^10.0
README
An elegant solution for monitoring your Laravel application's actual flow with comprehensive logging of warnings, infos, debug variables, and performance metrics. Features automatic method wrapping and a beautiful web interface for real-time application monitoring.
Features
- ๐ฏ Real-Time Application Flow Monitoring - Track your app's actual execution flow with comprehensive logging
- โ ๏ธ Smart Warning & Info Logging - Automatically capture warnings, infos, and debug variables throughout your application
- ๐ Advanced Debug Variable Tracking - Monitor complex data structures, arrays, objects, and variables in real-time
- โ Automatic Method Wrapping - Wrap any method with start/end logging for complete flow visibility
- ๐จ Beautiful Web Interface - Modern, responsive log viewer with advanced filtering and search
- ๐ Request Tracing - Group all logs by request ID for easy debugging and flow analysis
- ๐ Performance Monitoring - Automatic duration and memory usage tracking for optimization
- ๐จ Intelligent Error Handling - Automatic exception logging with detailed stack traces
- ๐ Sensitive Data Sanitization - Automatically masks passwords, tokens, and sensitive information
- ๐พ Flexible Storage - Store logs in database and/or files with configurable retention
- ๐ Zero Dependencies - Works with any data structure and Laravel version
- ๐ฑ Mobile Responsive - Beautiful interface on all devices for monitoring on-the-go
๐ฏ Perfect for Application Flow Monitoring
This package is specifically designed for monitoring your Laravel application's actual execution flow. It excels at:
- ๐ Debug Variable Tracking - Monitor complex data structures, arrays, objects, and variables as they flow through your application
- โ ๏ธ Warning & Info Capture - Automatically log warnings, infos, and debug messages with full context
- ๐ Real-Time Flow Analysis - See exactly how your application processes requests, with timing and memory usage
- ๐จ Exception Tracking - Capture and analyze errors with complete stack traces and variable states
- ๐ Request Tracing - Follow a single request through your entire application stack
- ๐ Performance Insights - Identify bottlenecks and optimize your application based on real usage data
Perfect for debugging complex business logic, monitoring API responses, tracking user interactions, and understanding your application's behavior in production.
Installation
composer require frddl/laravel-simple-logging
Publish the config file and migrations:
php artisan vendor:publish --provider="Frddl\LaravelSimpleLogging\SimpleLoggingServiceProvider" --tag="config" php artisan vendor:publish --provider="Frddl\LaravelSimpleLogging\SimpleLoggingServiceProvider" --tag="migrations"
Run the migrations:
php artisan migrate
Quick Start
1. Add the trait to your controller:
use Frddl\LaravelSimpleLogging\Traits\SimpleLoggingTrait; class YourController extends Controller { use SimpleLoggingTrait; // Your methods here }
2. Wrap your methods with automatic logging:
public function yourMethod(Request $request) { return $this->logMethod('Your Method Name', $request->all(), function() use ($request) { // Your business logic here - automatic start/end logging! return response()->json(['message' => 'Success']); }); }
3. Add comprehensive monitoring with debug variables:
public function processOrder(Request $request) { return $this->logMethod('Process Order', $request->all(), function() use ($request) { // Monitor input data and validation $this->log('Order validation started', [ 'order_data' => $request->all(), 'user_id' => $request->user_id, 'items_count' => count($request->items ?? []) ], 'info'); // Track business logic execution $order = Order::create($request->validated()); $this->log('Order created successfully', [ 'order_id' => $order->id, 'total_amount' => $order->total, 'payment_method' => $order->payment_method ], 'info'); // Monitor external API calls $payment = $this->processPayment($order); $this->log('Payment processed', [ 'payment_id' => $payment->id, 'status' => $payment->status, 'amount' => $payment->amount ], 'info'); // Track warnings and potential issues if ($payment->amount !== $order->total) { $this->log('Payment amount mismatch detected', [ 'order_total' => $order->total, 'payment_amount' => $payment->amount, 'difference' => $payment->amount - $order->total ], 'warning'); } return response()->json(['order' => $order]); }); }
Configuration
Edit config/simple-logging.php:
return [ 'enabled' => env('SIMPLE_LOGGING_ENABLED', true), 'file_logging' => env('SIMPLE_LOGGING_FILE_LOGGING', false), 'database_logging' => env('SIMPLE_LOGGING_DATABASE_LOGGING', true), 'log_level' => env('SIMPLE_LOGGING_LEVEL', 'info'), 'route_prefix' => 'logs', 'middleware' => ['web'], 'viewer' => [ 'per_page' => 50, ], 'export' => [ 'max_records' => 100, ], 'cleanup_old_logs_days' => env('SIMPLE_LOGGING_CLEANUP_DAYS', 30), ];
Log Cleanup & Maintenance
The package includes automatic log cleanup to prevent database bloat:
Automatic Cleanup
- Scheduled Daily - Runs automatically at 2:00 AM daily
- Configurable Retention - Keep logs for specified days (default: 30 days)
- Background Processing - Runs without blocking your application
Manual Cleanup
# Clean up logs older than 30 days (uses config default) php artisan simple-logging:cleanup # Clean up logs older than 7 days php artisan simple-logging:cleanup --days=7 # Clean up logs older than 90 days php artisan simple-logging:cleanup --days=90
Configuration
// In config/simple-logging.php 'cleanup_old_logs_days' => env('SIMPLE_LOGGING_CLEANUP_DAYS', 30), // In your .env file SIMPLE_LOGGING_CLEANUP_DAYS=30
Disable Cleanup
Set the cleanup days to null or 0 to disable automatic cleanup:
'cleanup_old_logs_days' => null, // Disable cleanup
Usage
Automatic Method Logging
The logMethod function automatically logs:
- Method start with input data
- Method completion with duration and memory usage
- Any exceptions with stack traces
public function processOrder(Request $request) { return $this->logMethod('Process Order', $request->all(), function() use ($request) { $order = Order::create($request->validated()); $this->log('Order created', ['order_id' => $order->id], 'info'); // Process payment $payment = $this->processPayment($order); $this->log('Payment processed', ['payment_id' => $payment->id], 'info'); return response()->json(['order' => $order]); }); }
Direct Logging for Application Flow Monitoring
Monitor your application's execution flow with detailed logging:
// Monitor user actions and debug variables $this->log('User authentication started', [ 'email' => $request->email, 'ip_address' => $request->ip(), 'user_agent' => $request->userAgent(), 'session_id' => session()->getId() ], 'info'); // Track business logic with complex data structures $this->log('Order processing initiated', [ 'order_id' => $order->id, 'customer_data' => $order->customer->toArray(), 'items' => $order->items->map(function($item) { return [ 'name' => $item->name, 'price' => $item->price, 'quantity' => $item->quantity ]; }), 'total_calculation' => [ 'subtotal' => $order->subtotal, 'tax' => $order->tax, 'shipping' => $order->shipping, 'total' => $order->total ] ], 'info'); // Monitor warnings and potential issues $this->log('Low inventory warning', [ 'product_id' => $product->id, 'current_stock' => $product->stock, 'requested_quantity' => $quantity, 'threshold' => $product->low_stock_threshold ], 'warning'); // Track errors with full context $this->log('Payment processing failed', [ 'error' => $exception->getMessage(), 'order_id' => $order->id, 'payment_data' => $paymentData, 'retry_count' => $retryCount, 'stack_trace' => $exception->getTraceAsString() ], 'error');
Log Levels
emergency- System is unusablealert- Action must be taken immediatelycritical- Critical conditionserror- Error conditionswarning- Warning conditionsnotice- Normal but significant conditionsinfo- Informational messages (default)debug- Debug-level messages
Web Interface
Access the log viewer at: http://your-app.com/logs
Features:
- Request Tracing - See all logs grouped by request
- Advanced Filtering - Filter by level, date, search terms
- Real-time Viewing - Beautiful, responsive interface
- Performance Metrics - Duration and memory usage tracking
- Mobile Friendly - Works perfectly on all devices
Disable Logging
Environment Variable (Recommended):
SIMPLE_LOGGING_ENABLED=false
Or in code:
config(['simple-logging.enabled' => false]);
API Endpoints
GET /logs- Web interfaceGET /logs/api- JSON API for logsGET /logs/api/statistics- Log statisticsGET /logs/api/property-keys- Available property keys
Sensitive Data Sanitization
The package automatically sanitizes sensitive data:
// This will be automatically masked $this->log('User data', [ 'password' => 'secret123', // โ [HIDDEN] 'token' => 'abc123xyz', // โ [HIDDEN] 'authorization' => 'Bearer token123' // โ Bearer [HIDDEN] ]);
Performance
- Minimal Overhead - Only logs when enabled
- Efficient Storage - Optimized database queries
- Memory Conscious - Tracks memory usage
- Configurable Cleanup - Automatic old log removal
Examples
Complete Controller Example
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests\CreateOrderRequest; use Frddl\LaravelSimpleLogging\Traits\SimpleLoggingTrait; class OrderController extends Controller { use SimpleLoggingTrait; public function store(CreateOrderRequest $request) { return $this->logMethod('Create Order', $request->all(), function() use ($request) { $this->log('Validating order data', ['items_count' => count($request->items)]); $order = Order::create($request->validated()); $this->log('Order created successfully', ['order_id' => $order->id]); // Process payment $payment = $this->processPayment($order); if (!$payment->success) { $this->log('Payment failed', ['error' => $payment->error], 'error'); throw new PaymentException('Payment processing failed'); } $this->log('Payment successful', ['payment_id' => $payment->id]); return response()->json(['order' => $order], 201); }); } private function processPayment($order) { return $this->logMethod('Process Payment', ['order_id' => $order->id], function() use ($order) { // Payment logic here return (object) ['success' => true, 'id' => 'pay_123']; }); } }
๐งช Comprehensive Testing
The package includes built-in comprehensive testing functionality to validate all logging features:
Quick Test
# Run basic logging tests
php artisan simple-logging:test --quick
Comprehensive Test
# Run extensive tests covering all features
php artisan simple-logging:test --comprehensive
The comprehensive test covers:
- All Log Levels: info, warning, error, debug, success, critical, alert, emergency
- Complex Data Structures: Nested objects, arrays, mixed data types
- Data Type Permutations: All possible combinations of strings, numbers, booleans, arrays, objects, nulls
- Real-World Scenarios: E-commerce, monitoring, security, API responses
- Edge Cases: Special characters, unicode, boundary values, empty data
- Nested Function Calls: Call depth tracking and stack management
- Performance Metrics: Memory usage, execution time, database queries
Clean Test Logs
# Run comprehensive test and clean up afterward
php artisan simple-logging:test --comprehensive --clean
Test Features Demonstrated
The comprehensive test generates 26+ log entries covering:
Log Levels & Categories
- Information, Warning, Error, Debug, Success, Critical, Alert, Emergency
- Authentication, Database, API, Security, Performance, Data Test
Complex Data Structures
- User profiles with nested personal info, preferences, and activity
- System metrics with performance, database, and cache data
- Business logic with orders, inventory, and revenue tracking
- API responses with external and internal service monitoring
- Error tracking with recent errors and error rates
- Security events with failed logins and suspicious activity
Data Type Permutations
- Mixed arrays with strings, integers, floats, booleans, nulls
- Nested objects up to 4 levels deep
- Complex combinations of arrays and objects
- Edge cases with special characters, unicode, and boundary values
Real-World Examples
- E-commerce order processing with payment and inventory
- System monitoring with performance metrics and health checks
- Security monitoring with failed logins and threat detection
- API integration with external services and response tracking
View Test Results
After running tests, view the results in the web interface:
# Access the log viewer
http://your-app.com/logs
The test logs will be grouped by request ID, showing the complete flow of the comprehensive test with all data structures, log levels, and nested function calls.
Unit Testing
composer test
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
The MIT License (MIT). Please see License File for more information.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
Support
If you discover any issues, please open an issue on GitHub.