Track Drupal error rates with the logger
To use Drupal’s logger to track error rates in production, treat logging as a measurement system rather than a list of technical messages. Drupal’s PSR-3 logger can record a channel, severity, message and structured context, but a useful rate also needs consistent event definitions, request counts and an accurate clock. The result should tell an on-call developer whether a deployment is harming customers, not merely whether the server has produced an error.
Start with a small set of tracked operations, such as authentication, checkout, scheduled imports or third-party API requests. Establish what counts as an error, where the record will be stored and who will respond to an alert. This prevents every exception, warning and validation message from being treated as an equal failure.
Separate channels and severity levels
Drupal channels divide log records by the component or feature responsible for them. Core uses channels such as php, watchdog and cron, while a custom Drupal module can use a channel such as my_module. The available PSR-3 levels run from emergency and critical through error, warning, notice, info and debug. Tracking these separately makes it possible to count genuine failures without allowing deprecation notices or expected warnings to distort the rate.
An injectable service can obtain a dedicated channel through LoggerChannelFactoryInterface. This approach is easier to test than calling \Drupal::logger() throughout the codebase:
$logger = $this->loggerFactory->get('my_module');
$logger->error(
'The @operation operation failed',
[
'operation' => $operation,
'exception' => $exception,
]
);
Register the service in the module’s services.yml file and inject it into the class that performs the operation:
services:
my_module.error_tracker:
class: Drupal\my_module\ErrorTracker
arguments:
- '@logger.factory'
Keep the channel stable over time. Renaming it can break dashboards, alert rules and historical comparisons. Use separate channels for different operational responsibilities if that improves ownership, but avoid creating a channel for every route or entity type, as excessive fragmentation makes aggregation harder.
Turn exceptions into countable events
Drupal can log uncaught exceptions, but application code often catches an exception to recover, retry or present a useful message. Those handled failures still need explicit logging. Record the operation, stable event identifier, exception class and relevant business context at the point where the failure is detected:
try {
$result = $this->invoiceClient->send($invoice);
}
catch (\Throwable $exception) {
$this->tracker->logFailure('invoice_sync', $exception);
throw $exception;
}
Use a consistent event identifier such as invoice_sync_failed rather than writing a different message for every occurrence. The identifier allows the monitoring system to group similar failures and prevents one incident from appearing as hundreds of unrelated errors. If a lower layer and Drupal’s exception handler both record the same failure, use the event identifier to deduplicate it.
Context should help an engineer reproduce and classify the problem. A route name, operation name, exception class, deployment identifier and correlation ID are usually more valuable than a long prose message. Drupal’s core Media oEmbed workflow illustrates a feature that can depend on an external provider. Drupalwoo’s guide to embedding external videos explains that path, while custom instrumentation can record the provider, HTTP status and media entity ID when an embed fails.
Never place passwords, access tokens, session values, authorisation headers or complete request bodies in the context array. Personal information and commercially sensitive payloads should be redacted or omitted. The exception itself may contain sensitive values in its message, so review how the chosen formatter renders exceptions before enabling the handler.
Configure durable production log output
Drupal’s Database Logging module, or dblog, is useful during development and on modest sites, but a busy production database can accumulate substantial write volume and retention overhead. It can also make the database unavailable when the logging table grows too large. For production monitoring, send Drupal records to a file, the system journal or a dedicated log collector while keeping only a short operational history in Drupal itself.
The Monolog module can route channels to different handlers. A representative exported configuration for a JSON log file might look like this:
monolog.settings:
handlers:
production_file:
type: stream
path: '/var/log/drupal/production.json'
level: error
channels: '!deprecation'
formatter: monolog.formatter.json
The handler should run at error level when measuring failed operations, while another handler can retain warnings and notices for investigation. The file path must be writable by the PHP or container process but outside the public web root. Configure rotation or forward the stream to a collector so a disk-full incident does not become the next outage.
Many Australian managed Drupal and VPS providers offer infrastructure in Sydney or Melbourne. Confirm where each collector and backup is located rather than assuming that an Australian support contract guarantees Australian data residency. If the hosting platform prevents direct file writes, use its supported system-journal integration or ship Monolog output through the provider’s logging agent. Also verify that PHP, web-server and database errors enter the same correlation workflow.
Calculate meaningful error rates
A raw count of error messages is not an error rate. Calculate the ratio against the number of requests that could produce those errors:
error rate = tracked error events ÷ matching requests × 1,000
Drupal’s logger supplies the numerator, but it does not automatically supply a reliable request denominator. Count requests in the reverse proxy or web-server access log, or add a lightweight request counter in Drupal. Exclude health checks, static assets and administrative probes when they are not part of the tracked operation. Background jobs and command-line tasks should have their own denominator because one scheduled run is not equivalent to one customer request.
Use fixed windows such as five minutes for immediate detection and hourly or daily periods for trends. Compare each window with the same operating period rather than with an arbitrary average. A threshold of one percent can be severe during a quiet period and insignificant during a busy one, so display the error rate beside request volume, absolute error count and latency.
Store timestamps in UTC while displaying them in Australian Eastern Time where operationally useful. Sydney and Melbourne change between AEST and AEDT, while Brisbane and Perth do not use daylight saving. A dashboard grouped by the local clock can therefore show a duplicated hour in autumn or a missing hour in spring. UTC windows remain stable and make comparisons between Australian and overseas support teams reliable.
Alert on customer impact
Alerts should describe customer impact rather than the internal severity chosen in code. A critical event affecting authentication or payment may deserve immediate paging, while a sustained error ratio on one integration can go to a ticket queue. Combine a relative threshold with an absolute count so the rule works during both low and high traffic. For example, a rule can trigger when the error ratio remains above one percent for five minutes and the volume exceeds twenty events.
Create one alert per incident rather than sending a message for every affected request. Group records by event identifier, operation and exception class, then attach a count, first-seen time, latest deployment and a link to the relevant dashboard. This reduces alert fatigue during an outage and gives the responder a concise starting point.
Log retention and access must account for the Privacy Act 1988 and the Australian Privacy Principles when records contain identifiers, IP addresses or customer-related information. Apply data minimisation, restrict access, define a deletion period and pseudonymise identifiers where practical. Security logging guidance from the Australian Cyber Security Centre can help with monitoring controls, but it does not remove the need to comply with the organisation’s privacy obligations.
Seasonal workloads also affect suitable thresholds. Australian businesses may experience heavier transactional traffic during June end-of-financial-year processing or the Christmas retail period. Baseline those periods separately so a predictable batch failure is not hidden by higher traffic, and so normal seasonal load does not create a permanent stream of false alerts.
Reproduce failures in a safe environment
A production error is easier to investigate when the corresponding release, configuration and data shape are available in staging. Create a sanitised dataset that preserves the relationships involved without copying unnecessary customer details. Confirm that the staging environment uses the same PHP version, Drupal core version, contributed modules and deployment configuration as the affected release.
Storage-related failures are often missed when development machines use local disks with different latency and capacity. IT Diversified’s home-lab SAN build demonstrates how FreeNAS and iSCSI can sit behind virtual machines. Such a lab can help reproduce slow storage, interrupted writes or exhausted volumes, although consumer hardware and a home network should not replace production monitoring or capacity controls.
Reproduce faults in a controlled sequence: capture the release identifier, apply one relevant change, record the resulting error rate and compare it with the baseline. Test conditions such as a full database volume, an unavailable API provider, a read-only filesystem or an expired credential. Avoid manual testing against live payment, authentication or messaging systems unless the owner has approved a dedicated test account and a rollback procedure.
Keep the investigation artefact-focused. A sanitised log record, correlation ID and deployment hash are often more useful than a screenshot containing a session identifier or customer address. Record which checks were performed and whether the original failure was reproduced, then link those findings to the incident rather than leaving them in temporary chat messages.
Maintain the logging workflow
A production dashboard should show the error ratio, absolute event count and request volume over time. Break the results down by event identifier, operation, route, exception class, release and channel. Include latency and deployment markers so an increase can be compared with a release or infrastructure change. Dashboards designed for a Drupal agency in Melbourne or a Sydney operations team should use UTC internally and make the selected display time zone explicit.
Manage logging configuration as code. Export the active Monolog and logging settings, review changes, and deploy them through the same configuration workflow used for code. Keep sample log payloads in documentation, but ensure they contain no real credentials or personal information. Version changes to event identifiers and severity rules because a silent rename can break historical comparisons.
Review the resulting metrics regularly to confirm that alerts reach the intended on-call rotation, thresholds reflect actual traffic and retained data matches the organisation’s policy. Record ownership for each monitored integration and ensure obsolete channels are retired deliberately. A disciplined logger turns production exceptions into comparable evidence, allowing the team to detect deterioration, connect failures to releases and restore service with less ambiguity.