I thought this would be easy. For troubleshooting, I wish to call my _logger()
function from anywhere in my application.
function _logger(?string $msg=null, int $offset=0, bool $time=false):void
{
$d1 = debug_backtrace()[$offset+1];
$d2 = debug_backtrace()[$offset+2];
syslog(LOG_INFO, sprintf('_logger%s: %s::%s(%s) called by %s::%s on line %s%s', $time?'('.date("Y-m-d H:i:s").')':'', $d1['class'], $d1['function'], json_encode($d1['args']), $d2['class'], $d2['function'], $d2['line'], $msg?' | '.$msg:''));
}
First, I tried adding it to index.php. When added directly in the main body, I got a server error and either with error reporting, couldn't get any info about it (just curious, but anyone know why?). I then placed it into the closure function and it works for HTTP requests only.
<?php
use App\Kernel;
// Added my logger() function here resulted in unexplained server error.
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
// Added my logger() function here works
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
Then I tried adding it to to Kernal.php, and it seems to work, but must be called as \App\_logger()
.
<?php
declare(strict_types=1);
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
if(!function_exists('_logger')) {
// Added my logger() function here works but must be called as \App\_logger()
}
So, then I created a new file called _logger.php which I located in src, and it works sometimes but other times the get the below error and need to clear cache to get it working again.
<?php
declare(strict_types=1);
if(!function_exists('_logger')) {
// Added my logger() function sometimes works but other times doesn't
}
Expected to find class "App_logger" in file "/var/www/src/_logger.php" while importing services from resource "../src/", but it was not found! Check the namespace prefix used with the resource in /var/www/config/services.yaml (which is being imported from "/var/www/src/Kernel.php"). (500 Internal Server Error)
So, I went back to locating it in Kernel.php, and all is kind of good, but would really know the correct way to add a global function and what are the implications of Symphony's caching when I tried my various approaches.