I would like to create a class that provides a logging mechanism. For this I have created the following class:
<?php
namespace tfaq;
final class Logger
{
private static ?Logger $instance = null;
private static $logfilePath;
private static $writeCnt = 0;
public static function getInstance(): Logger
{
if (static::$instance === null) {
static::$instance = new static();
static::$logfilePath = Init::getInstance()->get_plugin_path() . 'log.txt';
if (!file_exists(static::$logfilePath)) {
$log = fopen(static::$logfilePath, "w") or die("Unable to open file!");
fwrite($log, '');
fclose($log);
}
}
return static::$instance;
}
public function write_log_entry($text) {
$log = fopen(static::$logfilePath, "a") or die("Unable to open file!");
if(static::$writeCnt>0) {
fwrite($log, "\r\n");
}
fwrite($log, $text . '[ ' . static::$writeCnt . ' ]');
fclose($log);
static::$writeCnt = static::$writeCnt + 1;
}
}
I use this class on one page:
<?php
use tfaq\Logger;
Logger::getInstance()->write_log_entry('write log entry...');
If I reload this page several times now, I get the following file... I simply cannot explain it to myself. Maybe I am blind or stupid.
First Entry...[ 0 ]First Entry...[ 0 ]First Entry...[ 0 ]