Luminova Framework

PHP Luminova: Application Logger Helper

Last updated: 2026-04-06 23:13:38

Logger helper centralizes application logging and dispatches messages to supported channels.

The Logger class is a helper in Luminova for handling application logs. It provides a unified set of static, level-based methods for writing logs across multiple channels. Acting as a dispatcher, it works with any PSR-3 compliant logger configured in your application’s service kernel.

When NovaLogger is used as the default logger, the dispatch() method automatically routes critical logs to a remote server, Telegram, or email based on your environment configuration (.env) when running in production.


Key Features

  • PSR-3 Compliant: Accepts LoggerInterface for seamless integration with third-party loggers.
  • Ready by Default: Preconfigured and enabled, ready to use.
  • Multi-Channel Logging: Supports files, remote servers, email, and Telegram.
  • Automatic Context Injection: Enriches logs with relevant HTTP request data for easier debugging.

Customization

Using a Custom Logger

You can replace the default logger with any PSR-compliant implementation by returning it from the getLogger method in your App\Kernel class.

// /app/Kernel.php
namespace App;

use Monolog\Logger;
use Psr\Log\LoggerInterface;
use Monolog\Handler\StreamHandler;

final class Kernel implements ServiceKernelInterface
{
    public function getLogger(): ?LoggerInterface
    {
        return (new Logger('custom-channel'))
            ->pushHandler(
                new StreamHandler(root('/writeable/logs/', 'debug.log'))
            );
    }
}

Note:This allows you to switch logging implementations without changing application code.Ensure your custom logger implements Psr\Log\LoggerInterface.


Auto Log Context

The Auto Log Context feature automatically adds useful request-based information to your logs. This is helpful when tracing issues tied to specific users, clients, or requests.

Configuration

Set the following static properties in your logger configuration:

// /app/Config/Logger.php
namespace App\Config;

use Luminova\Base\Configuration;

class Logger extends Configuration
{
    public static ?string $contextFieldName = 'username';
    public static ?string $contextHeaderName = 'X-API-CLIENT-ID';
}
  • $contextFieldName: Extracts a value from request data (GET, POST, or payload).
  • $contextHeaderName: Extracts a value from a specific HTTP header.

Example:

If a client reports an intermittent issue, including their X-API-CLIENT-ID or username ensures every related log entry carries that identifier.

When Enabled, core framework logs (errors, exceptions, and system logs) automatically include these context values when available.


Usages

Global Helper Function

The global logger() helper provides a quick way to write logs without creating a logger instance.

use function Luminova\Funcs\logger;

// Informational log
logger('info', 'This is an informational message.');

// Remote log (URL)
logger('https://example.com/api/log', 'This is a remote log message.');

// Email log
logger('[email protected]', 'This is an email log message.');

// Telegram log
logger('123456789', 'This is a Telegram log message.');

Using Static Methods

You can log messages directly using static methods on the Logger class.

use Luminova\Logger\Logger;

Logger::info('This is an informational message.');
Logger::error('This is an error message.');
Logger::log('critical', 'This is a critical issue.');

This approach is ideal for quick logging without managing logger instances.


Log Dispatching

Automatic Dispatch in Production

The Logger::dispatch() method automatically sends logs to an external destination based on your environment configuration. Destinations are evaluated in the following priority order:

  1. Email (logger.mail.logs)
  2. Remote URL (logger.remote.logs)
  3. Telegram (logger.telegram.bot.token + logger.telegram.bot.chat.id)
  4. Local error log (fallback if no other destination is configured)
Logger::dispatch('error', 'This is an error message.');

Only one destination is used per dispatch, following the priority above.


Dispatch Configuration

You can configure which log levels are eligible for dispatching and where logs are sent via your .env file:

# /.env

# Define log levels that should trigger remote, email, or Telegram dispatch
logger.dispatch.levels = [critical,emergency,alert,exception]

# Send logs to email
logger.mail.logs = [email protected]

# Send logs to a remote server
logger.remote.logs = https://example.com/logs/ingest
# Shared encryption key for remote logging
logger.remote.shared.key = key:secret

# Send logs to a Telegram bot
logger.telegram.bot.token = bot:token
logger.telegram.bot.chat.id = chat:id

Notes:

  • dispatch() is intended for critical or high-priority logs in production.
  • Development mode defaults to local file logging unless an explicit destination is provided.
  • Only one destination is used per dispatch call, based on the configured priority.

Send Logs by Email

To send logs by email, set the logger.mail.logs environment variable to a valid email address.

Manual dispatch:

Logger::dispatch('[email protected]', 'Critical error detected.');

Or call the helper directly:

Logger::mail('[email protected]', 'Critical error detected.');

Send Logs to a Remote URL

To forward logs to a remote endpoint, configure logger.remote.logs with the target URL.

Manual dispatch:

Logger::dispatch('https://example.com/api/log', 'Critical error detected.');

Or use the shortcut method:

Logger::remote('https://example.com/api/log', 'Critical error detected.');

Send Logs to Telegram

To send logs to Telegram, configure the target chat ID using telegram.bot.chat.id.

Manual dispatch:

Logger::dispatch('123456789', 'Critical error detected.');

Or call the Telegram method directly:

Logger::telegram('123456789', 'Critical error detected.');

The bot token is read from the logger.telegram.bot.token environment variable.


Use a Different Telegram Bot Token

To send a log using a bot token other than the default (.env), call the logger instance directly or use Luminova\Logger\NovaLogger class instead.

Example:

Logger::logger()
        ->telegram('123456789', 'Bot:Token', 'Log message to Telegram');

Parameters:

  • 123456789 – Target chat ID
  • Bot:Token – Custom bot token
  • Log message to Telegram – Log message content

Repeated Logging

You can merge multiple or repeated messages into a single log entry. This improves readability and reduces write overhead.

This approach formats each entry first, then sends everything in one log call.


Literal Log Entries

Build the log content manually using Logger::entry():

use Luminova\Logger\Logger;
use Luminova\Logger\LogLevel;

$entry = Logger::entry(LogLevel::DEBUG, 'Debug message one');
$entry .= Logger::entry(LogLevel::DEBUG, 'Debug message two');

Logger::debug($entry);

Log Entry Object

The Entry class allows you to collect multiple log messages and dispatch them in a single call.Use it when working with structured logs, multi-line output, when attaching context per entry or reduce repeated logger calls.


Log Entry Usage

use Luminova\Logger\Entry;
use Luminova\Logger\LogLevel;

$entry = new Entry(LogLevel::DEBUG);

$entry->add('Debug message one', [...]);
$entry->add('Debug message two', [...]);

// Dispatch all entries
$entry->log();

Log Entry Helper Methods

$entry->isEmpty();     // Check if no entries exist
$entry->count();       // Get total entries
$entry->clear();       // Remove all entries
$entry->toString();    // Convert entries to string
$entry->getEntries();  // Retrieve array of entries

Class Definition

  • Class namespace: Luminova\Logger\Logger
  • This class marked as final

Methods

logger

Return the active PSR-compliant logger instance.

Falls back to the default NovaLogger if no custom logger is configured in App\Kernel->getLogger().

public static logger(): Psr\Log\LoggerInterface

Return Value:

Psr\Log\LoggerInterface - Return the active logger instance.


emergency

Logs a system emergency (highest severity).

public static emergency(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe emergency message to log.
$contextarrayAdditional context data (optional).

alert

Logs an alert that requires immediate action.

public static alert(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe alert message to log.
$contextarrayAdditional context data (optional).

critical

Logs a critical condition that requires prompt attention.

public static critical(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe critical message to log.
$contextarrayAdditional context data (optional).

error

Logs an error that prevents execution but does not require immediate shutdown.

public static error(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe error message to log.
$contextarrayAdditional context data (optional).

warning

Logs a warning about a potential issue.

public static warning(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe warning message to log.
$contextarrayAdditional context data (optional).

notice

Logs a normal but significant event.

public static notice(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe notice message to log.
$contextarrayAdditional context data (optional).

info

Logs general informational messages.

public static info(string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$messagestringThe info message to log.
$contextarrayAdditional context data (optional).

debug

Logs debugging information for developers.