How to Log Errors Cleanly in Drupal 10 and 11 with LoggerChannelFactoryInterface
When debugging a custom Drupal integration or background queue worker, it is tempting to drop in \Drupal::logger('debug')->notice(print_r($data, TRUE)) and move on. In production, though, unformatted print_r() dumps, string-concatenated variables, and static \Drupal::logger() calls clutter dblog / syslog, make unit testing painful, and risk writing sensitive API tokens or customer emails straight into plain-text logs. Injecting LoggerChannelFactoryInterface with structured PSR-3 placeholders keeps your Drupal logs clean, searchable, and safe.
Editorial illustration: inject LoggerChannelFactoryInterface, select a dedicated channel, and use @placeholder context arrays.
Summary
- Per Drupal API’s
LoggerChannelFactoryInterface, inject@logger.factory(LoggerChannelFactoryInterface) or a dedicated channel service (@logger.channel.<name>) into custom Drupal 10 and 11 classes rather than calling\Drupal::logger()statically. - Use PSR-3 severity methods (
error(),warning(),notice(),info(),debug()) with placeholders (@id,%name) in the$contextarray instead of string concatenation so Drupal escapes values properly and log backends can index fields. - Never log passwords, bearer tokens, SAML assertions, or full HTTP authorization headers into watchdog/
dblogtables. - Combine clean logging with
drush ws(watchdog:show) and separatesyslogor centralized log shipping in high-traffic production sites instead of leaving verbosedblogenabled everywhere.
Injecting a dedicated logger channel cleanly
In a custom service (my_module.services.yml), you can either inject logger.factory directly or define a dedicated channel service (which uses LoggerChannelFactoryInterface::get('my_module') under the hood):
<?php
declare(strict_types=1);
namespace Drupal\my_module;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Psr\Log\LoggerInterface;
final class WebhookDispatcher {
private readonly LoggerInterface $logger;
public function __construct(
LoggerChannelFactoryInterface $loggerFactory,
) {
$this->logger = $loggerFactory->get('my_module');
}
public function send(string $orderId, string $endpoint): bool {
try {
// Perform HTTP request...
$this->logger->info('Dispatched order @order to @host.', [
'@order' => $orderId,
'@host' => parse_url($endpoint, PHP_URL_HOST) ?: 'unknown',
]);
return TRUE;
}
catch (\Throwable $e) {
$this->logger->error('Webhook failed for order @order: @message', [
'@order' => $orderId,
'@message' => $e->getMessage(),
]);
return FALSE;
}
}
}
Notice three clean habits in this pattern:
- Dedicated channel (
my_module): Operators can filterdrush ws --type=my_moduleinstantly without wading through unrelatedphporpage not foundentries. - PSR-3
@placeholdersinstead of.concatenation: Drupal formats@orderand@messagesafely for both HTML admin reports and plain-text syslog/JSON handlers. - Logging only the host (
parse_url(..., PHP_URL_HOST)), not a full URL with query tokens: If a webhook URL contains?api_key=..., logging the raw URL leaks secrets to everyone with “View site reports” permission.
Choosing the right PSR-3 severity level
Using error() for everything creates alert fatigue; using notice() for real failures hides outages:
error()/critical(): Failed payment callbacks, unhandled exceptions in queue workers, broken external API syncs that need attention.warning(): Recoverable issues, such as a third-party rate limit (429) that will be retried by a QueueWorker.info()/notice(): Significant state transitions (batch completed, manual import started) kept concise so they do not flooddblog.debug(): Verbose diagnostics disabled or filtered out in production log handlers.
If you are building background workers or update hooks that log progress, pair clean logging with Drupal Batch API vs. Queue API and Drupal hook_update_N() vs. hook_post_update_NAME(). Also keep dev-only logging modules isolated from production using Drupal Configuration Split.
Common mistakes
- Logging raw user input or
print_r($form_state->getValues())in production. Besides leaking personal data or passwords, huge serialized dumps bloat thewatchdogtable and slow down database backups. - Wrapping log messages in
$this->t(...). Per Drupal’s logging conventions, pass raw English strings with@placeholdersdirectly to$logger->error(...)—the logger formats placeholders itself, avoiding premature translation before storage. - Relying exclusively on
dblog(Database Logging) on high-traffic production sites. Everydblogwrite executes anINSERTquery into MySQL/MariaDB. On busy sites, use coresyslog(or Monolog) and keepdblogrow limits conservative or enabled only on non-production environments.
Why this matters
Good logs turn a 2:00 AM production outage into a 30-second drush ws --type=my_module lookup. Injecting LoggerChannelFactoryInterface, using @placeholders, and scrubbing secrets keeps your logs actionable without turning your database into a security liability.
My Take
Give every custom Drupal module its own logger channel via LoggerChannelFactoryInterface, never pass $this->t() into logger methods, and make it a code-review rule that no exception handler ever logs full request headers, cookies, or query-string secrets.
Conclusion
Inject LoggerChannelFactoryInterface (@logger.factory) into your Drupal 10 and 11 services, call $factory->get('your_module') for a clean channel, pass un-translated messages with @placeholder context arrays, and strip secrets before logging.