Overview
Logs help explain what happened in an application, but unstructured or excessive logs can be difficult to search and may expose sensitive data. Define a consistent logging approach before the application grows.
Use meaningful levels
Use debug for development diagnostics, info for significant normal events, notice or warning for unusual but recoverable conditions, error for failed operations and critical levels for serious service failures. Avoid logging every successful low-value operation at warning level.
Add useful context
Include a timestamp, severity, environment, request or job identifier and a stable event name. Structured JSON logs are easier for centralized systems to parse. Keep context concise and avoid embedding entire request bodies.
Protect sensitive information
Never log passwords, session identifiers, authorization headers, API tokens or full payment data. Mask or omit personal information unless there is a documented operational need and appropriate access controls. Restrict log permissions and define retention periods.
Correlate requests and background work
Generate a request ID at the edge and include it in application logs and error responses where appropriate. Pass a job ID into background tasks so related events can be traced without relying on timestamps alone.
Official references
PSR-3 Logger Interface Monolog documentation
Use levels and structured context
Choose consistent levels such as debug, info, warning, error and critical. Include useful context such as a request ID, operation name and safe entity identifier. Structured logs are easier to search than long free-form messages.
Protect sensitive information
Never log passwords, session identifiers, access tokens, private keys or full payment details. Mask or omit personal data unless there is a documented operational need and an appropriate retention policy. Treat logs as sensitive production data and restrict access.
Centralize logging
Use a maintained PSR-3-compatible logger where it fits the project, or a small adapter that keeps application code independent of a specific destination. Write logs outside the public web root and configure rotation, retention and disk-space monitoring.
Make incidents diagnosable
Record the event, timestamp, severity, request correlation ID and relevant component. Avoid logging the same exception repeatedly at every layer. Log it once at the boundary that can handle or report it, while preserving exception chaining for diagnosis.