October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Logging with PSR-3: Make PHP Code More Reusable

PSR-3 lets reusable PHP code log through LoggerInterface without depending on a specific backend. Learn the contract, context conventions, injection pattern, and version checks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PSR-3 makes PHP code easier to reuse by letting it depend on a standard logger interface instead of a specific logging product. A library can accept PsrLogLoggerInterface, while the application chooses and configures the actual logger—such as Monolog—and its destinations. PSR-3 defines the contract, not a complete logging system or log destination.

How PSR-3 improves reusability

A reusable library often needs to report what it is doing or why an operation failed, but it should not dictate how an application stores or routes those messages. PHP-FIG describes PSR-3’s goal as allowing libraries to receive a PsrLogLoggerInterface and write to it “in a simple and universal way.” The PSR-3 specification defines that shared interface.

Without a common contract, a library may need to know a particular logger’s class, method names, or configuration. With PSR-3, the library calls the standard methods; the application can connect those calls to its chosen backend. That separation makes it possible to use the same library in different applications without coupling it to Monolog or another vendor’s logger.

What PSR-3 provides—and what it does not

The psr/log Composer package provides interfaces and related classes; it is not itself a logger. It does not, on its own, write to files, databases, or hosted services. The application must supply a compatible implementation and configure where records go. The php-fig/log README makes this distinction explicit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Monolog is one example of a PSR-3-compatible implementation. Its handlers can send records to destinations such as files, sockets, databases, and services. The standard and the implementation are separate choices: PSR-3 specifies how code talks to a logger, while a backend and its configuration determine what happens to each record. See the Monolog documentation.

Inject the logger into reusable code

Constructor injection makes the dependency visible and allows the application to provide the implementation when it assembles the program:

<?php

use PsrLogLoggerInterface;

final class Importer
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public function run(string $file): void
    {
        $this->logger->info('Import started for {file}', ['file' => $file]);

        try {
            // Import work goes here.
        } catch (Throwable $exception) {
            $this->logger->error('Import failed for {file}', [
                'file' => $file,
                'exception' => $exception,
            ]);
            throw $exception;
        }
    }
}

This shows the interface contract; the placeholder comment stands for the import operation. The reusable class does not construct or configure Monolog. The application’s composition or configuration code creates a compatible logger and passes it to Importer.

Use levels and context as the contract intends

Choose a standard level

PSR-3 defines eight level-specific methods: emergency, alert, critical, error, warning, notice, info, and debug. It also defines log($level, $message, $context) for callers that need to provide the level dynamically. Calling log with a standard level must have the same result as calling that level’s named method.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume arbitrary custom levels will work everywhere. If an implementation does not recognize a supplied level, the specification requires it to throw PsrLogInvalidArgumentException. Use standard levels for portable library behavior unless the application and selected implementation deliberately support an extension.

Keep messages stable; put changing values in context

Use a static message template and pass changing data in the context array. Placeholder names correspond to context keys:

$logger->info('User {userId} signed in', ['userId' => $userId]);

Keeping values out of the message string gives implementations the opportunity to format or encode context appropriately for their output. PHP-FIG’s PSR-3 meta document says implementations are responsible for escaping context displayed to users. Avoid inserting raw user-controlled values into a message before handing it to the logger.

Attach exceptions under the exception key

When a throwable should be logged with its stack trace, put it in the context entry named exception. In modern PHP, the relevant type is Throwable, which covers both Exception and Error. A logger or helper should validate that the context value is actually a Throwable before using it to obtain a trace; the key name alone does not prove the value’s type.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose helper classes only when they fit

PSR-3 includes more than the main interface. These supporting types are useful in particular integration patterns:

  • AbstractLogger and LoggerTrait help an implementation provide the level-specific methods by forwarding them to a common logging method.
  • NullLogger is a no-op fallback when code needs a logger object but no logging is configured.
  • LoggerAwareInterface and LoggerAwareTrait support setter-based integration for code that receives its logger after construction.
  • LogLevel provides constants for the standard level names.

These helpers do not change the central design choice: reusable code should rely on the contract, and application code should decide which implementation to supply.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check PHP and package compatibility before upgrading

Package constraints change over time, so check the exact releases and Composer constraints used by your project. At the time the package information was checked for this article, Packagist listed psr/log 3.0.2, published 2024-09-11, with a PHP requirement of >=8.0. Its release history includes 1.x, 2.x, and 3.x. See the psr/log Packagist page.

Packagist listed Monolog 3.12.0, published 2026-09-09, requiring PHP >=8.1 and psr/log ^2.0 or ^3.0. Monolog’s documentation says version 2.5 supports PHP 7.2 and later, while 1.25 supports PHP 5.3 through PHP 8.1 and is no longer maintained for PHP support fixes. These are release-specific facts, not permanent requirements; verify the target versions and project constraints before upgrading. See the Monolog package page and Monolog documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Select an implementation for the application, not the library

PSR-3 compatibility answers whether code can speak the common logging interface; it does not establish that every backend is equally suitable. When choosing one for an application, compare:

  • PHP and psr/log compatibility: confirm the backend’s version constraints fit the PHP version and other dependencies in the project.
  • Destinations and operations: check that its handlers and configuration support the required destinations, routing, and operational setup.
  • Framework integration: determine whether the framework or application already configures a compatible logger that can be injected.
  • Maintenance: check the support status of the specific release line you intend to use.

There is no universal best backend implied by PSR-3. The right one depends on the application’s compatibility, integration, destination, and maintenance requirements.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.