Oihana PHP System

Logger implements LoggerInterface uses LoggerTrait, ToStringTrait

A simple PSR-3-compliant file-based logger.

This Logger implementation provides support for logging messages to individual daily log files, categorized by severity level. It supports dynamic message interpolation with context values, and includes hooks for global error and exception handling.

Example usage:

use oihana\logging\Logger;

$logger = new Logger(__DIR__ . '/logs', Logger::DEBUG);

$logger->info('Application started');
$logger->error('An error occurred: {error}', ['error' => $exception->getMessage()]);

Features:

  • Supports standard PSR-3 log levels (emergency to debug)
  • Writes logs to a file named by date (e.g., log_2025-06-17.log)
  • Automatically creates the logging directory if it doesn’t exist
  • Includes a message buffer for introspection
  • Provides optional methods for clearing logs and capturing global errors

Notes:

  • This logger is not asynchronous or thread-safe.
  • Make sure the log directory is writable by the PHP process.

Table of Contents

Interfaces

LoggerInterface

Constants

ALERT  = 1
CRITICAL  = 2
DEBUG  = 7
EMERGENCY  = 0
Error severity, from low to high. From BSD syslog RFC, section 4.1.1
ERROR  = 3
ERROR_DIR_WRITE_FAILED  = 'dir:write:failed'
ERROR_FILE_OPEN_FAILED  = 'fil:open:failed'
ERROR_FILE_OPEN_SUCCESS  = 'fil:open:success'
ERROR_FILE_PERMISSION_FAILED  = 'fil:permission:failed'
ERROR_FILE_WRITE_FAILED  = 'fil:write:failed'
INFO  = 6
LEVELS  = [\Psr\Log\LogLevel::EMERGENCY => self::EMERGENCY, \Psr\Log\LogLevel::ALERT => self::ALERT, \Psr\Log\LogLevel::CRITICAL => self::CRITICAL, \Psr\Log\LogLevel::ERROR => self::ERROR, \Psr\Log\LogLevel::WARNING => self::WARNING, \Psr\Log\LogLevel::NOTICE => self::NOTICE, \Psr\Log\LogLevel::INFO => self::INFO, \Psr\Log\LogLevel::DEBUG => self::DEBUG]
NOTICE  = 5
OFF  = 8
STATUS_LOG_CLOSED  = 3
STATUS_LOG_OPEN  = 1
Internal status codes
STATUS_OPEN_FAILED  = 2
WARNING  = 4

Properties

$extension  : string
$fileDateFormat  : string
$prefix  : string
$_dateFormat  : string
Valid PHP date() format string for log timestamps
$_defaultPermissions  : int
Octal notation for default permissions of the log file
$_defaultSeverity  : int
Default severity of log messages, if not specified
$_file  : resource
This holds the file handle for this instance's log file
$buffer  : array<string|int, mixed>
Holds messages generated by the class
$directory  : string
The directory to the log file
$errors  : array<string|int, mixed>
Standard messages produced by the class. Can be modified for il8n
$path  : string|null
Path to the log file
$severityThreshold  : int
Current minimum logging threshold
$status  : int
Current status of the log file

Methods

__construct()  : void
Creates a new Logger instance.
__destruct()  : void
Destruct the instance.
__toString()  : string
Returns a String representation of the object.
clear()  : void
Clear all logs in the log path.
createPath()  : string
Creates the log file path with a specific name.
getDirectory()  : string
Returns the directory of the logs files.
getErrors()  : array<string|int, mixed>
Returns the entire message queue (leaving it intact)
getLogFiles()  : array<string|int, mixed>
Returns the list of all log files in the logger directory.
getMessage()  : string
Returns (and removes) the last message from the queue buffer.
getPath()  : string
Returns the path of the logs files.
getStatus()  : int
Indicates the status of the logger instance.
log()  : void
Writes a message to the log with the given severity.
onError()  : true
Invoked when a global error is sending.
onException()  : true
Invoked when a global exception is sending.
writeFreeFormLine()  : void
Writes a line to the log without prepending a status or timestamp.
getErrorMessage()  : string
Returns an error message with a specific error status.

Constants

CRITICAL

public mixed CRITICAL = 2

ERROR_DIR_WRITE_FAILED

public mixed ERROR_DIR_WRITE_FAILED = 'dir:write:failed'

ERROR_FILE_OPEN_FAILED

public mixed ERROR_FILE_OPEN_FAILED = 'fil:open:failed'

ERROR_FILE_OPEN_SUCCESS

public mixed ERROR_FILE_OPEN_SUCCESS = 'fil:open:success'

ERROR_FILE_PERMISSION_FAILED

public mixed ERROR_FILE_PERMISSION_FAILED = 'fil:permission:failed'

ERROR_FILE_WRITE_FAILED

public mixed ERROR_FILE_WRITE_FAILED = 'fil:write:failed'

LEVELS

public array<string|int, mixed> LEVELS = [\Psr\Log\LogLevel::EMERGENCY => self::EMERGENCY, \Psr\Log\LogLevel::ALERT => self::ALERT, \Psr\Log\LogLevel::CRITICAL => self::CRITICAL, \Psr\Log\LogLevel::ERROR => self::ERROR, \Psr\Log\LogLevel::WARNING => self::WARNING, \Psr\Log\LogLevel::NOTICE => self::NOTICE, \Psr\Log\LogLevel::INFO => self::INFO, \Psr\Log\LogLevel::DEBUG => self::DEBUG]

STATUS_LOG_CLOSED

public mixed STATUS_LOG_CLOSED = 3

STATUS_LOG_OPEN

Internal status codes

public mixed STATUS_LOG_OPEN = 1

STATUS_OPEN_FAILED

public mixed STATUS_OPEN_FAILED = 2

WARNING

public mixed WARNING = 4

Properties

$extension

public string $extension = '.log'

$fileDateFormat

public string $fileDateFormat = 'Y-m-d'

$prefix

public string $prefix = 'log_'

$_dateFormat

Valid PHP date() format string for log timestamps

private static string $_dateFormat = 'Y-m-d H:i:s'

$_defaultPermissions

Octal notation for default permissions of the log file

private static int $_defaultPermissions = 0775

$_defaultSeverity

Default severity of log messages, if not specified

private static int $_defaultSeverity = self::DEBUG

$_file

This holds the file handle for this instance's log file

private resource $_file = null

$buffer

Holds messages generated by the class

private array<string|int, mixed> $buffer = []

$directory

The directory to the log file

private string $directory

$errors

Standard messages produced by the class. Can be modified for il8n

private array<string|int, mixed> $errors = [self::ERROR_DIR_WRITE_FAILED => 'Failed to create log directory: {0}', self::ERROR_FILE_OPEN_SUCCESS => 'The log file was opened successfully.', self::ERROR_FILE_OPEN_FAILED => 'The file could not be opened. Check permissions.', self::ERROR_FILE_PERMISSION_FAILED => 'Failed to set correct permissions (0664) on log file {0} {1}.', self::ERROR_FILE_WRITE_FAILED => 'The file {0} could not be written to. Failed to change permissions for existing file, check that appropriate permissions have been set.']

$path

Path to the log file

private string|null $path = null

$severityThreshold

Current minimum logging threshold

private int $severityThreshold = self::DEBUG

$status

Current status of the log file

private int $status = self::STATUS_LOG_CLOSED

Methods

__construct()

Creates a new Logger instance.

public __construct(string $directory[, int $level = 7 ]) : void
Parameters
$directory : string

File path to the logging directory

$level : int = 7

One of the pre-defined level constants

__destruct()

Destruct the instance.

public __destruct() : void

__toString()

Returns a String representation of the object.

public __toString() : string
Tags
throws
ReflectionException
Return values
string

A string representation of the object.

clear()

Clear all logs in the log path.

public clear() : void

createPath()

Creates the log file path with a specific name.

public createPath(string $name) : string
Parameters
$name : string
Return values
string

getDirectory()

Returns the directory of the logs files.

public getDirectory() : string
Return values
string

getErrors()

Returns the entire message queue (leaving it intact)

public getErrors() : array<string|int, mixed>
Return values
array<string|int, mixed>

getLogFiles()

Returns the list of all log files in the logger directory.

public getLogFiles() : array<string|int, mixed>
Return values
array<string|int, mixed>

getMessage()

Returns (and removes) the last message from the queue buffer.

public getMessage() : string
Return values
string

getPath()

Returns the path of the logs files.

public getPath() : string
Return values
string

getStatus()

Indicates the status of the logger instance.

public getStatus() : int
Return values
int

log()

Writes a message to the log with the given severity.

public log(int $level, string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$level : int

Severity level of log message (use constants)

$message : string|Stringable

Text to add to the log

$context : array<string|int, mixed> = []

onError()

Invoked when a global error is sending.

public onError(string|int $code, string $message, string|int $file, string|int $line[, string $pattern = '[%s] - L:%s - C:%s - %s' ]) : true
Parameters
$code : string|int
$message : string
$file : string|int
$line : string|int
$pattern : string = '[%s] - L:%s - C:%s - %s'
Return values
true

onException()

Invoked when a global exception is sending.

public onException(Throwable $exception) : true
Parameters
$exception : Throwable
Return values
true

writeFreeFormLine()

Writes a line to the log without prepending a status or timestamp.

public writeFreeFormLine(string $line) : void
Parameters
$line : string

Line to write to the log

getErrorMessage()

Returns an error message with a specific error status.

protected getErrorMessage(string $errorStatus, mixed ...$args) : string
Parameters
$errorStatus : string
$args : mixed
Return values
string

        
On this page

Search results