Logging with grav from within a twig file

I like to add logging to one of my twig files for error tracking. I found Debugging & Logging | Grav Documentation from the docs, which should do the job, but how do I call this from within a twig file?

You can’t call Grav’s PHP logger directly from Twig — Twig templates don’t have access to PHP methods like Utils::log().

Options:

  1. Log from PHP: move the logic that needs logging into a plugin or theme PHP file and use
$this->grav['log']->error('message');

  1. Expose a helper to Twig: in your plugin/theme PHP, register a Twig function or filter that wraps the logger, then call that function from Twig.

Example in a plugin:

$this->grav['twig']->twig()->addFunction(
    new \Twig\TwigFunction('log_error', function($msg) {
        $this->grav['log']->error($msg);
    })
);

Twig:

{{ log_error('Something went wrong') }}

Direct logging purely in Twig isn’t supported; you need a PHP bridge.

1 Like

Option 2 looks primising, I’ll check that out. Thanks!