PSR-3 is a PHP-FIG (PHP Framework Interoperability Group) recommendation that establishes a standardized interface for logging libraries in PHP applications. This interface defines methods and rules that allow developers to work with logs consistently across different frameworks and libraries, making it easier to replace or change logging libraries within a project without changing the codebase that calls the logger.
Standardized Logger Interface: PSR-3 defines a Psr\Log\LoggerInterface
with a set of methods corresponding to different log levels, such as emergency()
, alert()
, critical()
, error()
, warning()
, notice()
, info()
, and debug()
.
Log Levels: The standard specifies eight log levels (emergency, alert, critical, error, warning, notice, info, and debug), which follow an escalating level of severity. These are based on the widely used RFC 5424 Syslog protocol, ensuring compatibility with many logging systems.
Message Interpolation: PSR-3 includes a basic formatting mechanism known as message interpolation, where placeholders (like {placeholder}
) within log messages are replaced with actual values. For instance:$logger->error("User {username} not found", ['username' => 'johndoe']);
This allows for consistent, readable logs without requiring complex string manipulation.
Flexible Implementation: Any logging library that implements LoggerInterface
can be used in PSR-3 compatible code, such as Monolog, which is widely used in the PHP ecosystem.
Error Handling: PSR-3 also allows the log()
method to be used to log at any severity level dynamically, by passing the severity level as a parameter.
Here’s a basic example of how a PSR-3 compliant logger might be used:
use Psr\Log\LoggerInterface;
class UserService
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function findUser($username)
{
$this->logger->info("Searching for user {username}", ['username' => $username]);
// ...
}
}
For more details, you can check the official PHP-FIG documentation for PSR-3.