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

Laravel Logplex Laravel Package

shureban/laravel-logplex

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require shureban/laravel-logplex
    
  2. Register the service provider in config/app.php:
    Shureban\LaravelLogplex\LogplexServiceProvider::class,
    
  3. Publish the config:
    php artisan vendor:publish --provider="Shureban\LaravelLogplex\LogplexServiceProvider"
    
  4. Configure logging channels in config/logging.php:
    'logplex' => [
        'driver' => 'custom',
        'via' => \Shureban\LaravelLogplex\LogplexLogger::class,
        'level' => env('LOGPLEX_LEVEL', \Monolog\Level::Error),
    ],
    
  5. Update .env to include the logplex channel in your stack:
    LOG_STACK_CHANNELS=single,logplex
    
    Or modify the stack channel directly in config/logging.php:
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single', 'logplex'],
    ],
    

First Use Case: Logging Errors to Slack

Log an error with contextual data (e.g., user, request, trace):

Log::channel('logplex')->error('Failed to process payment', [
    'user_id' => auth()->id(),
    'request' => request()->all(),
    'trace' => collect(debug_backtrace())->slice(1)->toArray(),
]);

This will generate a rich Slack-formatted message with:

  • Timestamp
  • Log level (❌ for errors)
  • Contextual data (user, request payload)
  • Stack trace

Implementation Patterns

1. Channel Integration Workflow

  • Default: Use the logplex channel for structured logs.
  • Stacked Channels: Combine with single (file) or slack for dual output:
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single', 'logplex', 'slack'],
    ],
    
  • Conditional Logging: Filter logs by level (e.g., only error/critical to Logplex):
    'logplex' => [
        'driver' => 'custom',
        'via' => \Shureban\LaravelLogplex\LogplexLogger::class,
        'level' => env('LOGPLEX_LEVEL', \Monolog\Level::Error),
    ],
    

2. Contextual Logging

Attach metadata to logs using Laravel’s built-in context:

Log::channel('logplex')->info('User action', [
    'user' => auth()->user(),
    'metadata' => ['action' => 'profile_update'],
]);

The package automatically formats:

  • User data (ID, email, roles)
  • Request data (method, URL, headers)
  • Traceback (file, line, function)

3. Customizing Output

Override the default MessageBuilder to modify Slack blocks:

// app/Logging/Logplex/CustomMessageBuilder.php
namespace App\Logging\Logplex;

use Shureban\LaravelLogplex\Builder\MessageBuilderInterface;
use Shureban\LaravelLogplex\LogRecord;

class CustomMessageBuilder implements MessageBuilderInterface {
    public function buildSlackMessage(LogRecord $logRecord, string $username, string $emoji) {
        $message = new \Shureban\LaravelLogplex\Channels\Slack\Message($username, $emoji);
        $message->addBlock(new \App\Logging\Logplex\CustomUserBlock($logRecord));
        return $message;
    }
}

Bind it in AppServiceProvider:

public function boot() {
    $this->app->bind(
        \Shureban\LaravelLogplex\Builder\MessageBuilderInterface::class,
        \App\Logging\Logplex\CustomMessageBuilder::class
    );
}

4. Logging Exceptions

Wrap try/catch blocks for automatic exception logging:

try {
    // Risky operation
} catch (\Exception $e) {
    Log::channel('logplex')->error('Payment failed', [
        'exception' => $e,
        'context' => ['amount' => $request->amount],
    ]);
}

The package extracts:

  • Exception message
  • Stack trace
  • Custom context

5. Logging HTTP Requests

Use middleware to log incoming requests:

// app/Http/Middleware/LogRequests.php
public function handle($request, Closure $next) {
    Log::channel('logplex')->info('Incoming request', [
        'method' => $request->method(),
        'path' => $request->path(),
        'headers' => $request->header(),
    ]);
    return $next($request);
}

Gotchas and Tips

Pitfalls

  1. Channel Misconfiguration:

    • Issue: Logs disappear if LOG_STACK_CHANNELS is misconfigured.
    • Fix: Verify .env and config/logging.php:
      LOG_STACK_CHANNELS=single,logplex
      
      'stack' => ['channels' => ['single', 'logplex']],
      
  2. Missing User Context:

    • Issue: Logs lack user data if auth()->user() returns null.
    • Fix: Ensure middleware (e.g., Authenticate) runs before logging.
  3. Slack Formatting Errors:

    • Issue: Custom blocks break Slack rendering.
    • Fix: Validate JSON structure with:
      $block->toArray(); // Check output before Slack sends it
      
  4. Performance Overhead:

    • Issue: Heavy logs (e.g., large payloads) slow responses.
    • Fix: Use queue channel for async logging:
      'logplex' => [
          'driver' => 'queue',
          'queue' => 'logs',
          'via' => \Shureban\LaravelLogplex\LogplexLogger::class,
      ],
      

Debugging Tips

  • Check Logplex Endpoint: Ensure LOG_PLEX_ENDPOINT in .env is correct:
    LOG_PLEX_ENDPOINT=https://your-logplex-endpoint.com
    
  • Test Locally: Use logplex channel in development:
    LOG_LEVEL=debug
    LOG_STACK_CHANNELS=logplex
    
  • Inspect Raw Logs: Temporarily log to single channel to debug formatting:
    Log::channel('single')->debug('Raw log data', $logRecord->toArray());
    

Extension Points

  1. Custom Blocks:

    • Extend \Shureban\LaravelLogplex\Channels\Slack\Block to add new sections (e.g., DatabaseBlock).
    • Example:
      class DatabaseBlock implements Block {
          public function toArray() {
              return [
                  'type' => 'section',
                  'text' => [
                      'type' => 'mrkdwn',
                      'text' => '*Database Query*',
                  ],
                  'fields' => [
                      ['type' => 'mrkdwn', 'text' => '*Query:*\n```sql\nSELECT * FROM users```'],
                  ],
              ];
          }
      }
      
  2. Log Level Overrides:

    • Dynamically set log levels per channel:
      Log::channel('logplex')->debug('Debug message', [], \Monolog\Level::Debug);
      
  3. Webhook Integration:

    • Replace Slack with other webhooks (e.g., Discord, Teams) by extending MessageBuilderInterface:
      public function buildWebhookMessage(LogRecord $logRecord) {
          return [
              'content' => $logRecord->message,
              'embeds' => [/* custom embeds */],
          ];
      }
      

Configuration Quirks

  • Environment Variables:

    • LOGPLEX_LEVEL: Defaults to error; set to debug for verbose logs.
    • LOGPLEX_USERNAME: Customize the bot username in Slack (default: LaravelLogplex).
    • LOGPLEX_EMOJI: Change the emoji (e.g., :robot_face:).
  • Logplex-Specific:

    • Ensure your Logplex endpoint supports JSON payloads (Heroku/Papertrail do).
    • For Heroku, use the LOG_PLEX_TOKEN env var if authentication is required.

Pro Tips

  1. Log Retention:

    • Configure Logplex retention policies (e.g., 30 days) to avoid storage costs.
  2. Alerting:

    • Use Logplex filters to trigger alerts (e.g., level=error AND user_id=123).
  3. Local Development:

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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