How do I track a publicly downloaded file?

Easton: 5 days ago

I am creating a custom module to track the file download time and user id with a file link or path. I have tried multiple modules but the download the file time tracking option is not available.

How I can programmatically track the file download time?

This is the code I am using.

function mymodule_file_download($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
  if (in_array($scheme, ['private', 'temporary', 'session'])) {
    $permission = "read $scheme files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      return [
        'Content-Type: text/plain',

    if (\Drupal::currentUser()->isAnonymous()) {
      throw new NotFoundHttpException();

  elseif (in_array($scheme, ['public'])){
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();


Claire: 5 days ago

hook_file_download ( doesn't run for public file downloads.

Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.

For example, track downloads with Google Analytics event tracking (