XI. Logs

Treat logs as event streams

“A twelve-factor app never concerns itself with routing or storage of its output stream.” – 12factor.net

When to use

Always.

Why it matters

  • Flexibility: The app shouldn’t care if logs go to a file, to ELK, to Splunk, or to /dev/null.
  • Simplicity: No complex logging configuration inside the app.

Signs of Violation

  • App contains code to rotate log files.
  • App writes to /var/log/myapp.log directly.

Explanation

Problem

If the app manages log files, it fills up disks, requires write permissions, and locks you into a specific file structure.

Solution

Write to STDOUT (Standard Output) and STDERR. The environment (Docker, Systemd, Heroku) captures that stream and routes it to the final destination (File, CloudWatch, PaperTrail).

Real world analogy

A news reporter. They just speak into the microphone (Stream). They don’t worry about printing the newspaper or broadcasting the TV signal; the infrastructure handles valid routing.

Pros and Cons

Pros Cons
  • No disk management issues
  • Easy centralization
  • Mixing logs from multiple threads can be messy without identifiers
  • Comparison

    • Log Rotation: Not the app’s job.

    Code example

    Typescript

    Bad (Violation)

    Good (Adherence)

    PHP

    Bad (Violation)

    Good (Adherence)