PSR Log

repository·master·Indexed 27 days ago

https://github.com/php-fig/log

Standard interfaces for logging in PHP based on the PSR-3 specification. It provides the LoggerInterface for interchangeable logging implementations, LogLevel constants for RFC 5424, and a NullLogger no-op implementation.

Tokens
721
Snippets
3
Records
7
Agent score
93%

What's inside psr/log

  1. Implement LoggerInterface

    master
    To create your own logger that is compatible with the PHP ecosystem, implement the Psr\Log\LoggerInterface. You should refer to the official PSR-3 specification for the required method signatures and behavior.
  2. Use LoggerInterface for dependency injection

    master

    To make your classes compatible with any PSR-3 compliant logger, type-hint the Psr\Log\LoggerInterface in your constructor. This allows you to inject any logger implementation (such as Monolog) into your class.

    <?php
    
    use Psr\/Log\/LoggerInterface;
    
    class Foo
    {
        private $logger;
    
        public function __construct(LoggerInterface $logger = null)
        {
            $this->logger = $logger;
        }
    
        public function doSomething()
        {
            if ($this->logger) {
                $this->logger->info('Doing work');
            }
               
            try {
                $this->doSomethingElse();
            } catch (Exception $exception) {
                $this->logger->error('Oh no!', array('exception' => $exception));
            }
    
            // do something useful
        }
    }
  3. Use NullLogger to avoid conditional logging checks

    master
    The NullLogger class is a no-op implementation of the LoggerInterface. It is useful for providing a default logger to libraries or components so that you can call logging methods without checking if a logger instance exists (e.g., avoiding if ($this->logger) { ... } blocks).
  4. Use LogLevel constants for RFC 5424 log levels

    master
    The Psr\Log\LogLevel class provides a set of constants representing the standard RFC 5424 log levels. Use these constants instead of raw strings when calling logging methods to ensure compatibility with the PSR-3 standard.
  5. Catch Psr\Log\InvalidArgumentException

    master
    When using a PSR-3 compliant logger, an InvalidArgumentException may be thrown if an invalid argument is passed to a logging method (for example, if the context array contains non-scalar values or nested objects that the implementation cannot handle). You can catch this specific exception to handle logging errors gracefully.
  6. Implement log() in NullLogger

    master

    The NullLogger::log() method accepts an arbitrary log level, a message (string or stringable), and an optional context array. It performs no action (noop).

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