Skip to content

API Reference

Muhammet Şafak edited this page May 24, 2026 · 1 revision

API Reference

Authoritative reference for every public class member shipped by initphp/logger. Method signatures are reproduced verbatim from the source; behavioural details correspond to the current main branch.

ClassNamespaceExtends / Implements
LoggerInitPHP\Logger\LoggerPsr\Log\AbstractLogger (final)
FileLoggerInitPHP\Logger\FileLoggerPsr\Log\AbstractLogger
PDOLoggerInitPHP\Logger\PDOLoggerPsr\Log\AbstractLogger
HelperTraitInitPHP\Logger\HelperTraittrait (@internal)

All three concrete classes implement Psr\Log\LoggerInterface transitively through AbstractLogger.


Logger

finalclass InitPHP\Logger\Logger extends \Psr\Log\AbstractLogger

Fan-out multiplexer. Forwards every PSR-3 call to every registered inner logger, in registration order. See Multi-Logger for the narrative documentation.

__construct

publicfunction __construct(\Psr\Log\LoggerInterface ...$loggers)

Parameters

NameTypeDescription
$loggersvariadic LoggerInterfaceOne or more PSR-3 loggers to dispatch to.

Throws

  • \InvalidArgumentException — when zero loggers are supplied.
  • \TypeError — when any argument is not a Psr\Log\LoggerInterface (raised by PHP at the call site).

Example

newLogger(
newFileLogger(['path' => '/var/log/app.log']),
newPDOLogger(['pdo' => $pdo, 'table' => 'logs']),
);

log

publicfunction log($level, string|\Stringable$message, array$context = []): void

Iterates the registered loggers and calls $inner->log($level, $message, $context) on each, in order. Exceptions raised by inner loggers are not caught and abort the rest of the fan-out.

Parameters

NameTypeDescription
$levelmixed (typically a Psr\Log\LogLevel constant)One of the eight PSR-3 levels.
$messagestring|\StringableLog message, optionally containing {placeholder} tokens.
$contextarray<string, mixed>Placeholder values. See Context Interpolation.

Throws

  • \Psr\Log\InvalidArgumentException — when an inner handler raises it for an unknown level.
  • Any exception thrown by an inner handler (e.g. \PDOException).

getLoggers

publicfunction getLoggers(): array

Returns the inner loggers in the order they were registered.

Returnslist<\Psr\Log\LoggerInterface>

Inherited helpers

From \Psr\Log\AbstractLogger, all eight delegate to log():

publicfunction emergency(string|\Stringable$message, array$context = []): void;
publicfunction alert (string|\Stringable$message, array$context = []): void;
publicfunction critical (string|\Stringable$message, array$context = []): void;
publicfunction error (string|\Stringable$message, array$context = []): void;
publicfunction warning (string|\Stringable$message, array$context = []): void;
publicfunction notice (string|\Stringable$message, array$context = []): void;
publicfunction info (string|\Stringable$message, array$context = []): void;
publicfunction debug (string|\Stringable$message, array$context = []): void;

FileLogger

class InitPHP\Logger\FileLogger extends \Psr\Log\AbstractLogger
{
use \InitPHP\Logger\HelperTrait;
}

Appends each record as a single line to a file. See FileLogger for the narrative documentation.

__construct

publicfunction __construct(array$options = [])

Parameters

NameTypeDescription
$optionsarray{path?: string}Configuration array. Only the path key is read.

Recognised options

KeyTypeRequiredDescription
pathstringyesDestination file path. May contain {year}, {month}, {day}, {hour}, {minute}, {second} tokens.

Throws

  • \InvalidArgumentException — when path is missing, not a string, or empty.

Example

newFileLogger(['path' => __DIR__ . '/logs/app-{year}-{month}-{day}.log']);

log

publicfunction log($level, string|\Stringable$message, array$context = []): void

Writes exactly one line of the form:

<ISO-8601 timestamp> [<UPPERCASE-LEVEL>] <interpolated message>\n

Parameters

NameTypeDescription
$levelmixed (typically a Psr\Log\LogLevel constant)One of the eight PSR-3 levels.
$messagestring|\StringableLog message with optional placeholders.
$contextarray<string, mixed>Placeholder values.

Throws

  • \Psr\Log\InvalidArgumentException — when $level is not a recognised PSR-3 level.

Failure modes (silent)

  • Failure to create the parent directory → error_log() notice, no exception.
  • Failure of file_put_contents()error_log() notice, no exception.

Concurrency: writes use FILE_APPEND | LOCK_EX.

getPath

publicfunction getPath(): string

Returns the destination file path after token interpolation.

Returnsstring

Example

$logger = newFileLogger(['path' => '/var/log/app-{year}.log']);
$logger->getPath(); // "/var/log/app-2026.log"

Properties

VisibilityNameTypeDescription
protected$pathstringToken-resolved destination path.

PDOLogger

class InitPHP\Logger\PDOLogger extends \Psr\Log\AbstractLogger
{
use \InitPHP\Logger\HelperTrait;
}

Inserts each record as a row in a relational table. See PDOLogger for the narrative documentation.

__construct

publicfunction __construct(array$options = [])

Parameters

NameTypeDescription
$optionsarray{pdo?: \PDO, table?: string}Configuration array.

Recognised options

KeyTypeRequiredDescription
pdo\PDOyesConfigured PDO connection.
tablestringyesDestination table name. Must match /^[A-Za-z_][A-Za-z0-9_]*$/.

Throws (all \InvalidArgumentException)

  • pdo key missing
  • pdo not a PDO instance
  • table key missing
  • table empty / not a string
  • table fails the identifier regex

The exact messages are listed in PDOLogger › Validation.

log

publicfunction log($level, string|\Stringable$message, array$context = []): void

Inserts one row:

INSERT INTO<table> (level, message, date) VALUES (?, ?, ?)

with level uppercased, message interpolated, date formatted as Y-m-d H:i:s at insertion time. Bound through prepared statements.

Throws

  • \Psr\Log\InvalidArgumentException — unknown level.
  • \PDOException — any database failure (connection lost, table missing, permission denied, …). Not swallowed; see Error Handling › Database failures.

getTable

publicfunction getTable(): string

Returns the configured destination table name.

Returnsstring

Properties

VisibilityNameTypeDescription
protected$pdo\PDOThe supplied PDO connection.
protected$tablestringValidated table name.

Class constants

VisibilityNameTypeValue
privateTABLE_NAME_PATTERNstring/^[A-Za-z_][A-Za-z0-9_]*$/

HelperTrait

trait InitPHP\Logger\HelperTrait

Note. Marked @internal. The trait is part of the implementation surface of the bundled handlers and may shift between patch releases. Reusing it in your own handlers is supported but at your own risk — there is no compatibility guarantee.

interpolate

protectedfunction interpolate(string|\Stringable$message, array$context = []): string

Expands {placeholder} tokens. Rendering rules:

Value typeRendered as
null""
true, false"true", "false"
int, float, string(string) $value
\Stringable(string) $value
\Throwable"<Class>(<code>): <message> in <file>:<line>"
arraysplaceholder left untouched
non-stringable objectsplaceholder left untouched

Non-string context keys are skipped. See Context Interpolation for examples.

Returnsstring

getDate

protectedfunction getDate(string$format = 'c'): string

Returns the current time formatted with DateTimeImmutable::format(). Defaults to ISO-8601 with offset ('c').

Returnsstring

logLevelVerify

protectedfunction logLevelVerify(mixed$level): void

Validates that $level is one of the eight PSR-3 level strings, comparing case-insensitively.

Throws\Psr\Log\InvalidArgumentException on failure.

PHPStan note. The trait carries a @phpstan-assert string $level annotation, so after calling logLevelVerify($level) static analysers know $level is a string.

Internal properties

VisibilityNameTypeDescription
private$levelslist<string>The eight canonical PSR-3 level strings, in severity order.

Exception types at a glance

Where?ExceptionWhen?
Logger::__construct\InvalidArgumentExceptionZero loggers.
Logger::__construct\TypeErrorNon-LoggerInterface argument (PHP-enforced).
FileLogger::__construct\InvalidArgumentExceptionpath missing / empty / non-string.
PDOLogger::__construct\InvalidArgumentExceptionpdo or table missing/wrong/invalid.
*Logger::log()\Psr\Log\InvalidArgumentExceptionUnknown level.
PDOLogger::log()\PDOExceptionBackend failure (propagated).
Logger::log()(inner exception verbatim)Inner handler raised.

Related

Clone this wiki locally