PHP Luminova: NovaLogger PSR Abstract 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 in the 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\Application
{
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\Configuration;
use Luminova\Interface\RequestInterface;
class Logger extends Configuration
{
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;createBackup
Flag indicating if backup should be created.
protected bool $createBackup = 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
protected array $tracer = [];Methods
constructor
Create a new logger instance.
Initializes logger configuration, resolves storage path, and applies environment-based limits and behaviors.
public __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}'). |
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 getLogFormat(): stringReturn Value:
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 setLogFormat(string $format): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Custom format template. (e.g, [{level}] [{name}] [{time:Y-m-d\TH:i:s.uP}] {message} {context}). |
Return Value:
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 setName(string $name): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The Logging system name. |
Return Value:
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 setTracer(array $trace): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$trace | array | Debug trace data (stack trace, context, metadata). |
Return Value:
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 setMaxLogSize(int $size): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$size | int | The maximum size of the log file in bytes. |
Return Value:
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 setAutoBackup(bool $backup = true): self Parameters:
| Parameter | Type | Description |
|---|---|---|
$backup | bool | Set to true to enable auto-backup, false to disable it (default: true). |
Return Value:
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 setLevel(string|int $level): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level to set (e.g., 'error', 'info', 'debug'). |
Return Value:
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 log(string|int $level, string $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 | Optional associative array providing 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 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 | Additional context data (optional). |
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 remote(string $url, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The remote URL endpoint to send the log to. |
$message | string | The log message to send. |
$context | array | 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
Sends a log message to a Telegram chat using the Telegram Bot API.
This method sends an error log to a telegram chat bot, allowing to get instant notification on telegram when error occurs in your application.
public telegram(string|int $chatId, string $token, string $message, array $context = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$chatId | string|int | The telegram chat ID to send the message to. |
$string | string | The telegram bot token. |
$message | string | The log message to send. |
$context | array | Additional contextual data related to the log message. |
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>clear
Clears the contents of the specified log file for a given log level.
public clear(string|int $level): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level whose log file should be cleared (e.g., 'info', 'error'). |
Return Value:
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 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 associative array providing context data. |
$htmlFormat | bool | Whether to format the message and context as HTML (default: false). |
Return Value:
string - 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 backup(string|int $level): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log level to create backup for. |
Return Value:
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 toHtmlMessage(string|int $level, string $message, array $context = []): ?string Parameters:
| Parameter | Type | Description |
|---|---|---|
$level | string|int | The log entry level (e.g., INFO, ERROR). |
$message | string | The log entry message. |
$level | string|int | The additional contextual information passed with log entry. |
Return Value:
string|null - Return HTML-formatted string representing the log message and context or null for default.