Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 147 ยท Advanced PHP

Logging with PSR-3

Learn PHP logging with the PSR-3 interface - log levels, context placeholders, writing your own logger with handlers, and rotating log files by size.

When something goes wrong on a production server, you cannot attach a debugger and you cannot var_dump to the screen. What you have is whatever your application wrote down at the time. Logging is how code leaves a trail: "payment 4711 failed", "cache miss", "user 12 logged in". Good logs make an outage a ten-minute puzzle; missing logs make it a night of guessing.

PHP has a shared standard for the logging interface, PSR-3. Libraries such as Monolog, and the loggers inside Laravel and Symfony, all implement it, so your code can say "I need a logger" without caring where messages end up. In this lesson you will learn the eight levels, how to use context data properly, and how to write a small PSR-3 style logger with handlers and size-based file rotation. It continues from errors and exceptions, and the logger is a perfect thing to hand in with dependency injection.

The PSR-3 interface

The core is one interface with a method per level, plus the generic log():

PHP
interface LoggerInterface
{
    public function emergency(string|Stringable $message, array $context = []): void;
    public function alert(string|Stringable $message, array $context = []): void;
    public function critical(string|Stringable $message, array $context = []): void;
    public function error(string|Stringable $message, array $context = []): void;
    public function warning(string|Stringable $message, array $context = []): void;
    public function notice(string|Stringable $message, array $context = []): void;
    public function info(string|Stringable $message, array $context = []): void;
    public function debug(string|Stringable $message, array $context = []): void;
    public function log($level, string|Stringable $message, array $context = []): void;
}

The real package is psr/log; installing it with Composer (autoloading and Composer) gives you Psr\Log\LoggerInterface and an AbstractLogger helper. The runnable examples below define the same shape locally.

The eight levels

From most to least severe, they follow the old syslog scale:

Level Use it for
emergency The system is unusable
alert Act immediately (database down, disk full)
critical A key component is unavailable
error A runtime failure that needs attention but the app continues
warning Something unexpected, not an error (deprecated call, retry used)
notice Normal but significant events
info Business milestones: user registered, order placed
debug Detailed data for developers

A good rule: production logs at info or warning and above; you turn on debug temporarily. Most real code uses only debug, info, warning, error and critical. Don't log an expected "user typed a wrong password" as error; that drowns real problems.

Context and placeholders

Never build log messages by gluing values into strings. PSR-3 passes data in the context array, and a message may refer to context keys with . The logger interpolates them, and structured handlers (JSON logs) can keep the data separate for searching.

PHP A PSR-3 style logger with placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notes: the message text stays constant ("User {id} signed in...") so log tools can group similar lines; only the context changes. PSR-3 reserves the key exception for a Throwable, so handlers can print a stack trace.

Also notice what not to log: passwords, tokens, full card numbers, session ids. Logs are copied to many places and kept for months. See security basics.

Handlers: where messages go

A bare logger formats; a handler writes the line somewhere: a file, stderr, a syslog, a Slack channel. Monolog calls this design a channel with a stack of handlers. You can build the same idea in a few lines. The point is that the code using the logger never changes when you change destinations.

flowchart LR
    A["Your code<br/>$logger->error(...)"] --> L["Logger<br/>(level filter, interpolation)"]
    L --> H1["Stream handler<br/>stderr"]
    L --> H2["Rotating file handler<br/>app.log"]
    L --> H3["Alert handler<br/>critical only"]

One log call, several destinations, each with its own minimum level.

PHP Handlers with their own thresholds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Rotating log files

A log file that grows forever eventually fills the disk. Rotation starts a new file when the current one gets too big (or when the day changes) and keeps only a few old ones. On Linux servers logrotate often does this from outside; inside PHP you can do it yourself. Here is a size-based rotating handler that keeps app.log, app.log.1, app.log.2:

PHP Size-based log rotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each file holds up to two lines (40 bytes), the newest lines are in app.log, and anything older than app.log.2 was deleted. LOCK_EX stops two PHP processes from interleaving a line, which matters on busy sites. See file handling for the underlying functions. In production, prefer a tested library (Monolog's RotatingFileHandler) or write to stderr and let the platform collect logs.

Practical advice

  • Log at boundaries: incoming requests, outgoing calls to other services, job starts and failures, and every caught exception you swallow.
  • Add a request id to the context of every line so you can follow one request through many lines.
  • Log once. Catching an exception, logging it, and rethrowing means the same error is logged at every layer.
  • Don't let logging break the app. A full disk should not become a 500 error.
  • Use JSON lines in production if you use a log service; the context stays searchable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does PSR-3 use a context array with {placeholders} instead of building the message with string concatenation?

    A fixed message template makes similar events easy to group and search, while the context carries the varying values, which handlers can store as structured data.
  2. 2. Which of these is the most severe PSR-3 level?

    From least to most severe the order is debug, info, notice, warning, error, critical, alert, emergency.
  3. 3. A logger is configured with a minimum level of warning. What happens to an info message?

    Messages below the threshold are dropped, which is how you keep production logs quiet and enable debug only when needed.
  4. 4. What problem does log rotation solve?

    Rotation starts a new file when the old one reaches a size or age limit and deletes the oldest ones.

Summary

  • PSR-3 gives every logger the same interface: eight level methods and log(), each taking a message and a context array.
  • Use levels deliberately; production usually keeps info/warning and above.
  • Put variable data in the context and refer to it with ; the key exception is for a Throwable.
  • Handlers decide where lines go and can have their own minimum level.
  • Rotate files by size or date, never log secrets, and log each problem once.

Next: Caching in PHP