tylercd100/monolog-mailgun
Mailgun handler for Monolog in PHP/Laravel apps. Send log records by email through Mailgun with simple configuration, useful for alerts and production error notifications. Lightweight package that plugs into existing Monolog logging stacks.
Installation
composer require tylercd100/monolog-mailgun
Basic Configuration
Add the handler to your config/logging.php under the channels array:
'mailgun' => [
'driver' => 'mailgun',
'api_key' => env('MAILGUN_API_KEY'),
'domain' => env('MAILGUN_DOMAIN'),
'from_email' => env('MAILGUN_FROM_EMAIL'),
'to_email' => env('MAILGUN_TO_EMAIL'),
'priority' => env('MAILGUN_PRIORITY', 'high'),
'subject' => env('MAILGUN_SUBJECT', 'Application Error'),
'level' => env('MAILGUN_LOG_LEVEL', \Monolog\Logger::ERROR),
],
First Use Case Log an error in a controller or service:
use Illuminate\Support\Facades\Log;
try {
// Risky operation
} catch (\Exception $e) {
Log::channel('mailgun')->error('Failed to process payment', [
'exception' => $e,
'user_id' => auth()->id(),
]);
}
config/logging.php (Mailgun channel config)app/Exceptions/Handler.php (Global exception logging).env (Mailgun credentials)Error Logging
// Log with context
Log::channel('mailgun')->error('Database connection failed', [
'query' => $query,
'backtrace' => $e->getTraceAsString(),
]);
Debugging in Production
// Temporarily log debug messages
Log::channel('mailgun')->debug('User session data', [
'user_id' => auth()->id(),
'session' => session()->all(),
]);
Structured Logging
// Use Monolog's structured logging
Log::channel('mailgun')->info('Order processed', [
'order_id' => $order->id,
'amount' => $order->amount,
'metadata' => $order->metadata,
]);
Laravel's Exception Handler
Extend Handler.php to automatically log exceptions to Mailgun:
public function report(Throwable $exception)
{
Log::channel('mailgun')->error('Uncaught exception', [
'exception' => $exception,
'url' => url()->current(),
]);
parent::report($exception);
}
Queue Failed Jobs Log failed queue jobs:
// In app/Exceptions/Handler.php
protected function logFailedJob(FailedJob $exception)
{
Log::channel('mailgun')->error('Job failed', [
'job' => $exception->job,
'exception' => $exception->exception,
]);
}
Custom Log Levels
Use Log::channel('mailgun')->alert() or Log::channel('mailgun')->emergency() for critical issues.
Dynamic Recipients
// Override recipient per log entry
Log::channel('mailgun')->withContext(['to_email' => 'admin@example.com'])
->error('Critical failure detected');
API Key Exposure
.env or hardcode MAILGUN_API_KEY. Use Laravel's .env securely.config/logging.php:
'api_key' => env('MAILGUN_API_KEY') ?: throw new \RuntimeException('Mailgun API key not set.'),
Rate Limiting
WARNING instead of DEBUG).HTML/Email Formatting
Log::channel('mailgun')->withContext(['format' => 'text']) for plain-text logs.Missing Dependencies
guzzlehttp/guzzle (installed automatically via Composer).guzzlehttp/guzzle is in composer.json if manually installing.Subject Overrides
subject config is global. Dynamic subjects require customization.$handler = new \Tylercd100\Monolog\MailgunHandler(
$apiKey,
$domain,
function ($record) {
return "Custom Subject: {$record['context']['user_id']}";
}
);
Test Locally
Use a Mailgun sandbox domain (*.mailgun.org) to test without real emails.
Check Mailgun Webhooks Monitor the Mailgun dashboard for delivery failures or bounces.
Log Level Debugging
Temporarily set MAILGUN_LOG_LEVEL=DEBUG to see all logs (not recommended for production).
Handler Configuration
The handler uses Monolog\Logger::ERROR by default. Adjust via:
'level' => \Monolog\Logger::DEBUG, // Log everything
Custom Handlers
Extend \Tylercd100\Monolog\MailgunHandler to add:
Middleware
Add a LogMiddleware to log HTTP requests/responses:
Log::channel('mailgun')->info('Incoming request', [
'method' => $request->method(),
'path' => $request->path(),
'input' => $request->all(),
]);
Queue Logs Offload logging to a queue to avoid blocking:
Log::channel('mailgun')->pushHandler(
new \Monolog\Handler\BufferHandler(
new \Tylercd100\Monolog\MailgunHandler(...),
50 // Flush every 50 logs
)
);
Slack/Teams Integration Forward Mailgun emails to Slack/Teams using Mailgun's routing features.
How can I help you explore Laravel packages today?