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 of Drupal PSR-3 logging with LoggerChannelFactoryInterface

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 $context array 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/dblog tables.
  • Combine clean logging with drush ws (watchdog:show) and separate syslog or centralized log shipping in high-traffic production sites instead of leaving verbose dblog enabled 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:

  1. Dedicated channel (my_module): Operators can filter drush ws --type=my_module instantly without wading through unrelated php or page not found entries.
  2. PSR-3 @placeholders instead of . concatenation: Drupal formats @order and @message safely for both HTML admin reports and plain-text syslog/JSON handlers.
  3. 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 flood dblog.
  • 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 the watchdog table and slow down database backups.
  • Wrapping log messages in $this->t(...). Per Drupal’s logging conventions, pass raw English strings with @placeholders directly to $logger->error(...)—the logger formats placeholders itself, avoiding premature translation before storage.
  • Relying exclusively on dblog (Database Logging) on high-traffic production sites. Every dblog write executes an INSERT query into MySQL/MariaDB. On busy sites, use core syslog (or Monolog) and keep dblog row 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.

Sources