PHP code example of fulgid / log-management
1. Go to this page and download the library: Download fulgid/log-management library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
fulgid / log-management example snippets
// Trigger a test alert
Log::error('Houston, we have a problem!', ['user_id' => 123]);
// Or use the facade for custom alerts
LogManagement::alert('Payment gateway is down!', [
'severity' => 'critical',
'service' => 'payments'
]);
// Custom email template
LogManagement::emailTemplate('critical-alert', function ($log) {
return [
'subject' => "🚨 Critical Error: {$log['message']}",
'template' => 'emails.critical-alert',
'data' => [
'log' => $log,
'dashboard_url' => route('log-management.dashboard'),
'action_
use Fulgid\LogManagement\Notifications\Contracts\NotificationChannelInterface;
class DiscordChannel implements NotificationChannelInterface
{
public function send(array $logData): bool
{
$webhook = config('services.discord.webhook_url');
$payload = [
'content' => "🚨 **{$logData['level']}**: {$logData['message']}",
'embeds' => [
[
'color' => $this->getColorForLevel($logData['level']),
'timestamp' => $logData['timestamp'],
'fields' => $this->formatFields($logData)
]
]
];
return Http::post($webhook, $payload)->successful();
}
private function getColorForLevel($level): int
{
return match($level) {
'emergency', 'alert', 'critical' => 0xFF0000, // Red
'error' => 0xFF4500, // Orange Red
'warning' => 0xFFA500, // Orange
'notice' => 0x0000FF, // Blue
'info' => 0x00FF00, // Green
'debug' => 0x808080, // Gray
default => 0x000000 // Black
};
}
private function formatFields(array $logData): array
{
$fields = [
['name' => 'Level', 'value' => ucfirst($logData['level']), 'inline' => true],
['name' => 'Environment', 'value' => $logData['environment'] ?? 'Unknown', 'inline' => true]
];
if (!empty($logData['context']['user_id'])) {
$fields[] = ['name' => 'User ID', 'value' => $logData['context']['user_id'], 'inline' => true];
}
return $fields;
}
}
// Register in AppServiceProvider
LogManagement::addChannel('discord', new DiscordChannel());
// In migration
Schema::table('log_management_logs', function (Blueprint $table) {
$table->index(['level', 'created_at']);
$table->index(['user_id', 'created_at']);
$table->index('channel');
});
// Example test case
class LogManagementTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function it_can_store_log_entries()
{
// Arrange
$logData = [
'level' => 'error',
'message' => 'Test error message',
'context' => ['user_id' => 123]
];
// Act
LogManagement::log($logData);
// Assert
$this->assertDatabaseHas('log_management_logs', [
'level' => 'error',
'message' => 'Test error message'
]);
}
/** @test */
public function it_sends_notifications_for_critical_errors()
{
// Arrange
Notification::fake();
// Act
LogManagement::log([
'level' => 'critical',
'message' => 'Critical system error'
]);
// Assert
Notification::assertSent(CriticalErrorNotification::class);
}
}
// Use log contexts for better filtering
Log::error('Payment failed', [
'user_id' => $user->id,
'payment_id' => $payment->id,
'gateway' => 'stripe',
'amount' => $payment->amount
]);
// Batch log operations for better performance
LogManagement::batch([
['level' => 'info', 'message' => 'Batch operation 1'],
['level' => 'info', 'message' => 'Batch operation 2'],
['level' => 'info', 'message' => 'Batch operation 3'],
]);
// Use conditional logging to reduce noise
if (app()->environment('production')) {
Log::channel('log-management')->info('Production-only log');
}
// Custom log processor
LogManagement::addProcessor(function ($record) {
$record['extra']['server_id'] = gethostname();
$record['extra']['memory_usage'] = memory_get_usage(true);
return $record;
});
// Custom alert rules
LogManagement::addAlertRule('high_error_rate', function ($stats) {
return $stats['error_rate'] > 5.0; // Alert if error rate > 5%
});
// Dynamic notification routing
LogManagement::addNotificationRouter(function ($logData) {
if ($logData['level'] === 'critical') {
return ['slack', 'email', 'webhook'];
} elseif ($logData['level'] === 'error') {
return ['slack'];
}
return [];
});
bash
php artisan log-management:install
json
{
"data": [
{
"id": 1,
"level": "error",
"message": "Database connection failed",
"channel": "database",
"context": {
"user_id": 123,
"connection": "mysql",
"query_time": 5.2
},
"extra": {
"file": "/app/Database/Connection.php",
"line": 157
},
"formatted": "[2024-01-15 10:30:15] production.ERROR: Database connection failed",
"timestamp": "2024-01-15T10:30:15.000000Z",
"created_at": "2024-01-15T10:30:15.000000Z"
}
],
"meta": {
"current_page": 1,
"last_page": 10,
"per_page": 20,
"total": 195,
"from": 1,
"to": 20
},
"links": {
"first": "/api/logs?page=1",
"last": "/api/logs?page=10",
"prev": null,
"next": "/api/logs?page=2"
}
}
json
{
"summary": {
"total_logs": 12450,
"total_today": 234,
"total_errors": 45,
"error_rate": 3.6,
"avg_response_time": 245.7
},
"level_breakdown": {
"emergency": 0,
"alert": 2,
"critical": 5,
"error": 38,
"warning": 156,
"notice": 234,
"info": 1890,
"debug": 10125
},
"hourly_stats": [
{
"hour": "2024-01-15T10:00:00Z",
"count": 45,
"errors": 3,
"avg_response_time": 234.5
}
],
"top_errors": [
{
"message": "Database connection timeout",
"count": 23,
"last_seen": "2024-01-15T10:25:00Z"
}
]
}
bash
# Generate log statistics report
php artisan log-management:stats --period=7d --format=table
# Export logs to various formats
php artisan log-management:export --format=csv --from=2024-01-01 --to=2024-01-31
php artisan log-management:export --format=json --level=error
php artisan log-management:export --format=excel --user-id=123
# Generate trending analysis
php artisan log-management:trends --period=30d --group-by=level
# Performance analysis
php artisan log-management:performance --analyze-slow-queries
bash
# Optimize Composer autoloader
composer install --no-dev --optimize-autoloader --classmap-authoritative
# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache
# Optimize for production
php artisan optimize
# Set up log rotation
echo "*/5 * * * * php /var/www/html/artisan log-management:cleanup --days=30" | crontab -
# Configure Redis for sessions and cache
# In .env:
SESSION_DRIVER=redis
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
bash
# Solution: Check and rollback if necessary
php artisan migrate:status
php artisan migrate:rollback --step=1
php artisan log-management:install --skip-migrations
bash
# Solution: Implement aggressive cleanup and archiving
php artisan log-management:cleanup --days=7 --level=debug
php artisan log-management:cleanup --days=30 --exclude-levels=error,critical
# Set up automated cleanup
*/0 2 * * * php /var/www/html/artisan log-management:cleanup --days=30 --quiet
bash
# Format code with PHP CS Fixer
vendor/bin/php-cs-fixer fix
# Run static analysis with PHPStan
vendor/bin/phpstan analyse
# Check code quality with PHPMD
vendor/bin/phpmd src text cleancode,codesize,controversial,design,naming,unusedcode