LoggerTrait uses \Psr\Log\LoggerAwareTrait
Provides PSR-3 logging capabilities to any class via {@see LoggerAwareTrait}.
This trait offers a complete set of logging methods corresponding to all PSR-3 log levels, along with utilities to initialize and configure a logger instance from various sources.
Key features:
- PSR-3 compliant logging methods: emergency(), alert(), critical(), error(), warning(), notice(), info(), debug(), and log().
- Constants LOGGER and LOGGABLE to standardize logger-related configuration keys.
- Initialization methods:
- initLoggable() to configure whether logging is enabled or disabled.
- initLogger() to set a logger instance directly, via an associative array, or by resolving a service from a PSR-11 container.
- Support for optional dependency injection container resolution, allowing the logger to be fetched from a DI container by service ID or class name.
Usage:
- Include this trait in a class to gain PSR-3 logging support without manually implementing LoggerInterface.
- Optionally, call initLogger() during construction or setup to bind the desired logger.
- Use loggable to control whether log calls should be performed.
Example:
use DI\Container;
use Psr\Log\LoggerInterface;
use oihana\logging\LoggerTrait;
class MyService
{
use LoggerTrait;
public function __construct( ?LoggerInterface $logger = null, ?Container $container = null )
{
$this->initLoggable(['loggable' => true]);
$this->initLogger($logger ?? ['logger' => 'my_logger_service'], $container);
}
public function run(): void
{
if ($this->loggable)
{
$this->info('Service started.');
try
{
// perform some action
} catch ( Throwable $e )
{
$this->error('An error occurred', ['exception' => $e]);
}
}
}
}
Tags
Table of Contents
Constants
- LOGGABLE = 'loggable'
- The 'loggable' parameter constant.
- LOGGER = 'logger'
- The 'logger' parameter constant.
Properties
- $loggable : bool
- The loggable flag.
Methods
- alert() : void
- Action must be taken immediately.
- critical() : void
- Critical conditions.
- debug() : void
- Detailed debug information.
- emergency() : void
- System is unusable.
- error() : void
- Runtime errors that do not require immediate action but should typically be logged and monitored.
- getLogger() : LoggerInterface|null
- Returns the logger reference.
- info() : void
- Interesting events.
- initializeLoggable() : static
- Initialize the loggable flag.
- initializeLogger() : static
- Initializes the logger reference for the current instance.
- log() : void
- Logs with an arbitrary level.
- notice() : void
- Normal but significant events.
- warning() : void
- Exceptional occurrences that are not errors.
Constants
LOGGABLE
The 'loggable' parameter constant.
public
mixed
LOGGABLE
= 'loggable'
LOGGER
The 'logger' parameter constant.
public
mixed
LOGGER
= 'logger'
Properties
$loggable
The loggable flag.
public
bool
$loggable
= false
Methods
alert()
Action must be taken immediately.
public
alert(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
critical()
Critical conditions.
public
critical(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Example: Application component unavailable, unexpected exception.
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
debug()
Detailed debug information.
public
debug(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
emergency()
System is unusable.
public
emergency(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
error()
Runtime errors that do not require immediate action but should typically be logged and monitored.
public
error(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
getLogger()
Returns the logger reference.
public
getLogger() : LoggerInterface|null
Return values
LoggerInterface|nullinfo()
Interesting events.
public
info(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Example: User logs in, SQL logs.
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
initializeLoggable()
Initialize the loggable flag.
public
initializeLoggable([bool|array<string|int, mixed>|null $init = null ][, ContainerInterface|null $container = null ][, bool|array<string|int, mixed>|null $defaultValue = false ]) : static
Parameters
- $init : bool|array<string|int, mixed>|null = null
-
The definition to initialize the loggable property.
- $container : ContainerInterface|null = null
- $defaultValue : bool|array<string|int, mixed>|null = false
-
The default value if the $init argument is not defined.
Tags
Return values
staticinitializeLogger()
Initializes the logger reference for the current instance.
public
initializeLogger([array<string|int, mixed>|LoggerInterface|string|null $init = null ][, ContainerInterface|null $container = null ][, bool $useDefault = true ]) : static
This method accepts either:
- A LoggerInterface instance
- An associative array containing a logger reference under the static::LOGGER key
- A string representing a service ID or class name resolvable by the container
null
or an empty value, which will default to LoggerInterface::class depending on the$useDefault
parameter.
If a dependency injection container is provided, the method will attempt to
resolve the logger service from it. If no valid logger can be resolved, the
$this->logger
property will be set to null
.
Parameters
- $init : array<string|int, mixed>|LoggerInterface|string|null = null
-
Logger initialization data. May be an instance, an array with a logger entry, a string service ID/class name, or
null
. - $container : ContainerInterface|null = null
-
Optional dependency injection container used to resolve the logger service.
- $useDefault : bool = true
-
Whether to use LoggerInterface::class as a fallback if
$init
does not provide a valid logger string. Defaults totrue
.
Tags
Return values
static —Returns the current instance for method chaining.
log()
Logs with an arbitrary level.
public
log(mixed $level, string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $level : mixed
- $message : string|Stringable
- $context : array<string|int, mixed> = []
notice()
Normal but significant events.
public
notice(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []
warning()
Exceptional occurrences that are not errors.
public
warning(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
Parameters
- $message : string|Stringable
- $context : array<string|int, mixed> = []