PHP Luminova: NovaLogger PSR Error Logger
NovaLogger is Luminova’s default logging system, supporting file logs, email notifications, and remote server log dispatch.
The NovaLogger class is the default logging system for Luminova framework. It helps you track application events, create log backups, and send logs via email or to remote servers. It also supports both PSR-style string levels (e.g., error, info) and RFC 5424 numeric levels (0–7).
If you prefer, you can replace NovaLogger with any PSR-compliant logger (like Monolog) by updating the App Service Kernel class's getLogger method. This makes it easy to route all logging operations to a custom logger.
Key Features
- Default Logger: Automatically configured for Luminova applications.
- Flexible Logging: Logs can be written to files, emailed, or sent to remote servers.
- Customizable: Options include file extensions, logging format, and dispatch methods.
Usage
Log Template Formatting
You can customize how log messages are rendered by defining a log format template.
This can be configured in two ways:
- Environment configuration using
logger.log.format - Programmatically during application bootstrap (for example, in the
onPreCreateoronCreatemethod)
To customize the log template, use curly braces {} with the allowed placeholders (level, name, time, message, ipaddress, referer, useragent, context). You can place each placeholder anywhere in the string to fit your needs.
You can also include additional text outside the braces. For example:
"My Message: {message} - Logged at {time:Y-m-d H:i:s}"The {time} placeholder supports optional PHP datetime formatting, e.g., {time:Y-m-d h:i:s}.
This allows you to create a custom, readable log format while including extra context or labels.
Configure via Environment
Set the log format in your .env file:
# /.env
logger.log.format = "[{level}] [{name}] [{time:Y-m-d\TH:i:s.uP}] {message} {referer} {useragent} {context}"This format will be used globally unless overridden in code.
Configure in Application Code
You can override the log format at runtime using NovaLogger::setLogFormat():
// /app/Application.php
namespace App;
use Luminova\Logger\NovaLogger;
class Application extends Luminova\Foundation\Core\AbstractApplication
{
protected function onPreCreate(): void
{
NovaLogger::setLogFormat(
'[{level}] [{name}] [{time:Y-m-d\TH:i:s.uP}] {message} {ipaddress} {referer} {useragent} {context}'
);
}
}Tip:Keep log formats concise. Logs are meant to be scanned quickly, especially in production environments.
Custom Logger
You can configure a custom logger in the App\Kernel class:
// /app/Kernel.php
namespace App;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
final class Kernel implements ServiceKernelInterface
{
public function getLogger(): ?LoggerInterface
{
return new NovaLogger(
name: 'custom-channel',
extension: '.txt',
useLocking: false,
logFormat: '[{time:Y-m-d H:i:s}] {level}: {message}'
);
}
}Note:Any logger implementing the PSR-3
LoggerInterfacecan be used instead of NovaLogger.
Logging Messages
Log messages:
$logger->log(LogLevel::INFO, 'This is an info message');
$logger->log(LogLevel::ERROR, 'This is an error message');Email Logs
Send logs directly via email:
$logger->setLevel('error')
->mail('[email protected]', 'This is a log sent via email');Custom Email Template
You can define a custom HTML template by implementing getEmailLogTemplate. Returning null will use the default template.
// /app/Config/Logger.php
namespace App\Config;
use Psr\Log\AbstractLogger;
use Luminova\Base\AbstractConfig;
use Luminova\Interface\RequestInterface;
class Logger extends AbstractConfig
{
public static function getEmailLogTemplate(
RequestInterface $request,
AbstractLogger $logger,
string $message,
string $level,
array $context
): ?string
{
return "<template>{$message}</template>";
}
}Remote Logs
Send logs to a remote server:
$logger->setLevel('debug')
->remote('https://example.com/api/log', 'This is a log sent to a remote server');Tip:You can also use the
Luminova\Logger\Logger::dispatchmethod to send logs to files, email, or remote servers based on their type.
See HTTP Remote Logging for more guides.
Class Definition
- Class namespace:
Luminova\Logger\NovaLogger - Parent class: Psr\Log\AbstractLogger
Properties
maxSize
The maximum log size in bytes.
protected int $maxSize = 0;autoBackup
Flag indicating if backup should be created.
protected bool $autoBackup = false;extension
The log file extension type (e.g, .txt, .log).
protected string $extension = '.log';name
The logging system name (e.g, app, foo).
protected string $name = 'AppLogger';tracer
Remote logging debug tracer
/**
* @var array<array-key, mixed>
*/
protected array $tracer = [];Methods
constructor
Create a new logger instance.
Initializes logger configuration, resolves storage path, and applies environment-based limits and behaviors.
public function __construct(
string $name = 'AppLogger',
string $extension = '.log',
bool $useLocking = true,
?string $logFormat = null
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The logger identifier (default: AppLogger). |
$extension | string | The log file extension (default: .log). |
$useLocking | bool | Enable file locking during writes (default: true). |
$logFormat | ?string | Optional custom log format. (e.g, '[{time:Y-m-d\TH:i:s.uP}] {level} {name} {message} {context}') (default null). |
getLogFormat
Get the active log format.
Returns the currently configured log format. If none has been set,it will be resolved once from the environment configuration andcached for subsequent calls.
public static function getLogFormat(): stringReturn:
string - Returns the active log format string.
setLogFormat
Set a custom log format.
Overrides the global log format used when rendering log messages.Passing an empty string resets the format back to the environment env(logger.log.format) or the default configuration.
Supported placeholders:
{level}Uppercased log level (DEBUG, INFO, ERROR, etc.){name}Logger or channel name{time:format}Date/time with optional PHP date format (default:Y-m-d H:i:s){message}Log message string{ipaddress}Client IP address{referer}HTTP referer, if available{useragent}Client user agent string{context}Context payload (JSON in production, readable dump in development)
public static function setLogFormat(string $format): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$format | string | Custom format template (e.g. [{level}] [{name}] [{time:Y-m-d\TH:i:s.uP}] {message} {referer} {useragent} {context}). |
Return:
string - Returns the active log format after assignment.
Examples:
Simple format (short date and level first):
NovaLogger::setLogFormat(
'[{time:Y-m-d H:i:s}] {level}: {message}'
);Monolog style (ISO 8601 datetime with microseconds):
NovaLogger::setLogFormat(
'[{time:Y-m-d\TH:i:s.uP}] {name}.{level}: {message} [{context}]'
);Verbose format (includes context payload):
NovaLogger::setLogFormat(
'[{time:Y-m-d H:i:s.u}] {name} [{level}]: {message} Context: {context}'
);Custom format (channel and log level inline):
NovaLogger::setLogFormat(
'{name} | {level} | {time:Y-m-d H:i:s} | {message}'
);setName
Sets the log name for application identifier.
public function setName(string $name): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The Logging system name. |
Return:
self - Returns the instance of NovaLogger class.
setTracer
Store a debug trace for later remote logging.
Saves the provided trace data on the logger instance so it can beattached to remote log submissions. The trace is not written to local logs and is not sent via email or Telegram.
public function setTracer(array $trace): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$trace | array<array-key,mixed> | Debug trace data (stack trace, context, metadata). |
Return:
self - Returns the instance of NovaLogger class.
This method only stores the trace and does not trigger logging.
setMaxLogSize
Sets the maximum size for log files.
This method allows setting a custom maximum size for log files. When a log file reaches this size, it may trigger backup or clearing operations depending on other configuration settings.
public function setMaxLogSize(int $size): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$size | int | The maximum size of the log file in bytes. |
Return:
self - Returns the instance of NovaLogger class.
setAutoBackup
Enables or disables automatic log file backup based on maximum log size configuration.
When enabled, old log files will be automatically archived to prevent excessive log size and improve performance.
public function setAutoBackup(bool $backup = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$backup | bool | Set to true to enable auto-backup, false to disable it (default: true). |
Return:
self - Returns the instance of NovaLogger class.
setLevel
Sets the default log level for the remote or email logging.
When sending logs via email or to a remote server, the default log level will be use in case of failure.It also serves as an indicator of log severity.
public function setLevel(string|int $level): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level to set (e.g., 'error', 'info', 'debug'). |
Return:
self - Returns the instance of NovaLogger class.
Note:
Setting log level with this method doesn't affect
logandwritemethods.This is only forremoteand
log
Log a message at the given level.
Writes a log message to the specified file.
public function log($level, $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level (e.g., emergency, error, info). |
$message | string | The log message. |
$context | array<string, mixed> | Optional additional context data. |
Throws:
- Luminova\Exceptions\FileException - If unable to write log to file.
Logs message to an email.
This method prepares and sends an error log via email using the configured Mailer.If sending fails, it logs an error message.
public function mail(string $email, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$email | string | The recipient email address. |
$message | string | The message to log. |
$context | array<string,mixed> | Optional additional context data. |
Note:
If error occurs during mailing log, file logger will be used instead.If exception occurs during mailing log, file logger with level
exceptionbe used.
remote
Send a log message to a remote server.
This method builds a standard log payload, optionally encrypts it using the shared secret defined in env('logger.remote.shared.key'), and sends it to the given URL via HTTP POST.
Encryption behavior:
- In production: if encryption fails, the log is written to the local file system.
- In development: failure to encrypt throws a
RuntimeException.
Network errors:
- If sending the log fails, the message is written locally.
- If an exception occurs during sending, it is logged locally with level
exception.
public function remote(string $url, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The remote endpoint URL to send the log (e.g, https://example.com/api/logs). |
$message | string | The log message content. |
$context | array<string,mixed> | Optional additional context data. |
Throws:
- Luminova\Exceptions\RuntimeException - If encryption fails in a non-production environment.
Note:
If error occurs during network log, file logger will be used instead.If exception occurs during network log, file logger with level
exceptionbe used.
See HTTP Remote Logging for guides on configuring and handling remote logs.
telegram
Send a log message to a Telegram chat via the Bot API.
This method builds a formatted message and posts it to the given chat ID usingthe provided bot token. If credentials are missing, a critical log entry is recorded and the request is skipped.
public function telegram(string|int $chatId, string $token, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$chatId | string|int | Target telegram chat ID (user, group, or channel). |
$token | string | Telegram bot token used for authentication. |
$message | string | The log message content. |
$context | array<string,mixed> | Optional context data to append. |
Telegram Bot Setup
Setup Steps for Telegram Integration:
1. Create a Telegram Bot
- Open BotFather.
- Create a new bot and copy the generated bot token.
2. Manually Configure Environment Variables
- Send a message (e.g.,
"Hi!") to your bot. - Retrieve your chat ID using the following API:
https://api.telegram.org/bot<TOKEN>/getUpdates - Set the environment variables in your configuration for global use:
logger.telegram.bot.token = <TOKEN> logger.telegram.bot.chat.id = <CHAT_ID>
3. Automatically Configure via CLI
Use the novakit command to set up the Telegram bot:
php novakit env:setup -t=telegram
Enter your Telegram bot token: <TOKEN>slack
Send a log message to a Slack channel using an incoming webhook.
This method formats the message and delivers it to Slack via the webhook URL.If the webhook URL is missing, a critical log entry is recorded and the request is skipped.
public function slack(string $webhookUrl, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$webhookUrl | string | Slack incoming webhook URL. |
$message | string | The log message content. |
$context | array<string,mixed> | Optional context data to append. |
Slack Setup
Setup Steps for Telegram Integration:
1. Create Slack App
- Visit Slack App.
- Create a new app and enable incoming webhook.
2. Configure Environment Variables
- Set slack webhook URL in environment variables for global use:
logger.slack.webhook = https://hooks.slack.com/services/XYZ
clear
Clears the contents of the specified log file for a given log level.
public function clear(?string $level = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | ?string | The log level whose log file should be cleared (e.g., 'info', 'error'). |
Return:
bool - Returns true on success, or false on failure if the log file cannot be cleared.
message
Constructs a formatted log message with an ISO 8601 timestamp (including microseconds).
public function message(
string|int $level,
string $message,
array $context = [],
bool $htmlFormat = false
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level (e.g., LogLevel::DEBUG, info, error). |
$message | string | The primary log message. |
$context | array<string,mixed> | Optional additional context data (default []). |
$htmlFormat | bool | Whether to format the message and context as HTML (default: false). |
Return:
string|null - Return the formatted log message text/HTML based $htmlFormat or null if invalid log level.
backup
Creates a backup of the log file if it exceeds a specified maximum size.
public function backup(string|int $level): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level to create backup for. |
Return:
bool - Return true if the backup was created, otherwise false.
toHtmlMessage
Generates an HTML-formatted log message for email logging.
This method is called when sending log to email or generating a formatted HTML representation of a log message.
protected function toHtmlMessage(string|int $level, string $message, array $context = []): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log entry level (e.g., INFO, ERROR). |
$message | string | The log entry message. |
$context | array<string,mixed> | Additional context for the log entry (default []). |
Return:
string|null - Return HTML-formatted string representing the log message and context or null for default.
getName
Gets the logging system name identifier.
public function getName(): stringReturn:
string - Return the logging system name.
getExtension
Get the log file extension.
public function getExtension(): stringReturn:
string - Return extension.
getPath
Get the log directory path.
public function getPath(): stringReturn:
string - Return the dirpath.
exception
Log an exception message.
public function exception(Throwable|string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | Throwable|string | The EXCEPTION message to log. |
$context | array<string,mixed> | Additional context data (optional). |
php
Log an php message.
public function php(string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The php message to log. |
$context | array<string,mixed> | Additional context data (optional). |
metrics
Log an performance metric.
public function metrics(string $data, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$data | string | The profiling data to log. |
$context | array<string,mixed> | Additional context data (optional). |
formatMessage
Formats a log message with level, name, timestamp, and optional context.
public static function formatMessage(
string $level,
string $message,
?string $name = null,
array $context = [],
?string $format = null
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | The log level (e.g., 'INFO', 'ERROR'). |
$message | string | The main log message. |
$name | ?string | Optional log system name (default null). |
$context | array<array-key,mixed> | Additional contextual information for the log entry (default []). |
$format | ?string | Optional log message format (default). |
Return:
string|null - Return the formatted log message. If context is provided, it will be appended to the message.
getHandlers
Get all active log streams indexed by filename.
public function getHandlers(): arrayReturn:
array<string,resource> - Returns an array mapping each log filename to its open stream resource.
getStreamSize
Get the current size of the log file.
public function getStreamSize(?string $basename = null): intParameters:
| Parameter | Type | Description |
|---|---|---|
$basename | ?string | The log file basename. |
Return:
int - File size in bytes, or 0 if unavailable.
close
Close an open log streams.
public function close(mixed $stream = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$stream | mixed | Optional stream to close. |
runAutoBackup
Check the log file against the configured size limit. At or above the limit, the logger backs up the level’s log when automatic backup is enabled, or clears the log when backup is disabled. A missing or zero size limit skips the check.
public final function runAutoBackup(
string $level,
bool $async = true,
?string $filename = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | Log level used to select the log to clear or back up. |
$async | bool | Dispatch an enabled backup as a background task when true. |
$filename | string\|null | Check the size of this file basename. Null checks the default filename for the level. |