PHP Luminova: Application Logger Helper
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
LoggerInterfacefor 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:
- Email (
logger.mail.logs) - Remote URL (
logger.remote.logs) - Telegram (
logger.telegram.bot.token+logger.telegram.bot.chat.id) - 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:idNotes:
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.tokenenvironment 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 IDBot:Token– Custom bot tokenLog message to Telegram– Log message content
Multiple Logging
You can merge multiple messages into a single log entry. This improves readability and reduces write overhead.
Using Literal Log Entries
Build the log content manually using Logger::entry():
use Luminova\Logger\Logger;
use Luminova\Logger\LogLevel;
$messages = [
'Debug message one',
'Debug message two',
];
$entry = '';
foreach ($messages as $message) {
$entry .= Logger::entry(LogLevel::DEBUG, $message);
}
Logger::debug($entry);This approach formats each entry first, then sends everything in one log call.
Using the Entry Class
Use the Luminova\Logger\Entry class for cleaner and more structured logs:
use Luminova\Logger\Logger;
use Luminova\Logger\Entry;
use Luminova\Logger\LogLevel;
$messages = [
'Debug message one',
'Debug message two',
];
$entry = new Entry();
foreach ($messages as $message) {
$entry->add(LogLevel::DEBUG, $message);
}
Logger::debug($entry->toString());
Entryis better when you need structured, multi-line logs or want to attach context data per message.
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\LoggerInterfaceReturn Value:
Psr\Log\LoggerInterface - Return the active logger instance.
emergency
Logs a system emergency (highest severity).
public static emergency(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The emergency message to log. |
$context | array | Additional context data (optional). |
alert
Logs an alert that requires immediate action.
public static alert(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The alert message to log. |
$context | array | Additional context data (optional). |
critical
Logs a critical condition that requires prompt attention.
public static critical(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The critical message to log. |
$context | array | Additional context data (optional). |
error
Logs an error that prevents execution but does not require immediate shutdown.
public static error(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The error message to log. |
$context | array | Additional context data (optional). |
warning
Logs a warning about a potential issue.
public static warning(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The warning message to log. |
$context | array | Additional context data (optional). |
notice
Logs a normal but significant event.
public static notice(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The notice message to log. |
$context | array | Additional context data (optional). |
info
Logs general informational messages.
public static info(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The info message to log. |
$context | array | Additional context data (optional). |
debug
Logs debugging information for developers.
public static debug(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The debug message to log. |
$context | array | Additional context data (optional). |
exception
Logs an exception with additional context.
public static exception(\Throwable|string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | \Throwable|string | The exception message to log. |
$context | array | Additional context data (optional). |
php
Logs a PHP runtime error.Alias for phpError, logs PHP-related issues.
public static php(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The php message to log. |
$context | array | Additional context data (optional). |
metrics
Logs performance and metric data.
public static metrics(string $data, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$data | string | The profiling data to log. |
$context | array | Additional context data (optional). |
log
Write log a message at a specified log level.
public static log(string $level, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | The log level (e.g., LogLevel::INFO, emergency). |
$message | string | The log message. |
$context | array<string,mixed> | Additional context data (optional). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If logger does not implement LoggerInterface
tracer
Sets a debug trace to the active logger, if tracing is supported.
This method forwards the given trace data to the internal loggeronly when the logger instance supports tracing (NovaLogger).
If tracing is unavailable or unsupported, the call is safely ignored.
public static tracer(array $trace): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$trace | array | Debug trace data (stack trace, context, metadata). |
Return Value:
boolReturns true when the trace was accepted by the logger, false when tracing is not supported or no logger is available.
entry
Generates a log entry with an ISO 8601 timestamp (including microseconds).
This method is useful for logging multiple messages that share the same severity level, especially in loops or batch operations. Instead of logging each entry separately, you can construct multiple log entries and log them all at once for better efficiency.
public static entry(string $level, string $message, array $context = []): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | The log severity level (e.g., LogLeve::INFO, LogLeve::ERROR). |
$message | string | The main log message. |
$context | array<string,mixed> | Optional contextual data for the log entry. |
Return Value:
string- Return the formatted log entry in plain text, ending with a newline.
Example:
use Luminova\Logger\Logger;
use Luminova\Logger\LogLevel;
$entry = Logger::entry(LogLevel::DEBUG, 'Debug message one');
$entry .= Logger::entry(LogLevel::DEBUG, 'Debug message two');
// Log both entries
Logger::debug($entry);dispatch
Sends a log message to a specified destination, such as a file, email, remote server, or Telegram bot chat.
The destination is determined by the $to parameter, which can be a log level, email address, URL, Telegram chat ID, or null.
- Development mode: Logs default to a local file unless an explicit email, URL, or chat ID is provided.
Production mode: If no
$tois provided, the method checks environment configuration for default destinations:logger.mail.logs→ Set email address to send logs to email.logger.remote.logs→ Set URL for remote logging URL.logger.telegram.bot.token→ Set Telegram Bot Token.logger.dispatch.levels→ The allowed log levels (default:[critical, emergency, alert, exception]).
public static dispatch(string|int|null $to, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$to | string|int|null | The destination for the log message (log level, email address, URL, telegram bot chat Id or NULL). |
$message | string | The message to log. |
$context | array | Additional data to provide context for the log (optional). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the provided destination is invalid (not a valid log level, email address, or URL).
- \Luminova\Exceptions\RuntimeException - If network or email logging is attempted in a non-novalogger class, or if the logger does not implement the PSR LoggerInterface.
Note:
If
logger.dispatch.levelsis not set in.env, the default will be used.
Sends a log message via email.
This method validates the email address and message, then sends the log message to the specified email address using the configured logger.
public static mail(string $email, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$email | string | The email address to send the log message to. |
$message | string | The log message to be sent. |
$context | array | Additional context data to be included in the log message (optional). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the provided email address is invalid.
- \Luminova\Exceptions\RuntimeException - If the logger doesn't support email functionality.
remote
Sends a log message to a remote server via HTTP POST.
This function sends a log message to a specified remote server using HTTP POST. The function validates the URL and ensures that the log message is not empty.
If the URL is invalid or the log message is empty, the function returns without performing any action.
public static remote(string $url, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$email | string | The URL of the remote server to send the log message to. |
$message | string | The log message to be sent. |
$context | array | Additional context data to be included in the log message (optional). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the provided URL is invalid.
- \Luminova\Exceptions\RuntimeException - If the logger doesn't support remote logging functionality.
See HTTP Remote Logging for more guides.
telegram
Sends a log message to a Telegram chat using the Telegram Bot API.
public static telegram(string|int $chatId, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$chatId | string|int | The chat ID to send the message to. |
$message | string | The log message to be sent. |
$context | array | Additional context data to be included in the log message (optional). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the provided chat Id is invalid.
- \Luminova\Exceptions\RuntimeException - If the logger doesn't support telegram logging functionality.
Note:Set Telegram bot token in
env(logger.telegram.bot.token)and provide Bot$chatId.