Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Monolog Mailgun Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tylercd100/monolog-mailgun
    
  2. 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),
    ],
    
  3. 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(),
        ]);
    }
    

Key Files to Review

  • config/logging.php (Mailgun channel config)
  • app/Exceptions/Handler.php (Global exception logging)
  • .env (Mailgun credentials)

Implementation Patterns

Common Workflows

  1. Error Logging

    // Log with context
    Log::channel('mailgun')->error('Database connection failed', [
        'query' => $query,
        'backtrace' => $e->getTraceAsString(),
    ]);
    
  2. Debugging in Production

    // Temporarily log debug messages
    Log::channel('mailgun')->debug('User session data', [
        'user_id' => auth()->id(),
        'session' => session()->all(),
    ]);
    
  3. Structured Logging

    // Use Monolog's structured logging
    Log::channel('mailgun')->info('Order processed', [
        'order_id' => $order->id,
        'amount' => $order->amount,
        'metadata' => $order->metadata,
    ]);
    

Integration Tips

  • 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');
    

Gotchas and Tips

Common Pitfalls

  1. API Key Exposure

    • Never commit .env or hardcode MAILGUN_API_KEY. Use Laravel's .env securely.
    • Fix: Validate keys in config/logging.php:
      'api_key' => env('MAILGUN_API_KEY') ?: throw new \RuntimeException('Mailgun API key not set.'),
      
  2. Rate Limiting

    • Mailgun has API rate limits (~1000 requests/minute). High-volume logs may trigger limits.
    • Fix: Throttle logs or use a lower log level (e.g., WARNING instead of DEBUG).
  3. HTML/Email Formatting

    • Mailgun emails render HTML by default. Plain-text logs may appear malformed.
    • Fix: Use Log::channel('mailgun')->withContext(['format' => 'text']) for plain-text logs.
  4. Missing Dependencies

    • The package requires guzzlehttp/guzzle (installed automatically via Composer).
    • Fix: Ensure guzzlehttp/guzzle is in composer.json if manually installing.
  5. Subject Overrides

    • The subject config is global. Dynamic subjects require customization.
    • Fix: Extend the handler:
      $handler = new \Tylercd100\Monolog\MailgunHandler(
          $apiKey,
          $domain,
          function ($record) {
              return "Custom Subject: {$record['context']['user_id']}";
          }
      );
      

Debugging Tips

  • 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
    

Extension Points

  1. Custom Handlers Extend \Tylercd100\Monolog\MailgunHandler to add:

    • Attachments (e.g., screenshots).
    • Custom email templates.
    • Webhook notifications.
  2. Middleware Add a LogMiddleware to log HTTP requests/responses:

    Log::channel('mailgun')->info('Incoming request', [
        'method' => $request->method(),
        'path' => $request->path(),
        'input' => $request->all(),
    ]);
    
  3. 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
        )
    );
    
  4. Slack/Teams Integration Forward Mailgun emails to Slack/Teams using Mailgun's routing features.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor