How to Log Messages to the PHP Error Log from Smarty Templates

I needed a way to write messages to the PHP error log directly from a .tpl file in OJS.
I use OJS version 3.3.0-5 and, with the help of AI, found a solution by modifying the PKPTemplateManager.inc.php file.
Implementation

Open:

lib/pkp/classes/template/PKPTemplateManager.inc.php

  1. Add the logging function

After the existing import statements, add the following code:

import(‘lib.pkp.classes.template.PKPTemplateResource’);

// *******************************
if (!function_exists(‘smarty_function_log’)) {
function smarty_function_log($params, $smarty) {
$message = $params[‘message’] ?? ‘’;
error_log('[OJS Smarty] ’ . print_r($message, true));
return ‘’;
}
}

This function accepts a message parameter and writes it to the PHP error log with the [OJS Smarty] prefix.

  1. Register the function in PKPTemplateManager

Inside the PKPTemplateManager class, find the constructor:

class PKPTemplateManager extends Smarty {
/** @var array of URLs to stylesheets */
private $_styleSheets =; // square brackets

// ... existing class code ...

function __construct() {
    parent::__construct();

    // ... existing constructor code ...

    // *******************************
    $this->registerPlugin('function', 'log', 'smarty_function_log');
}

}

Add the registerPlugin() call inside the constructor, after parent::__construct() and alongside the existing initialization code.

Usage in a Smarty template
You can now call the function directly from any applicable .tpl file:
{log message=“My message”}
The message will be written to the PHP error log, for example:
[OJS Smarty] My message
You can also pass a Smarty variable:
{log message=$myVariable}

Note: Back up the original PKPTemplateManager.inc.php file before editing it. Since this modifies a core PKP file, the change may need to be reapplied after an OJS or PKP upgrade.