如何在线程内使用log4php

时间:2015-02-21 18:32:51

标签: pthreads log4php

我试图在一个线程中使用log4php,因为我不想重新创建一个记录器的轮子。但是,这不起作用:(

<?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();

?>

该计划的输出是:

  

运行....
  启动MyThread :: initializeLogger

知道为什么它不起作用?我也没有例外...... 还有其他想法如何在不重新发明轮子的情况下登录线程吗?

0 个答案:

没有答案