Luminova Framework

PHP Luminova: NovaLogger PSR Abstract Logger

Last updated: 2026-01-14 11:11:58

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

  1. Default Logger: Automatically configured for Luminova applications.
  2. Flexible Logging: Logs can be written to files, emailed, or sent to remote servers.
  3. 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:

  1. Environment configuration using logger.log.format
  2. Programmatically during application bootstrap (for example, in the onPreCreate or onCreate method)

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 LoggerInterface can 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::dispatch method to send logs to files, email, or remote servers based on their type.

See HTTP Remote Logging for more guides.


Class Definition


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:

ParameterTypeDescription
$namestringThe logger identifier (default: AppLogger).
$extensionstringThe log file extension (default: .log).
$useLockingboolEnable file locking during writes (default: true).
$logFormatstringOptional 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(): string

Return 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): string

Parameters:

ParameterTypeDescription
$namestringCustom 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): self

Parameters:

ParameterTypeDescription
$namestringThe 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): self

Parameters:

ParameterTypeDescription
$tracearrayDebug 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): self

Parameters:

ParameterTypeDescription
$sizeintThe 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:

ParameterTypeDescription
$backupboolSet 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): self

Parameters:

ParameterTypeDescription
$levelstring|intThe 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 log and write methods.This is only for remote and mail logging, to identify the type of log level that triggered the logging.


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 = []): void

Parameters:

ParameterTypeDescription
$levelstring|intThe log level (e.g., emergency, error, info).
$messagestringThe log message.
$contextarrayOptional associative array providing context data.

Throws:


mail

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 = []): void

Parameters:

ParameterTypeDescription
$emailstringThe recipient email address.
$messagestringThe message to log.
$contextarrayAdditional 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 exception be 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 = []): void

Parameters:

ParameterTypeDescription
$urlstringThe remote URL endpoint to send the log to.
$messagestringThe log message to send.
$contextarrayOptional additional context data.

Throws:

Note:

If error occurs during network log, file logger will be used instead.If exception occurs during network log, file logger with level exception be 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 = []): void

Parameters:

ParameterTypeDescription
$chatIdstring|intThe telegram chat ID to send the message to.
$stringstringThe telegram bot token.
$messagestringThe log message to send.
$contextarrayAdditional 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): bool

Parameters:

ParameterTypeDescription
$levelstring|intThe 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): string

Parameters:

ParameterTypeDescription
$levelstring|intThe log level (e.g., LogLevel::DEBUG, info, error).
$messagestringThe primary log message.
$contextarray<string,mixed>Optional associative array providing context data.
$htmlFormatboolWhether 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): bool

Parameters:

ParameterTypeDescription
$levelstring|intThe 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:

ParameterTypeDescription
$levelstring|intThe log entry level (e.g., INFO, ERROR).
$messagestringThe log entry message.
$levelstring|intThe 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.