I am trying to use log4php inside a thread, as I don't want to re-create the wheel of a logger. However, that doesn't work :(
<?php
date_default_timezone_set('UTC');
require_once(dirname(__FILE__).'/../log4php/Logger.php');
$log4php = array(
'appenders' => array(
'default' => array(
'class' => 'LoggerAppenderFile',
'layout' => array(
'class' => 'LoggerLayoutPattern',
'params' => array (
'conversionPattern' => '%date{Y-m-d H:i:s,u} %-5level %5pid %-20c %-20C %message%exception%newline',
),
),
'params' => array(
'file' => './POC.log',
'append' => true,
)
),
),
'rootLogger' => array(
'level' => 'info',
'appenders' => array('default'),
),
'TEST' => array(
'level' => 'info',
'appenders' => array('default'),
),
);
class MyThread extends Thread {
protected $logger=null;
protected $loggerConfig=null;
public function __destruct() {
if($this->logger) {
$this->logger->info("Destroy ThreadConfig with threadId:".$this->getThreadId());
}
}
public function run() {
echo "Running....\n";
$this->initializeLogger();
echo "Trying to log something\n";
$this->logger->info("Starting config thread with threadId:".$this->getThreadId());
echo "Have I logged something?\n";
}
public function setLoggerConfig($config) {
$this->loggerConfig = $config;
}
public function initializeLogger()
{
echo 'Start '. __CLASS__ .'::' . __FUNCTION__ . "\n";
if(!$this->loggerConfig) {
throw new Exception('Failed to initialize logger since no config available');
}
Logger::configure($this->loggerConfig);
$this->logger = Logger::getLogger('TEST');
echo 'Finish '. __CLASS__ .'::' . __FUNCTION__ . "\n";
}
}
$my_thread = new MyThread();
$my_thread->setLoggerConfig($log4php);
$my_thread->start();
?>
Output of the program is:
Running....
Start MyThread::initializeLogger
Any idea why it doesn't work ? I also get no exceptions... Any other idea how to log inside a thread without re-inventing the wheel?