configure Tlog and TlogFile

This commit is contained in:
Manuel Raynaud
2012-12-27 18:05:50 +01:00
parent e74752cc3a
commit f5493f86af
14 changed files with 624 additions and 201 deletions

1
.gitignore vendored
View File

@@ -5,3 +5,4 @@ local/config/build
core/vendor core/vendor
local/config/runtime-conf.xml local/config/runtime-conf.xml
propel-gen propel-gen
log/*

View File

@@ -0,0 +1,82 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* First Bundle use in Thelia
* It initialize dependency injection container.
*
* @TODO load configuration from thelia plugin
* @TODO register database configuration.
*
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class LoggerBundle extends Bundle
{
/**
*
* Construct the depency injection builder
*
* Reference all Model in the Container here
*
* @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
*/
public function build(ContainerBuilder $container)
{
$container->setParameter("logger.class", "\Thelia\Log\Tlog");
$container->register("logger","%logger.class%")
->addArgument(new Reference('service_container'));
$kernel = $container->get('kernel');
if($kernel->isDebug())
{
// $debug = function ($query, $parameters)
// {
//
// $pattern = '(^' . preg_quote(dirname(__FILE__)) . '(\\.php$|[/\\\\]))'; // can be static
// foreach (debug_backtrace() as $backtrace) {
// if (isset($backtrace["file"]) && !preg_match($pattern, $backtrace["file"])) { // stop on first file outside NotORM source codes
// break;
// }
// }
// file_put_contents(THELIA_ROOT . 'log/request_debug.log', "$backtrace[file]:$backtrace[line]:$query", FILE_APPEND);
// file_put_contents(THELIA_ROOT . 'log/request_debug.log', is_scalar($parameters) ? $parameters : print_r($parameters, true), FILE_APPEND);
//
// };
//
// $container->getDefinition('database')
// ->addMethodCall('setDebug', array($debug));
$container->get('database')
->setLogger($container->get('logger'));
}
}
}

View File

@@ -26,6 +26,8 @@ use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
use Thelia\Log\Tlog;
/** /**
* First Bundle use in Thelia * First Bundle use in Thelia
* It initialize dependency injection container. * It initialize dependency injection container.
@@ -48,7 +50,9 @@ class NotORMBundle extends Bundle
public function build(ContainerBuilder $container) public function build(ContainerBuilder $container)
{ {
$config = array(); $config = array(
// \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
);
$kernel = $container->get('kernel'); $kernel = $container->get('kernel');
@@ -97,16 +101,7 @@ class NotORMBundle extends Bundle
} }
} }
if($kernel->isDebug())
{
$debug = function ($query, $parameters)
{
echo $query."<br />";
};
$container->getDefinition('database')
->addMethodCall('setDebug', array($debug));
}
} }

View File

@@ -69,9 +69,6 @@ class TheliaBundle extends Bundle
$container->register('parser','Thelia\Core\Template\Parser') $container->register('parser','Thelia\Core\Template\Parser')
->addArgument(new Reference('service_container')) ->addArgument(new Reference('service_container'))
; ;
// $container->setParameter("logger.class", "\Thelia\Log\Tlog");
// $container->register("logger","%logger.class%");
/** /**
* RouterListener implements EventSubscriberInterface and listen for kernel.request event * RouterListener implements EventSubscriberInterface and listen for kernel.request event
*/ */

View File

@@ -79,6 +79,8 @@ class Parser implements ParserInterface
$this->content = $request->get("test"); $this->content = $request->get("test");
$config = $this->container->get("model.config"); $config = $this->container->get("model.config");
echo $config->read("toto","tutu");
return $this->content; return $this->content;
} }

View File

@@ -34,9 +34,7 @@ namespace Thelia\Core;
use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderInterface;
use Thelia\Core\Bundle\TheliaBundle; use Thelia\Core\Bundle;
use Thelia\Core\Bundle\NotORMBundle;
use Thelia\Core\Bundle\ModelBundle;
class Thelia extends Kernel class Thelia extends Kernel
{ {
@@ -119,9 +117,10 @@ class Thelia extends Kernel
{ {
$bundles = array( $bundles = array(
/* TheliaBundle contain all the dependency injection description */ /* TheliaBundle contain all the dependency injection description */
new TheliaBundle(), new Bundle\TheliaBundle(),
new NotORMBundle(), new Bundle\NotORMBundle(),
new ModelBundle() new Bundle\ModelBundle(),
new Bundle\LoggerBundle()
); );
/** /**

View File

@@ -22,6 +22,10 @@
/*************************************************************************************/ /*************************************************************************************/
namespace Thelia\Database; namespace Thelia\Database;
use Thelia\Log\TlogInterface;
use Thelia\Database\NotORM\Result;
/** /**
* *
* Class Thelia\Database\NotORM extending \NotORM library http://www.notorm.com/ * Class Thelia\Database\NotORM extending \NotORM library http://www.notorm.com/
@@ -33,11 +37,18 @@ namespace Thelia\Database;
class NotORM extends \NotORM class NotORM extends \NotORM
{ {
public $logger = false;
public function setCache(\NotORM_Cache $cache) public function setCache(\NotORM_Cache $cache)
{ {
$this->cache = $cache; $this->cache = $cache;
} }
public function setLogger(TlogInterface $logger)
{
$this->logger = $logger;
}
public function setDebug($debug) public function setDebug($debug)
{ {
if(is_callable($debug)) if(is_callable($debug))
@@ -47,4 +58,17 @@ class NotORM extends \NotORM
$this->debug = true; $this->debug = true;
} }
} }
/** Get table data
* @param string
* @param array (["condition"[, array("value")]]) passed to NotORM_Result::where()
* @return NotORM_Result
*/
function __call($table, array $where) {
$return = new Result($this->structure->getReferencingTable($table, ''), $this);
if ($where) {
call_user_func_array(array($return, 'where'), $where);
}
return $return;
}
} }

View File

@@ -0,0 +1,40 @@
<?php
namespace Thelia\Database\NotORM;
class Result extends \NotORM_Result
{
protected function query($query, $parameters) {
if ($this->notORM->debug) {
if (!is_callable($this->notORM->debug)) {
$debug = "$query;";
if ($parameters) {
$debug .= " -- " . implode(", ", array_map(array($this, 'quote'), $parameters));
}
$pattern = '(^' . preg_quote(dirname(__FILE__)) . '(\\.php$|[/\\\\]))'; // can be static
foreach (debug_backtrace() as $backtrace) {
if (isset($backtrace["file"]) && !preg_match($pattern, $backtrace["file"])) { // stop on first file outside NotORM source codes
break;
}
}
fwrite(STDERR, "$backtrace[file]:$backtrace[line]:$debug\n");
} elseif (call_user_func($this->notORM->debug, $query, $parameters) === false) {
return false;
}
}
if($this->notORM->logger !== false)
{
$this->notORM->logger->debug($query);
$this->notORM->logger->debug($parameters);
}
$return = $this->notORM->connection->prepare($query);
if (!$return || !$return->execute(array_map(array($this, 'formatValue'), $parameters))) {
$this->notORM->logger->fatal("Error for this query : ".$query);
$this->notORM->logger->fatal($this->notORM->errorCode);
$this->notORM->logger->fatal($this->notORM->errorInfo);
return false;
}
return $return;
}
}

View File

@@ -33,6 +33,8 @@ abstract class AbstractTlogDestination {
// Vaudra true si on est dans le back office. // Vaudra true si on est dans le back office.
protected $flag_back_office = false; protected $flag_back_office = false;
protected $configModel;
public function __construct() { public function __construct() {
$this->_configs = array(); $this->_configs = array();
@@ -58,6 +60,16 @@ abstract class AbstractTlogDestination {
} }
return false; return false;
} }
public function setConfigModel($configModel)
{
$this->configModel = $configModel;
}
public function getConfigModel()
{
return $this->configModel;
}
//Récupère la valeur affectée à une configuration de la destination //Récupère la valeur affectée à une configuration de la destination
public function get_config($nom) { public function get_config($nom) {
@@ -73,33 +85,33 @@ abstract class AbstractTlogDestination {
return $this->_configs; return $this->_configs;
} }
public function mode_back_office($bool) { public function mode_back_office($bool) {
$this->flag_back_office = $bool; $this->flag_back_office = $bool;
} }
//Ajoute une ligne de logs à la destination //Ajoute une ligne de logs à la destination
public function ajouter($string) { public function ajouter($string) {
$this->_logs[] = $string; $this->_logs[] = $string;
} }
protected function inserer_apres_body(&$res, $logdata) { protected function inserer_apres_body(&$res, $logdata) {
$match = array(); $match = array();
if (preg_match("/(<body[^>]*>)/i", $res, $match)) { if (preg_match("/(<body[^>]*>)/i", $res, $match)) {
$res = str_replace($match[0], $match[0] . "\n" . $logdata, $res); $res = str_replace($match[0], $match[0] . "\n" . $logdata, $res);
} }
else { else {
$res = $logdata . $res; $res = $logdata . $res;
} }
} }
// Demande à la destination de se configurer pour être prête // Demande à la destination de se configurer pour être prête
// a fonctionner. Si $config est != false, celà indique // a fonctionner. Si $config est != false, celà indique
// que seul le paramètre de configuration indiqué a été modifié. // que seul le paramètre de configuration indiqué a été modifié.
protected function configurer($config = false) { protected function configurer($config = false) {
// Cette methode doit etre surchargée si nécessaire. // Cette methode doit etre surchargée si nécessaire.
} }
//Lance l'écriture de tous les logs par la destination //Lance l'écriture de tous les logs par la destination
//$res : contenu de la page html //$res : contenu de la page html

View File

@@ -0,0 +1,107 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Log\Destination;
use Thelia\Log\AbstractTlogDestination;
use Thelia\Log\TlogDestinationConfig;
class TlogDestinationFile extends AbstractTlogDestination {
// Nom des variables de configuration
// ----------------------------------
const VAR_PATH_FILE = "tlog_destinationfile_path";
const TLOG_DEFAULT_NAME = "log-thelia.txt";
const VAR_MODE = "tlog_destinationfile_mode";
const VALEUR_MODE_DEFAUT = "A";
protected $path_defaut = false;
protected $fh = false;
public function __construct($configModel = null) {
$this->path_defaut = THELIA_ROOT . "log/" . self::TLOG_DEFAULT_NAME;
$this->setConfigModel($configModel);
parent::__construct();
}
public function configurer($config = false) {
$file_path = $this->get_config(self::VAR_PATH_FILE);
$mode = strtolower($this->get_config(self::VAR_MODE)) == 'a' ? 'a' : 'w';
if (! empty($file_path)) {
if (! is_file($file_path)) {
$dir = dirname($file_path);
if(! is_dir($dir)) {
mkdir($dir, 0777, true);
}
}
if ($this->fh) @fclose($this->fh);
$this->fh = fopen($file_path, $mode);
}
}
public function get_titre() {
return "Text File";
}
public function get_description() {
return "Store logs into text file";
}
public function get_configs() {
return array(
new TlogDestinationConfig(
self::VAR_PATH_FILE,
"Chemin du fichier",
"Attention, vous devez indiquer un chemin absolu.<br />Le répertoire de base de votre Thelia est ".dirname(getcwd()),
$this->path_defaut,
TlogDestinationConfig::TYPE_TEXTFIELD,
$this->getConfigModel()
),
new TlogDestinationConfig(
self::VAR_MODE,
"Mode d'ouverture (A ou E)",
"Indiquez E pour ré-initialiser le fichier à chaque requête, A pour ne jamais réinitialiser le fichier. Pensez à le vider de temps en temps !",
self::VALEUR_MODE_DEFAUT,
TlogDestinationConfig::TYPE_TEXTFIELD,
$this->getConfigModel()
)
);
}
public function ajouter($texte) {
if ($this->fh) {
fwrite($this->fh, $texte."\n");
}
}
public function ecrire(&$res) {
if ($this->fh) @fclose($this->fh);
$this->fh = false;
}
}

View File

@@ -0,0 +1,72 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Log\Destination;
use Thelia\Log\AbstractTlogDestination;
class TlogDestinationHtml extends AbstractTlogDestination {
// Nom des variables de configuration
// ----------------------------------
const VAR_STYLE = "tlog_destinationhtml_style";
const VALEUR_STYLE_DEFAUT = "text-align: left; font-size: 12px; font-weight: normal; line-height: 14px; float: none; display:block; color: #000; background-color: #fff; font-family: Courier New, courier,fixed;";
private $style;
public function __construct() {
parent::__construct();
}
public function configurer($config = false) {
$this->style = $this->get_config(self::VAR_STYLE);
}
public function get_titre() {
return "Affichage direct dans la page, en HTML";
}
public function get_description() {
return "Permet d'afficher les logs directement dans la page resultat, avec une mise en forme HTML.";
}
public function get_configs() {
// return array(
// new TlogDestinationConfig(
// self::VAR_STYLE,
// "Style d'affichage direct dans la page",
// "Vous pouvez aussi laisser ce champ vide, et créer un style \"tlog-trace\" dans votre feuille de style.",
// self::VALEUR_STYLE_DEFAUT,
// TlogDestinationConfig::TYPE_TEXTAREA
// )
// );
}
public function ecrire(&$res) {
$block = sprintf('<pre class="tlog-trace" style="%s">%s</pre>', $this->style, htmlspecialchars(implode("\n", $this->_logs)));
$this->inserer_apres_body($res, $block);
}
}

View File

@@ -23,6 +23,7 @@
namespace Thelia\Log; namespace Thelia\Log;
use Thelia\Model\Config; use Thelia\Model\Config;
use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* *
@@ -32,7 +33,7 @@ use Thelia\Model\Config;
* *
* @author Franck Allimant <franck@cqfdev.fr> * @author Franck Allimant <franck@cqfdev.fr>
*/ */
class Tlog class Tlog Implements TlogInterface
{ {
// Nom des variables de configuration // Nom des variables de configuration
const VAR_LEVEL = "tlog_level"; const VAR_LEVEL = "tlog_level";
@@ -52,8 +53,8 @@ class Tlog
const MUET = PHP_INT_MAX; const MUET = PHP_INT_MAX;
// default values // default values
const DEFAULT_LEVEL = self::MUET; const DEFAULT_LEVEL = self::DEBUG;
const DEFAUT_DESTINATIONS = "Thelia\Log\Destination\TlogDestinationHtml"; const DEFAUT_DESTINATIONS = "Thelia\Log\Destination\TlogDestinationFile";
const DEFAUT_PREFIXE = "#NUM: #NIVEAU [#FICHIER:#FONCTION()] {#LIGNE} #DATE #HEURE: "; const DEFAUT_PREFIXE = "#NUM: #NIVEAU [#FICHIER:#FONCTION()] {#LIGNE} #DATE #HEURE: ";
const DEFAUT_FILES = "*"; const DEFAUT_FILES = "*";
const DEFAUT_IP = ""; const DEFAUT_IP = "";
@@ -76,22 +77,39 @@ class Tlog
// directories where are the Destinations Files // directories where are the Destinations Files
public $dir_destinations = array(); public $dir_destinations = array();
public static function instance() { protected $container;
if (self::$instance == false) {
self::$instance = new Tlog(); /**
*
// On doit placer les initialisations à ce niveau pour pouvoir * @param type $container
// utiliser la classe Tlog dans les classes de base (Cnx, BaseObj, etc.) *
// Les placer dans le constructeur provoquerait une boucle * public function __construct(ContainerBuilder $container)
self::$instance->init(); */
} public function __construct(ContainerInterface $container)
{
return self::$instance; $this->container = $container;
$this->init();
} }
// public static function instance() {
// if (self::$instance == false) {
// self::$instance = new Tlog();
//
// // On doit placer les initialisations à ce niveau pour pouvoir
// // utiliser la classe Tlog dans les classes de base (Cnx, BaseObj, etc.)
// // Les placer dans le constructeur provoquerait une boucle
// self::$instance->init();
// }
//
// return self::$instance;
// }
protected function init() { protected function init() {
$level = Config::read(self::VAR_LEVEL, self::DEFAULT_LEVEL); $config = $this->container->get("model.config");
$level = $config->read(self::VAR_LEVEL, self::DEFAULT_LEVEL);
$this->set_niveau($level); $this->set_niveau($level);
@@ -100,11 +118,11 @@ class Tlog
//, __DIR__.'/../client/tlog/destinations' //, __DIR__.'/../client/tlog/destinations'
); );
$this->set_prefixe(Config::read(self::VAR_PREFIXE, self::DEFAUT_PREFIXE)); $this->set_prefixe($config->read(self::VAR_PREFIXE, self::DEFAUT_PREFIXE));
$this->set_files(Config::read(self::VAR_FILES, self::DEFAUT_FILES)); $this->set_files($config->read(self::VAR_FILES, self::DEFAUT_FILES));
$this->set_ip(Config::read(self::VAR_IP, self::DEFAUT_IP)); $this->set_ip($config->read(self::VAR_IP, self::DEFAUT_IP));
$this->set_destinations(Config::read(self::VAR_DESTINATIONS, self::DEFAUT_DESTINATIONS)); $this->set_destinations($config->read(self::VAR_DESTINATIONS, self::DEFAUT_DESTINATIONS));
$this->set_show_redirect(Config::read(self::VAR_SHOW_REDIRECT, self::DEFAUT_SHOW_REDIRECT)); $this->set_show_redirect($config->read(self::VAR_SHOW_REDIRECT, self::DEFAUT_SHOW_REDIRECT));
// Au cas ou il y aurait un exit() quelque part dans le code. // Au cas ou il y aurait un exit() quelque part dans le code.
register_shutdown_function(array($this, 'ecrire_si_exit')); register_shutdown_function(array($this, 'ecrire_si_exit'));
@@ -113,13 +131,13 @@ class Tlog
// Configuration // Configuration
// ------------- // -------------
public function set_destinations(AbstractTlogDestination $destinations) { public function set_destinations($destinations) {
if (! empty($destinations)) { if (! empty($destinations)) {
$this->destinations = array(); $this->destinations = array();
$classes_destinations = explode(';', $destinations); $classes_destinations = explode(';', $destinations);
$this->charger_classes_destinations($this->destinations, $classes_destinations); $this->loadDestinations($this->destinations, $classes_destinations);
} }
} }
@@ -167,179 +185,179 @@ class Tlog
// Methodes d'accès aux traces // Methodes d'accès aux traces
// --------------------------- // ---------------------------
public static function trace() { public function trace() {
if (Tlog::instance()->niveau > self::TRACE) if ($this->niveau > self::TRACE)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("TRACE", $args); $this->out("TRACE", $args);
} }
public static function debug() { public function debug() {
if (Tlog::instance()->niveau > self::DEBUG) if ($this->niveau > self::DEBUG)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("DEBUG", $args); $this->out("DEBUG", $args);
} }
public static function info() { public function info() {
if (Tlog::instance()->niveau > self::INFO) if ($this->niveau > self::INFO)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("INFO", $args); $this->out("INFO", $args);
} }
public static function warning() { public function warning() {
if (Tlog::instance()->niveau > self::WARNING) if (Tlog::instance()->niveau > self::WARNING)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("WARNING", $args); $this->out("WARNING", $args);
} }
public static function error() { public function error() {
if (Tlog::instance()->niveau > self::ERROR) if ($this->niveau > self::ERROR)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("ERREUR", $args); $this->out("ERREUR", $args);
} }
public static function fatal() { public function fatal() {
if (Tlog::instance()->niveau > self::FATAL) if ($this->niveau > self::FATAL)
return; return;
$args = func_get_args(); $args = func_get_args();
Tlog::instance()->out("FATAL", $args); $this->out("FATAL", $args);
} }
// Mode back office // Mode back office
public static function mode_back_office($booleen) { public static function mode_back_office($booleen) {
foreach(Tlog::instance()->destinations as $dest) { foreach(Tlog::instance()->destinations as $dest) {
$dest->mode_back_office($booleen); $dest->mode_back_office($booleen);
} }
} }
// Ecriture finale // Ecriture finale
public static function ecrire(&$res) { public function ecrire(&$res) {
self::$ecrire_effectue = true; self::$ecrire_effectue = true;
// Muet ? On ne fait rien // Muet ? On ne fait rien
if (Tlog::instance()->niveau == self::MUET) return; if ($this->niveau == self::MUET) return;
foreach(Tlog::instance()->destinations as $dest) { foreach($this->destinations as $dest) {
$dest->ecrire($res); $dest->ecrire($res);
} }
} }
public static function ecrire_si_exit() { public function ecrire_si_exit() {
// Si les infos de debug n'ont pas été ecrites, le faire maintenant // Si les infos de debug n'ont pas été ecrites, le faire maintenant
if (self::$ecrire_effectue === false) { if (self::$ecrire_effectue === false) {
$res = ""; $res = "";
self::ecrire($res); $this->ecrire($res);
echo $res; echo $res;
} }
} }
public function afficher_redirections($url) { public function afficher_redirections($url) {
if ($this->niveau != self::MUET && $this->show_redirect) { if ($this->niveau != self::MUET && $this->show_redirect) {
echo " echo "
<html> <html>
<head><title>Redirection...</title></head> <head><title>Redirection...</title></head>
<body> <body>
<a href=\"$url\">Redirection vers $url</a> <a href=\"$url\">Redirection vers $url</a>
</body> </body>
</html> </html>
"; ";
return true; return true;
} }
else { else {
return false; return false;
} }
} }
// Permet de déterminer si la trace est active, en prenant en compte // Permet de déterminer si la trace est active, en prenant en compte
// le niveau et le filtrage par fichier // le niveau et le filtrage par fichier
public function active($level) { public function active($level) {
if ($this->niveau <= $level) { if ($this->niveau <= $level) {
$origine = $this->trouver_origine(); $origine = $this->trouver_origine();
$file = basename($origine['file']); $file = basename($origine['file']);
if ($this->is_file_active($file)) { if ($this->is_file_active($file)) {
return true; return true;
} }
} }
return false; return false;
} }
public function is_file_active($file) { public function is_file_active($file) {
return ($this->all_files || in_array($file, $this->files)) && ! in_array("!$file", $this->files); return ($this->all_files || in_array($file, $this->files)) && ! in_array("!$file", $this->files);
} }
/* -- Methodes privees ---------------------------------------- */ /* -- Methodes privees ---------------------------------------- */
// Adapté de LoggerLoginEvent dans log4php // Adapté de LoggerLoginEvent dans log4php
private function trouver_origine() { private function trouver_origine() {
$origine = array(); $origine = array();
if(function_exists('debug_backtrace')) { if(function_exists('debug_backtrace')) {
$trace = debug_backtrace(); $trace = debug_backtrace();
$prevHop = null; $prevHop = null;
// make a downsearch to identify the caller // make a downsearch to identify the caller
$hop = array_pop($trace); $hop = array_pop($trace);
while($hop !== null) {
if(isset($hop['class'])) {
// we are sometimes in functions = no class available: avoid php warning here
$className = $hop['class'];
while($hop !== null) { if (! empty($className) and ($className == ltrim($this->container->getParameter("logger.class"),'\\') or strtolower(get_parent_class($className)) == ltrim($this->container->getParameter("logger.class"),'\\'))) {
if(isset($hop['class'])) { $origine['line'] = $hop['line'];
// we are sometimes in functions = no class available: avoid php warning here $origine['file'] = $hop['file'];
$className = strtolower($hop['class']); break;
}
}
$prevHop = $hop;
$hop = array_pop($trace);
}
if (! empty($className) and ($className == 'tlog' or strtolower(get_parent_class($className)) == 'tlog')) { $origine['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main';
$origine['line'] = $hop['line'];
$origine['file'] = $hop['file'];
break;
}
}
$prevHop = $hop;
$hop = array_pop($trace);
}
$origine['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main'; if(isset($prevHop['function']) and
$prevHop['function'] !== 'include' and
$prevHop['function'] !== 'include_once' and
$prevHop['function'] !== 'require' and
$prevHop['function'] !== 'require_once') {
if(isset($prevHop['function']) and $origine['function'] = $prevHop['function'];
$prevHop['function'] !== 'include' and } else {
$prevHop['function'] !== 'include_once' and $origine['function'] = 'main';
$prevHop['function'] !== 'require' and }
$prevHop['function'] !== 'require_once') { }
$origine['function'] = $prevHop['function']; return $origine;
} else { }
$origine['function'] = 'main';
}
}
return $origine;
}
private function out($level, $tabargs) { private function out($level, $tabargs) {
@@ -353,52 +371,46 @@ class Tlog
$file = basename($origine['file']); $file = basename($origine['file']);
if ($this->is_file_active($file)) { if ($this->is_file_active($file)) {
$function = $origine['function']; $function = $origine['function'];
$line = $origine['line']; $line = $origine['line'];
$prefixe = str_replace( $prefixe = str_replace(
array("#NUM", "#NIVEAU", "#FICHIER", "#FONCTION", "#LIGNE", "#DATE", "#HEURE"), array("#NUM", "#NIVEAU", "#FICHIER", "#FONCTION", "#LIGNE", "#DATE", "#HEURE"),
array(1+$this->linecount, $level, $file, $function, $line, date("Y-m-d"), date("G:i:s")), array(1+$this->linecount, $level, $file, $function, $line, date("Y-m-d"), date("G:i:s")),
$this->prefixe $this->prefixe
); );
$trace = $prefixe . $text; $trace = $prefixe . $text;
foreach($this->destinations as $dest) { foreach($this->destinations as $dest) {
$dest->ajouter($trace); $dest->ajouter($trace);
} }
$this->linecount++; $this->linecount++;
} }
} }
protected function charger_classes_destinations(&$destinations, $actives = false) { /**
*
foreach($this->dir_destinations as $dir) { * @param type $destinations
$classes = array(); * @param array $actives array containing classes instanceof AbstractTlogDestination
*/
if ($dh = @opendir($dir)) { protected function loadDestinations(&$destinations, array $actives = NULL) {
while ($file = readdir($dh)) { foreach($actives as $active)
{
if ($file == '.' || $file == '..') continue; if(class_exists($active))
{
$matches = array(); $class = new $active($this->container->get('model.config'));
if (preg_match("/([^\.]+)\.class\.php/", $file, $matches)) { if(!$class instanceof AbstractTlogDestination)
$classname = $matches[1]; {
throw new \UnexpectedValueException($active." must extends Thelia\Tlog\AbstractTlogDestination");
if ( ($actives === false || in_array($classname, $actives)) && ! isset($destinations[$classname])) {
include_once("$dir/$file");
$destinations[$classname] = new $classname();
}
}
} }
@closedir($dh); $destinations[$active] = $class;
} }
} }
} }

View File

@@ -0,0 +1,64 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Log;
class TlogDestinationConfig
{
const TYPE_TEXTAREA = 1;
const TYPE_TEXTFIELD = 2;
public $titre;
public $label;
public $defaut;
public $type;
public $valeur;
public function __construct($nom, $titre, $label, $defaut, $type, $config = null) {
$this->nom = $nom;
$this->titre = $titre;
$this->label = $label;
$this->defaut = $defaut;
$this->type = $type;
// @$this->charger();
if($config)
{
$this->valeur = $config->read($this->nom, $this->defaut);
}
}
// public function charger() {
// // La variable n'existe pas ? La créer en y affectant la valeur par defaut
// if (! parent::charger($this->nom)) {
// $this->valeur = $this->defaut;
// $this->protege = 1;
// $this->cache = 1;
//
// $this->add();
// }
// }
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Thelia\Log;
Interface TlogInterface
{
public function trace();
public function debug();
public function info();
public function warning();
public function error();
public function fatal();
}