PHP Logging Library

GitHub GitHub last commit CI Workflow GitHub code size in bytes GitHub Issues Total Downloads Monthly Downloads

A flexible, PSR-3 compliant PHP logging library that leverages Monolog and add additional features while maintaining a clean and simple API.

Features

  • PSR-3 Compatible: Implements the PSR-3 logging interface for standardized usage.
  • In-Memory Log Storage: Store logs in memory for retrieval during runtime.
  • Caller Information: Automatically track which class, method, file, and line generated each log message.
  • Custom Formatting: Enhanced line formatter that includes caller information.
  • Multiple Log Levels: Support for all standard log levels (debug, info, notice, warning, error, critical, alert, emergency).
  • Context Support: Add structured data to your log messages.
  • Monolog Integration: Built on top of Monolog for robust logging capabilities.

Installation

composer require derafu/log

Basic Usage

use Derafu\Log\Level;
use Derafu\Log\Service\Logger;
use Derafu\Log\Service\LogService;
use Derafu\Log\Service\LineFormatter;

// Create a logger with a line formatter.
$logger = new Logger(
    formatter: new LineFormatter()
);

// Create the log service.
$logService = new LogService($logger);

// Log messages with different levels.
$logService->logger()->debug('Debug message');
$logService->logger()->info('Info message');
$logService->logger()->warning('Warning message', ['context' => 'value']);
$logService->logger()->error('Error message', ['error_code' => 500]);

// Retrieve all logs.
$allLogs = $logService->logs();

// Retrieve only error logs.
$errorLogs = $logService->logs(Level::ERROR);

// Retrieve logs, newest first (default).
$newestFirst = $logService->logs(null, true);

// Retrieve logs, oldest first.
$oldestFirst = $logService->logs(null, false);

// Clear logs.
$logService->clear(); // Clear all logs.
$logService->clear(Level::ERROR); // Clear only error logs.

// Retrieve logs and clear them in one operation.
$logs = $logService->flush();

Caller Information

One of the key features of this library is automatic tracking of the caller information. Every log includes details about which class, method, file, and line generated the log message:

$logService->logger()->error('Something went wrong');

// The log will include caller information automatically.
$logs = $logService->logs();
$caller = $logs[0]->getCaller();

echo $caller; // Outputs: in /path/to/file.php on line 42, called by Namespace\Class::method()

Working with Log Records

Each log record provides methods to access its data:

$logs = $logService->logs();
$log = $logs[0];

// Access log data.
$level = $log->getCode();
$message = $log->getMessage();
$context = $log->getContext();
$caller = $log->getCaller();

Dependency Injection

Import the package configuration to obtain a shared Derafu\Log\Contract\LoggerInterface and LogServiceInterface:

imports:
    - { resource: '../vendor/derafu/log/resources/config/log-services.yaml' }

parameters:
    derafu.log.configuration:
        channel: application

The configuration defaults to an empty array, using channel derafu_lib. This composition does not register or replace Psr\Log\LoggerInterface; an application can keep its existing PSR logger independently.

Contribute additional Monolog handlers through the derafu_log.handler tag:

services:
    Monolog\Handler\StreamHandler:
        arguments:
            $stream: '%kernel.logs_dir%/application.log'
        tags: ['derafu_log.handler']

The journal remains attached automatically. Tagged handlers are collected in priority order and pushed onto Monolog’s stack, which executes them in reverse order. The journal handler runs first. Each additional handler keeps its own formatter and Monolog’s normal level and bubbling behavior.

Optionally provide Monolog\Formatter\FormatterInterface to customize the journal’s formatted records:

services:
    Monolog\Formatter\FormatterInterface:
        class: Monolog\Formatter\LineFormatter
        arguments:
            $format: '%%channel%%: %%message%%'

Double percent signs escape Monolog’s placeholders in Symfony configuration. This formatter applies to journal records only; it does not configure the other handlers. Without this service, the journal uses Monolog’s default formatter.

Calling getJournal(), logs(), clear() or flush() before the first message initializes the logger without producing a log record. The journal is initially empty and remains the same instance for subsequent writes.

Advanced Configuration

You can customize the logger with additional handlers:

use Monolog\Handler\StreamHandler;
use Monolog\Level;

// Create a logger with additional handlers.
$logger = new Logger(
    configuration: ['channel' => 'app'],
    handlers: [
        new StreamHandler('path/to/your.log', Level::Debug),
        // Add more handlers as needed.
    ],
    formatter: new LineFormatter()
);

$logService = new LogService($logger);

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

This package is open-sourced software licensed under the MIT license.

On this page

#php
Last updated on 15/11/2026 by Anonymous