bg_image
header

PSR-3

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.

Key Points of PSR-3:

  1. 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().

  2. 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.

  3. 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.

  4. 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.

  5. 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.

Example Usage

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]);
        // ...
    }
}

Benefits of PSR-3:

  • Interoperability: You can switch between different logging libraries without changing your application’s code.
  • Consistency: Using PSR-3, developers follow a unified structure for logging, which simplifies code readability and maintainability.
  • Adaptability: With its flexible design, PSR-3 supports complex applications that may require different logging levels and log storage mechanisms.

For more details, you can check the official PHP-FIG documentation for PSR-3.

 

 


Created 7 Days 19 Hours ago
Applications Interface Method PHP PHP 7 PHP Standards Recommendation - PSR PSR-3 Principles Programming Source Code Software Strategies Web Development

Leave a Comment Cancel Reply
* Required Field