Weave 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

Simple Logger Laravel Package

averor/simple-logger

Simple, lightweight logger for PHP/Laravel apps. Provides an easy API to write log messages with minimal setup, useful for small projects, debugging, or when you want straightforward logging without extra configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require averor/simple-logger
    

    Add to config/app.php under providers (if not using auto-discovery):

    Averor\SimpleLogger\SimpleLoggerServiceProvider::class,
    
  2. Basic Usage Register the logger in config/logging.php:

    'channels' => [
        'simple' => [
            'driver' => 'custom',
            'via' => Averor\SimpleLogger\SimpleLogger::class,
            'level' => env('LOG_LEVEL', \Monolog\Logger::DEBUG),
        ],
    ],
    

    Then bind it in AppServiceProvider@boot():

    $this->app->bind(\Psr\Log\LoggerInterface::class, function ($app) {
        return new Averor\SimpleLogger\SimpleLogger($app['config']['logging.simple.level']);
    });
    
  3. First Use Case Inject \Psr\Log\LoggerInterface into a controller/service and log:

    public function index(LoggerInterface $logger) {
        $logger->debug('Debug message');
        $logger->info('User action', ['user_id' => 1]);
    }
    

Implementation Patterns

Core Workflows

  1. PSR-3 Compliance

    • Use standard methods (emergency(), alert(), critical(), ..., debug()).
    • Contextual data passed as associative arrays:
      $logger->warning('Failed', ['error' => $e, 'trace' => $e->getTraceAsString()]);
      
  2. Level-Based Filtering

    • Set log level in config (e.g., LOG_LEVEL=debug).
    • Only messages at or above the level are processed.
  3. Output Handlers

    • Default: Outputs to stderr (useful for CLI/Docker).
    • Customize: Extend Averor\SimpleLogger\Handler\AbstractHandler to write to files, databases, etc.
      $logger->setHandler(new CustomFileHandler('/path/to/logs'));
      
  4. Contextual Logging

    • Attach metadata (e.g., request IDs, user IDs) via middleware:
      $logger->withContext(['request_id' => $request->header('X-Request-ID')]);
      

Integration Tips

  • Monolog Bridge: Use monolog/monolog for advanced features (handlers, formatters) while keeping simple-logger as the core:
    $logger = new Averor\SimpleLogger\SimpleLogger();
    $monolog = new \Monolog\Logger('name', [$logger]);
    
  • Laravel Facade: Create a facade for convenience:
    facade: SimpleLogger { return app(LoggerInterface::class); }
    
  • Testing: Mock LoggerInterface in tests:
    $mock = Mockery::mock(LoggerInterface::class);
    $this->app->instance(LoggerInterface::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. No Built-in Formatting

    • Messages are logged as raw strings. Use a wrapper (e.g., monolog/monolog) for JSON/structured logs.
    • Example workaround:
      $logger->info(json_encode(['event' => 'user_login', 'data' => $user]));
      
  2. Thread Safety

    • Not thread-safe by design. Avoid in multi-threaded environments (e.g., queues with ignore_failure workers).
  3. Handler Limitations

    • Default handler (StderrHandler) is synchronous. For async logging, implement a custom handler.
  4. Level Case Sensitivity

    • Levels must match \Psr\Log\LogLevel constants exactly (e.g., DEBUG, not debug).

Debugging

  • Check Log Level: Ensure config matches runtime (e.g., php artisan config:clear if stale).
  • Handler Issues: Verify custom handlers implement Averor\SimpleLogger\Handler\HandlerInterface.
  • Context Loss: Use withContext() before logging to preserve metadata:
    $logger->withContext(['user_id' => auth()->id()])->info('Action performed');
    

Extension Points

  1. Custom Handlers

    • Extend AbstractHandler and override handle():
      class SlackHandler extends AbstractHandler {
          public function handle(array $record) {
              $this->sendToSlack($record['message'], $record['context']);
          }
      }
      
  2. Filtering

    • Implement Averor\SimpleLogger\Filter\FilterInterface to block sensitive data:
      $logger->addFilter(new SensitiveDataFilter(['password', 'token']));
      
  3. Performance

    • For high-volume logs, batch writes in custom handlers:
      class BatchFileHandler extends AbstractHandler {
          private $buffer = [];
          public function handle(array $record) {
              $this->buffer[] = $record;
              if (count($this->buffer) > 100) {
                  file_put_contents($this->path, implode("\n", $this->buffer));
                  $this->buffer = [];
              }
          }
      }
      
  4. Laravel-Specific

    • Bind to Laravel’s log stack for consistency:
      $this->app->extend(\Psr\Log\LoggerInterface::class, function ($app) {
          $logger = new Averor\SimpleLogger\SimpleLogger();
          $logger->pushHandler(new \Monolog\Handler\StreamHandler(storage_path('logs/simple.log')));
          return $logger;
      });
      
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.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource