Logger behaviour change

master
parent 6e0753df18
commit a7159502bd
  1. 6
      Components/Memcached.php
  2. 100
      Harmonious.php
  3. 83
      Log.php
  4. 4
      Logger.php

@ -37,12 +37,12 @@ class Harmonious_Components_Memcached implements IHarmonious_Component{
function get($key, $usecas = false) { function get($key, $usecas = false) {
$m = $this->get_server($key); $m = $this->get_server($key);
if (!$usecas) $ret = $m->get($key); if (!$usecas) $ret = $m->get($key);
else $ret = $m->get($key, null, $cas); else $ret = $m->get($key, null, Memcached::GET_EXTENDED);
if ($ret === false) $retcode = $m->getResultCode(); if ($ret === false) $retcode = $m->getResultCode();
unset($m); unset($m);
if ($ret === false) return array ('result'=>false, 'result_code'=>$retcode, 'result_string'=>$this->retcode2string($retcode)); if ($ret === false) return array ('result'=>false, 'result_code'=>$retcode, 'result_string'=>$this->retcode2string($retcode));
$ret = array ('result'=>true, 'value'=>$ret); if (!$usecas) $ret = array ('result'=>true, 'value'=>$ret);
if ($usecas) $ret['cas'] = $cas; else $ret = array ('result'=>true, 'value'=>$ret, 'cas'=>$ret['cas']);
return $ret; return $ret;
} }

@ -24,11 +24,11 @@
} }
spl_autoload_register(array('Harmonious', 'autoloader')); spl_autoload_register(array('Harmonious', 'autoloader'));
class Harmonious class Harmonious
{ {
protected $template_params = array(); protected $template_params = array();
protected $components; protected $components;
protected $request; protected $request;
protected $response; protected $response;
protected $view; protected $view;
@ -46,13 +46,13 @@
'error.500' => array(array()), 'error.500' => array(array()),
'error.halt' => array(array()) 'error.halt' => array(array())
); );
/** /**
* Constructor * Constructor
* @param array $userSettings * @param array $userSettings
* @return void * @return void
*/ */
public function __construct( $userSettings = array() ) { public function __construct( $userSettings = array() ) {
//Merge application settings //Merge application settings
$this->settings = array_merge(array( $this->settings = array_merge(array(
//Mode //Mode
@ -91,7 +91,7 @@
$this->getMode(); $this->getMode();
$this->components = new Harmonious_Components_Factory($this); $this->components = new Harmonious_Components_Factory($this);
//Setup HTTP request and response handling //Setup HTTP request and response handling
$this->request = $this->components['request']; $this->request = $this->components['request'];
$this->response = $this->components['response'];; $this->response = $this->components['response'];;
@ -109,7 +109,7 @@
if ( $sessionHandler instanceof Harmonious_Session_Handler ) { if ( $sessionHandler instanceof Harmonious_Session_Handler ) {
$sessionHandler->register($this); $sessionHandler->register($this);
} }
session_cache_limiter(false); session_cache_limiter(false);
session_start(); session_start();
} }
@ -120,25 +120,28 @@
set_error_handler(array('Harmonious', 'handleErrors')); set_error_handler(array('Harmonious', 'handleErrors'));
//set_exception_handler(array('Harmonious', 'handleExceptions')); //set_exception_handler(array('Harmonious', 'handleExceptions'));
register_shutdown_function(array($this, 'FatalErrorCatcher')); register_shutdown_function(array($this, 'FatalErrorCatcher'));
} }
/** /**
* Run the Harmonious application * Run the Harmonious application
* @return void * @return void
*/ */
public function run() { public function run() {
try { try {
try { try {
$this->applyHook('app.before', $this); $this->applyHook('app.before', $this);
ob_start(); ob_start();
$this->applyHook('app.before.router', $this);
$httpMethod = $this->request->getMethod(); $httpMethod = $this->request->getMethod();
$uri = rtrim($this->request->getResourceUri(), "/"); $uri = rtrim($this->request->getResourceUri(), "/");
if ($uri == '') $uri = '/index'; if ($uri == '') $uri = '/index';
$controller_name = $this->config('controller_path') . $uri . "_controller.php"; $controller_name = $this->config('controller_path') . $uri . "_controller.php";
$controller_class_name = substr($uri, strrpos($uri, '/') + 1) . "Controller"; $controller_class_name = substr($uri, strrpos($uri, '/') + 1) . "Controller";
$controller_class_name = str_replace('.', '_', $controller_class_name);
$hook_responce = $this->applyHook('app.before.router', array($this, $controller_name, $controller_class_name));
$controller_name = $hook_responce[1];
$controller_class_name = $hook_responce[2];
if (file_exists($controller_name)) { if (file_exists($controller_name)) {
include ($controller_name); include ($controller_name);
//создать экземпляр класса и проверить поддерживается ли http метод, если нет - ошибка 405 //создать экземпляр класса и проверить поддерживается ли http метод, если нет - ошибка 405
@ -169,13 +172,13 @@
} catch ( Slim_Exception_Stop $e ) { } catch ( Slim_Exception_Stop $e ) {
//Exit application context //Exit application context
} }
} }
/** /**
* "Магические" методы для работы с компонентами Harmonious. * "Магические" методы для работы с компонентами Harmonious.
* http://www.php.net/manual/ru/language.oop5.magic.php * http://www.php.net/manual/ru/language.oop5.magic.php
* *
* Возвращает компонент Harmonious из фабрики. * Возвращает компонент Harmonious из фабрики.
* @param type $name - Имя компонента * @param type $name - Имя компонента
* @return type - объект(компонент Harmonious) * @return type - объект(компонент Harmonious)
*/ */
@ -183,7 +186,7 @@
if ($name == 'components') return $this->components; if ($name == 'components') return $this->components;
return $this->components[$name]; return $this->components[$name];
} }
/** /**
* Добавляет компонент в фабрику * Добавляет компонент в фабрику
* @param type $name - имя компонента * @param type $name - имя компонента
@ -193,22 +196,22 @@
{ {
$this->components[$name] = $value; $this->components[$name] = $value;
} }
/****** Параметры шаблона ******/ /****** Параметры шаблона ******/
/** /**
* Глобальный массив параметров шаблона используется для наполнения шаблона параметрами из различных * Глобальный массив параметров шаблона используется для наполнения шаблона параметрами из различных
* участков кода. Например, часть параметров может быть передана посредством хука, а остальные посредством * участков кода. Например, часть параметров может быть передана посредством хука, а остальные посредством
* контроллена. См. также метод render, в котором этот глобальные массив объединяется с переданным перед * контроллена. См. также метод render, в котором этот глобальные массив объединяется с переданным перед
* передачей в шаблон. * передачей в шаблон.
* *
* Объединяет два массива: переданный в параметре и глобальный массив параметров шаблона * Объединяет два массива: переданный в параметре и глобальный массив параметров шаблона
* @param type $array * @param type $array
*/ */
public function addTemplateParam($array) { public function addTemplateParam($array) {
$this->template_params = array_merge($this->template_params, $array); $this->template_params = array_merge($this->template_params, $array);
} }
/** /**
* Чистит глобальный массив параметров шаблона * Чистит глобальный массив параметров шаблона
*/ */
@ -216,15 +219,15 @@
unset($this->template_params); unset($this->template_params);
$this->template_params = array(); $this->template_params = array();
} }
/** /**
* Возвращает глобальный массив параметров шаблона * Возвращает глобальный массив параметров шаблона
* @return type * @return type
*/ */
public function getTemplateParams() { public function getTemplateParams() {
return $this->template_params; return $this->template_params;
} }
/** /**
* Render a template * Render a template
* @param string $template The name of the template passed into the View::render method * @param string $template The name of the template passed into the View::render method
@ -237,8 +240,8 @@
$data = array_merge($this->template_params, $data); $data = array_merge($this->template_params, $data);
$this->view->appendData($data); $this->view->appendData($data);
$this->view->display($template); $this->view->display($template);
} }
/** /**
* Render a template * Render a template
* @param string $template The name of the template passed into the View::render method * @param string $template The name of the template passed into the View::render method
@ -251,8 +254,8 @@
$data = array_merge($this->template_params, $data); $data = array_merge($this->template_params, $data);
$this->view->appendData($data); $this->view->appendData($data);
return $this->view->fetch($template); return $this->view->fetch($template);
} }
/** /**
* Harmonious auto-loader * Harmonious auto-loader
* Этот метод производит загрузку файлов с классами при первом обращении к ним. Грузит свои классы и классы Slim-а * Этот метод производит загрузку файлов с классами при первом обращении к ним. Грузит свои классы и классы Slim-а
@ -260,19 +263,19 @@
*/ */
public static function autoloader( $className ) { public static function autoloader( $className ) {
$className = str_replace('Slim', 'Harmonious', $className); $className = str_replace('Slim', 'Harmonious', $className);
if ( strpos($className, 'Harmonious') !== 0 ) { if ( strpos($className, 'Harmonious') !== 0 ) {
return; return;
} }
$file = dirname(__FILE__) . '/' . str_replace('_', DIRECTORY_SEPARATOR, substr($className, 11)) . '.php'; $file = dirname(__FILE__) . '/' . str_replace('_', DIRECTORY_SEPARATOR, substr($className, 11)) . '.php';
if ( file_exists($file) ) { if ( file_exists($file) ) {
require $file; require $file;
} }
} }
/***** CONFIGURATION *****/ /***** CONFIGURATION *****/
/** /**
* Get application mode * Get application mode
* @return string * @return string
@ -285,7 +288,7 @@
} }
return $this->mode; return $this->mode;
} }
/** /**
* Configure Slim for a given mode * Configure Slim for a given mode
* *
@ -330,27 +333,27 @@
} else { } else {
$this->settings[$name] = $value; $this->settings[$name] = $value;
} }
} }
/***** LOGGING *****/ /***** LOGGING *****/
/** /**
* Get application Log (lazy-loaded) * Get application Log (lazy-loaded)
* @return Slim_Log * @return Harmonious_Log
*/ */
public function getLog() { public function getLog() {
if ( !isset($this->log) ) { if ( !isset($this->log) ) {
$this->log = new Slim_Log(); $this->log = new Harmonious_Log();
$this->log->setEnabled($this->config('log.enable')); $this->log->setEnabled($this->config('log.enable'));
$logger = $this->config('log.logger'); $logger = $this->config('log.logger');
if ( $logger ) { if ( $logger ) {
$this->log->setLogger($logger); $this->log->setLogger($logger);
} else { } else {
$this->log->setLogger(new Slim_Logger($this->config('log.path'), $this->config('log.level'))); $this->log->setLogger(new Harmonious_Logger($this->config('log.path'), $this->config('log.level')));
} }
} }
return $this->log; return $this->log;
} }
/** /**
* Not Found Handler * Not Found Handler
@ -374,7 +377,7 @@
$this->halt(500, ob_get_clean()); $this->halt(500, ob_get_clean());
} }
/***** ACCESSORS *****/ /***** ACCESSORS *****/
/** /**
* Get and/or set the View * Get and/or set the View
* *
@ -668,8 +671,8 @@
} else { } else {
throw new InvalidArgumentException('Slim::redirect only accepts HTTP 300-307 status codes.'); throw new InvalidArgumentException('Slim::redirect only accepts HTTP 300-307 status codes.');
} }
} }
/***** HOOKS *****/ /***** HOOKS *****/
/** /**
@ -706,7 +709,8 @@
foreach( $this->hooks[$name] as $priority ) { foreach( $this->hooks[$name] as $priority ) {
if( !empty($priority) ) { if( !empty($priority) ) {
foreach($priority as $callable) { foreach($priority as $callable) {
$hookArg = call_user_func($callable, $hookArg); if (is_array($hookArg)) $hookArg = call_user_func_array($callable, $hookArg);
else $hookArg = call_user_func($callable, $hookArg);
} }
} }
} }
@ -770,6 +774,8 @@
* @throws ErrorException * @throws ErrorException
*/ */
public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) { public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) {
if (isset($this)) $this->getLog()->error('handleErrors catched: '.$errstr);
if ( error_reporting() & $errno ) { if ( error_reporting() & $errno ) {
if (isset($this)) $this->getLog()->error('Unhandled Error: '.$errstr); if (isset($this)) $this->getLog()->error('Unhandled Error: '.$errstr);
throw new ErrorException($errstr, $errno, 0, $errfile, $errline); throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
@ -781,7 +787,7 @@
$this->getLog()->error('Unhandled Exception: '.$exception->getMessage()); $this->getLog()->error('Unhandled Exception: '.$exception->getMessage());
throw $exception; throw $exception;
} }
public function FatalErrorCatcher() public function FatalErrorCatcher()
{ {
$error = error_get_last(); $error = error_get_last();
@ -809,7 +815,7 @@
} }
} }
} }
/** /**
* Generate markup for error message * Generate markup for error message
* *
@ -866,6 +872,6 @@
protected function defaultError() { protected function defaultError() {
echo self::generateTemplateMarkup('Error', '<p>A website error has occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.</p>'); echo self::generateTemplateMarkup('Error', '<p>A website error has occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.</p>');
} }
} }
?> ?>

@ -50,12 +50,12 @@
* @author Josh Lockhart <info@joshlockhart.com> * @author Josh Lockhart <info@joshlockhart.com>
* @since Version 1.0 * @since Version 1.0
*/ */
class Slim_Log { class Harmonious_Log {
/** /**
* @var mixed An object that implements expected Logger interface * @var mixed An object that implements expected Logger interface
*/ */
protected $logger; protected $loggers = array();
/** /**
* @var bool Enable logging? * @var bool Enable logging?
@ -90,66 +90,51 @@ class Slim_Log {
return $this->enabled; return $this->enabled;
} }
/** public function __call($name, $args) {
* Log debug message if ($this->isEnabled()) {
* @param mixed $object $name = strtolower($name);
* @return mixed|false What the Logger returns, or false if Logger not set or not enabled $result = true;
*/ foreach ($this->loggers as $logger) {
public function debug( $object ) { switch ($name) {
return isset($this->logger) && $this->isEnabled() ? $this->logger->debug($object) : false; case 'debug':
} if (!$logger->debug($args)) $result = false;
break;
/** case 'info':
* Log info message if (!$logger->info($args)) $result = false;
* @param mixed $object break;
* @return mixed|false What the Logger returns, or false if Logger not set or not enabled case 'warn':
*/ if (!$logger->warn($args)) $result = false;
public function info( $object ) { break;
return isset($this->logger) && $this->isEnabled() ? $this->logger->info($object) : false; case 'error':
} if (!$logger->error($args)) $result = false;
break;
/** case 'fatal':
* Log warn message if (!$logger->fatal($args)) $result = false;
* @param mixed $object break;
* @return mixed|false What the Logger returns, or false if Logger not set or not enabled default:
*/ return false;
public function warn( $object ) { break;
return isset($this->logger) && $this->isEnabled() ? $this->logger->warn($object) : false; }
}
return $result;
} else return false;
} }
/**
* Log error message
* @param mixed $object
* @return mixed|false What the Logger returns, or false if Logger not set or not enabled
*/
public function error( $object ) {
return isset($this->logger) && $this->isEnabled() ? $this->logger->error($object) : false;
}
/**
* Log fatal message
* @param mixed $object
* @return mixed|false What the Logger returns, or false if Logger not set or not enabled
*/
public function fatal( $object ) {
return isset($this->logger) && $this->isEnabled() ? $this->logger->fatal($object) : false;
}
/** /**
* Set Logger * Set Logger
* @param mixed $logger * @param mixed $logger
* @return void * @return void
*/ */
public function setLogger( $logger ) { public function setLogger( $logger ) {
$this->logger = $logger; $this->loggers[] = $logger;
} }
/** /**
* Get Logger * Get Logger
* @return mixed * @return mixed
*/ */
public function getLogger() { public function getLoggers() {
return $this->logger; return $this->loggers;
} }
} }

@ -42,7 +42,7 @@
* @author Josh Lockhart <info@joshlockhart.com> * @author Josh Lockhart <info@joshlockhart.com>
* @since Version 1.0 * @since Version 1.0
*/ */
class Slim_Logger { class Harmonious_Logger {
/** /**
* @var array Log levels * @var array Log levels
@ -184,7 +184,7 @@ class Slim_Logger {
throw new RuntimeException("Log directory '$dir' not writable."); throw new RuntimeException("Log directory '$dir' not writable.");
} }
if ( $level <= $this->getLevel() ) { if ( $level <= $this->getLevel() ) {
$this->write(sprintf("[%s] %s - %s\r\n", $this->levels[$level], date('c'), (string)$data)); $this->write(sprintf("[%s] %s - %s\r\n", $this->levels[$level], date('c'), (string)$data[0]));
} }
} }

Loading…
Cancel
Save