Log
in package
Class Log
Simple, powerful logger designed for use with Primordyx EventManager. Features enhanced interpolation, flexible configuration, and secure file handling.
This logger is designed to work with EventManager for sophisticated routing:
- Different event types can log to different files
- Trouble users can have dedicated log files
- Multiple handlers can process the same event differently
- Each Log instance is configured for a specific purpose
Basic usage: Create Log instance with file path, call logging methods EventManager integration: Multiple Log instances achieve file "aliasing" Enhanced interpolation: Supports placeholders with default values
Tags
Table of Contents
Constants
- LEVELS = [ 'EMERGENCY' => 800, 'ALERT' => 700, 'CRITICAL' => 600, 'ERROR' => 500, 'WARNING' => 400, 'NOTICE' => 300, 'SUCCESS' => 250, // Custom level 'INFO' => 200, 'DEBUG' => 100, 'TRACE' => 50, ]
- Log levels for validation
Properties
- $allowedLevels : array<string|int, mixed>
- $echoToStdout : bool
- $file : string
- $formatter : callable|null
- $maxSize : int
- $sessionId : string
- $silence : bool
- $useUtc : bool
Methods
- __construct() : mixed
- Create a new logger instance
- alert() : void
- Action must be taken immediately
- allowedLevels() : array<string|int, mixed>
- Get/Set allowed log levels
- cleanupRotatedFiles() : int
- Clean up old rotated log files
- clearFormatter() : self
- Clear custom formatter (use default)
- compactFormatter() : callable
- Compact formatter - minimal output
- critical() : void
- Critical conditions
- debug() : void
- Debug-level messages
- detailedFormatter() : callable
- Detailed formatter - includes extra context
- echoToStdout() : bool
- Get/Set whether to echo logs to stdout
- emergency() : void
- System is unusable
- error() : void
- Error conditions
- file() : string
- Get current file path (read-only)
- formatter() : callable|null
- Get/Set custom formatter
- getConfig() : array<string|int, mixed>
- Get current configuration
- getFileStats() : array<string|int, mixed>
- Get file statistics
- info() : void
- Informational messages
- jsonFormatter() : callable
- JSON formatter - outputs structured JSON logs
- log() : void
- Log with an arbitrary level
- maxSize() : int
- Get/Set maximum file size before rotation
- notice() : void
- Normal but significant condition
- rotateNow() : void
- Force log rotation now
- sessionId() : string
- Get/Set session ID
- silence() : bool
- Get/Set silence mode
- success() : void
- Success-level messages (Custom Level)
- syslogFormatter() : callable
- Syslog-style formatter
- trace() : void
- Trace-level messages (Custom Level)
- useUtc() : bool
- Get/Set UTC mode
- warning() : void
- Warning conditions
- webFormatter() : callable
- Custom web request formatter - great for web applications
- checkRotation() : void
- Check if file needs rotation and rotate if necessary
- ensureDirectoryExists() : void
- Ensure the directory exists for the log file
- generateSessionId() : string
- Generate a simple session ID
- interpolate() : string
- Enhanced interpolation with default values
- isLevelAllowed() : bool
- Check if level is allowed based on configuration
- isValidLevel() : bool
- Check if log level is valid
- rotateFile() : void
- Rotate the current log file
- writeLog() : void
- Write log entry to file with custom formatting support
- writeToFile() : void
- Write content to log file with rotation check
Constants
LEVELS
Log levels for validation
protected
mixed
LEVELS
= [
'EMERGENCY' => 800,
'ALERT' => 700,
'CRITICAL' => 600,
'ERROR' => 500,
'WARNING' => 400,
'NOTICE' => 300,
'SUCCESS' => 250,
// Custom level
'INFO' => 200,
'DEBUG' => 100,
'TRACE' => 50,
]
Properties
$allowedLevels
protected
array<string|int, mixed>
$allowedLevels
= []
$echoToStdout
protected
bool
$echoToStdout
= false
$file
protected
string
$file
$formatter
protected
callable|null
$formatter
= null
Custom log formatter function
$maxSize
protected
int
$maxSize
= 10485760
$sessionId
protected
string
$sessionId
= ''
$silence
protected
bool
$silence
= false
$useUtc
protected
bool
$useUtc
= true
Methods
__construct()
Create a new logger instance
public
__construct([string $file = '' ][, array<string|int, mixed> $config = [] ]) : mixed
Each Log instance is configured for a specific file and purpose. Use multiple instances with EventManager to achieve sophisticated routing behavior.
Configuration options:
- max_size: int - Max file size before rotation (default: 10MB)
- echo_to_stdout: bool - Echo logs to stdout (default: false)
- silence: bool - Suppress all logging (default: false)
- use_utc: bool - Use UTC timestamps (default: true)
- allowed_levels: array - Filter specific levels (default: all)
- session_id: string - Session identifier (default: auto-generate)
- formatter: callable - Custom log entry formatter
File "aliasing" achieved via EventManager with multiple Log instances. Different events can route to different files based on data content.
Parameters
- $file : string = ''
-
: string (required) - Log file path
- $config : array<string|int, mixed> = []
-
Configuration options array
Tags
alert()
Action must be taken immediately
public
alert(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
allowedLevels()
Get/Set allowed log levels
public
allowedLevels([array<string|int, mixed>|null $levels = null ]) : array<string|int, mixed>
Parameters
- $levels : array<string|int, mixed>|null = null
-
New levels array, or null to get current value
Return values
array<string|int, mixed> —Previous/current allowed levels
cleanupRotatedFiles()
Clean up old rotated log files
public
cleanupRotatedFiles([int $maxAge = 30 ]) : int
Parameters
- $maxAge : int = 30
-
Maximum age in days for rotated files
Return values
int —Number of files deleted
clearFormatter()
Clear custom formatter (use default)
public
clearFormatter() : self
Return values
self —For method chaining
compactFormatter()
Compact formatter - minimal output
public
static compactFormatter() : callable
Return values
callable —Compact formatter function
critical()
Critical conditions
public
critical(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
debug()
Debug-level messages
public
debug(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
detailedFormatter()
Detailed formatter - includes extra context
public
static detailedFormatter() : callable
Return values
callable —Detailed formatter function
echoToStdout()
Get/Set whether to echo logs to stdout
public
echoToStdout([bool|null $echo = null ]) : bool
Parameters
- $echo : bool|null = null
-
New echo setting, or null to get current value
Return values
bool —Previous/current echo setting
emergency()
System is unusable
public
emergency(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
error()
Error conditions
public
error(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
file()
Get current file path (read-only)
public
file() : string
Return values
string —Current log file path
formatter()
Get/Set custom formatter
public
formatter([callable|null $formatter = null ]) : callable|null
Parameters
- $formatter : callable|null = null
-
New formatter function, or null to get current
Return values
callable|null —Previous/current formatter (null = default format)
getConfig()
Get current configuration
public
getConfig() : array<string|int, mixed>
Return values
array<string|int, mixed> —Complete configuration array
getFileStats()
Get file statistics
public
getFileStats() : array<string|int, mixed>
Return values
array<string|int, mixed> —File statistics array
info()
Informational messages
public
info(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
jsonFormatter()
JSON formatter - outputs structured JSON logs
public
static jsonFormatter() : callable
Return values
callable —JSON formatter function
log()
Log with an arbitrary level
public
log(mixed $level, string $message[, array<string|int, mixed> $context = [] ]) : void
This is the main logging method that all other methods delegate to. Perfect for use in EventManager handlers where you receive structured data.
Enhanced interpolation supports placeholders with default values.
Parameters
- $level : mixed
-
Log level (string)
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
Tags
maxSize()
Get/Set maximum file size before rotation
public
maxSize([int|null $bytes = null ]) : int
Parameters
- $bytes : int|null = null
-
New max size in bytes, or null to get current value
Tags
Return values
int —Previous/current max size value
notice()
Normal but significant condition
public
notice(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
rotateNow()
Force log rotation now
public
rotateNow() : void
sessionId()
Get/Set session ID
public
sessionId([string|null $sessionId = null ]) : string
Parameters
- $sessionId : string|null = null
-
New session ID, or null to get current value
Return values
string —Previous/current session ID
silence()
Get/Set silence mode
public
silence([bool|null $silence = null ]) : bool
Parameters
- $silence : bool|null = null
-
New silence setting, or null to get current value
Return values
bool —Previous/current silence setting
success()
Success-level messages (Custom Level)
public
success(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
syslogFormatter()
Syslog-style formatter
public
static syslogFormatter() : callable
Return values
callable —Syslog formatter function
trace()
Trace-level messages (Custom Level)
public
trace(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
useUtc()
Get/Set UTC mode
public
useUtc([bool|null $useUtc = null ]) : bool
Parameters
- $useUtc : bool|null = null
-
New UTC setting, or null to get current value
Return values
bool —Previous/current UTC setting
warning()
Warning conditions
public
warning(string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string
-
Message with optional placeholders
- $context : array<string|int, mixed> = []
-
Context data for interpolation
webFormatter()
Custom web request formatter - great for web applications
public
static webFormatter() : callable
Return values
callable —Web formatter function
checkRotation()
Check if file needs rotation and rotate if necessary
protected
checkRotation() : void
ensureDirectoryExists()
Ensure the directory exists for the log file
protected
ensureDirectoryExists() : void
Tags
generateSessionId()
Generate a simple session ID
protected
generateSessionId() : string
Return values
string —Generated session ID
interpolate()
Enhanced interpolation with default values
protected
interpolate(string $message, array<string|int, mixed> $context) : string
This is an ENHANCED version that supports default values when context keys are missing.
Standard: placeholder format is 'User from ip' Enhanced: supports 'Status: unknown, User: 123' when status missing
Placeholders: Use curly braces with optional default after colon Complex data: Arrays and objects are JSON encoded automatically
Parameters
- $message : string
-
Message with placeholder or placeholder:default syntax
- $context : array<string|int, mixed>
-
Associative array of placeholder values
Return values
string —Interpolated message with placeholders replaced
isLevelAllowed()
Check if level is allowed based on configuration
protected
isLevelAllowed(string $level) : bool
Parameters
- $level : string
-
Level to check
Return values
bool —True if level is allowed
isValidLevel()
Check if log level is valid
protected
isValidLevel(string $level) : bool
Parameters
- $level : string
-
Level to check
Return values
bool —True if valid level
rotateFile()
Rotate the current log file
protected
rotateFile() : void
writeLog()
Write log entry to file with custom formatting support
protected
writeLog(string $level, string $message, array<string|int, mixed> $context) : void
This method handles the actual log writing, including custom formatter support, interpolation, and error handling.
Parameters
- $level : string
-
The log level (already validated)
- $message : string
-
The message to log
- $context : array<string|int, mixed>
-
Context data for interpolation
writeToFile()
Write content to log file with rotation check
protected
writeToFile(string $content) : void
Parameters
- $content : string
-
Content to write