Accueil > > > [PHP5] CLASSE DE LOG
[PHP5] CLASSE DE LOG
Information sur la source
Description
Ceci est une classe de log. La classe en elle-même se trouve dans le répertoire class/class.oLogger.php Les 2 fichiers log.consult.php et log.detail.php sont là pour un exemple d'utilisation. Je les ai extirpé de ma propre interface...donc c'est du bidouillage pour que ça tourne en local lol :-) A vous de bidouiller la css fournie. Mais vous avez déjà une bonne base quand même, un bon exemple d'utilisation des logs créés. Les logs sont déjà créés évidemment. Pour créer les logs, personnellement, je les ai mis dans ma classe DB, dans la méthode effectuant une requête (oDB::query). Je ne logge pas les SELECT, mais ça, c'est un choix :-) Donc, je lance mon log ainsi : if (true === $log && substr (strtoupper (trim ($this->s_db_sql)), 0, 6) !== 'SELECT') { $ologger = new oLogger; $destId = (isset ($_SESSION['dest_id']))?$_SESSION['dest_id']:0; $o logger -> init ($this -> s_db_sql, $destId); } C'est tout! C'est ce petit bout de code qui a généré les quelques logs que je montre ici.
Source
- <?php
- /**
- * class oLogger
- * @author : johan <barbier_johan@hotmail.com>
- * @version : 2006-04-20
- */
- class oLogger {
-
- /**
- * const sLogDir
- * path to the logs
- */
- const sLogDir ='logs';
-
- /**
- * private array aLogs
- * array to store each log line
- */
- private $aLogs = array (
- 'PAGE' => '',
- 'DATE' => '',
- 'QUERY' => '',
- 'TYPE' => ''
- );
-
- /**
- * private array aLevels
- * array to store the query types
- */
- private $aLevels = array (
- 0 => 'UNKNOWN',
- 1 => 'SELECT',
- 2 => 'UPDATE',
- 3 => 'INSERT',
- 4 => 'DELETE'
- );
-
- /**
- * public array aDir
- * array to store all the log folders and log files
- */
- public $aDir = array ();
-
- /**
- * private object oXml
- * a simple_xml object
- */
- private $oXml = null;
-
- /**
- * public function __construct
- * the constructor
- * initailizes the simple_xml object if needed
- * @param (string) file : the xml log file from which will be set the simple_xml object property
- */
- public function __construct ($file = '') {
- if (!empty ($file)) {
- $this -> oXml = simplexml_load_file(self::sLogDir.'/'.$file);
- }
- }
-
- /**
- * public function init
- * initializes the logger
- * gets the sql query, the user id, current date, filename, query type, and builds the aLogs array with all of that
- * @param (string) sSql : the sql query we want to log
- * @param (int) destId : the user id (depends on your system)
- */
- public function init ($sSql, $destId) {
- $page = $_SERVER['PHP_SELF'];
- $this -> checkDir ($destId);
- $date = date ('H:i:s');
- $file = date ('Ymd').'.xml';
- $sSql = trim (preg_replace ('@(\s)+@', ' ', $sSql));
- $aSql = explode (' ', $sSql);
- if (false === ($level = array_search ($aSql[0], $this -> aLevels))) {
- $level = 0;
- }
- $this -> aLogs = array (
- 'PAGE' => $page,
- 'DATE' => $date,
- 'QUERY' => $sSql,
- 'TYPE' => $this -> aLevels[$level]
- );
- $this -> logIt ($file, $destId);
- }
-
- /**
- * private function checkDir
- * used to check if a log folder exists for a given user id. If not, creates it.
- * @param (int) id : the user id
- */
- private function checkDir ($id) {
- if (!file_exists (self::sLogDir.'/'.$id)) {
- mkdir (self::sLogDir.'/'.$id);
- }
- }
-
- /**
- * private function logIt
- * build the xml from the aLogs array, and saves it into the given file
- * if the given file already exists, it appends the new xml to the existing one
- * @param (string) file : the filename in which the xml log will be written
- * @param (int) destId : the user id (depends on your system)
- */
- private function logIt ($file, $destId) {
- if (file_exists (self::sLogDir.'/'.$destId.'/'.$file)) {
- $docXml = DOMDocument::load (self::sLogDir.'/'.$destId.'/'.$file);
- $root = $docXml -> documentElement;
- } else {
- $docXml = new DOMDocument('1.0', 'iso-8859-1');
- $root = $docXml -> createElement ('logs');
- $root = $docXml -> appendChild ($root);
- }
- $log = $docXml -> createElement ('log');
- $log = $root -> appendChild ($log);
- foreach ($this -> aLogs as $clef => $val) {
- $xmlClef = $docXml -> createElement ($clef);
- $xmlClef = $log -> appendChild ($xmlClef);
- $xmlVal = $docXml -> createTextNode ($val);
- $xmlVal = $xmlClef -> appendChild ($xmlVal);
- }
- $docXml -> save (self::sLogDir.'/'.$destId.'/'.$file);
- $this -> aLogs = array ();
- }
-
- /**
- * public function getaDir
- * builds the aDir array, in which are stored all the log folders and log files
- * @param (bool) ordID : if set to true, orders the array by users id ASC
- */
- public function getaDir ($ordID = false) {
- $aDestLogs = scandir (self::sLogDir);
- $aDestLogs = array_splice ($aDestLogs, 2);
- if (true === $ordID) {
- sort ($aDestLogs, SORT_NUMERIC);
- }
- if (!empty ($aDestLogs)) {
- foreach ($aDestLogs as $v) {
- $aFiles = scandir (self::sLogDir.'/'.$v);
- $aFiles = array_splice ($aFiles, 2);
- $this -> aDir[$v] = $aFiles;
- }
- } else {
- $this -> aDir = array ();
- }
- }
-
- /**
- * public function getList
- * builds an array from the oXml simple_xml object with all the values it contains in the $type xml element (the available types are the aLogs array keys)
- * used for the logs UI : with this method, I can display only the UPDATE, or the INSERT, or only a given page on the logged website...
- * @param (string) type : the type on wihch we want to filter. Must be a valid aLogs key.
- */
- public function getList ($type) {
- if (!array_key_exists ($type, $this -> aLogs)) {
- trigger_error ('Type '.$type.' non reconnu', E_USER_ERROR);
- }
- $oTypes = $this -> oXml -> xpath ('log/'.$type);
- $aType = array_unique ($oTypes);
- return $aType;
- }
-
- /**
- * public function getDetail
- * transforms the xml in a log file to html. Could unfortunately not use the XSLTProcessor, because my server did not implement it :-(
- * the html can, be changed, of course. The javascript is a javascript function used to get a filter, if needed.
- * @param (bool) ord : if set to true, we reverse the xml; as the xml is logged chronologically, we will reverse the dates.
- * @param (string) type : if not empty, we filter on that type.
- * @param (string) page : if not empty, we filter on that page.
- */
- public function getDetail ($ord = false, $type = '', $page = '') {
- $sXml = '';
- $oLignes = $this -> oXml -> xpath ('log');
- if (true === $ord) {
- $oLignes = array_reverse ($oLignes);
- }
- $iCpt = 0;
- foreach ($oLignes as $log) {
- if (!empty ($type) && $log -> TYPE != $type) {
- continue;
- }
- if (!empty ($page) && $log -> PAGE != $page) {
- continue;
- }
- $sColor = ($iCpt%2) ? 'ct1' : 'ct2';
- $sXml .= <<<HTML
- <tr>
- <td class="$sColor">{$log -> DATE}</td>
- <td class="$sColor"><a href="javascript:filtrePage('{$log -> PAGE}');">{$log -> PAGE}</a></td>
- <td class="$sColor"><a href="javascript:filtreType('{$log -> TYPE}');">{$log -> TYPE}</a></td>
- <td class="$sColor">{$log -> QUERY}</td>
- </tr>
- HTML;
- $iCpt ++;
- }
- return $sXml;
- }
- }
-
- ?>
<?php
/**
* class oLogger
* @author : johan <barbier_johan@hotmail.com>
* @version : 2006-04-20
*/
class oLogger {
/**
* const sLogDir
* path to the logs
*/
const sLogDir ='logs';
/**
* private array aLogs
* array to store each log line
*/
private $aLogs = array (
'PAGE' => '',
'DATE' => '',
'QUERY' => '',
'TYPE' => ''
);
/**
* private array aLevels
* array to store the query types
*/
private $aLevels = array (
0 => 'UNKNOWN',
1 => 'SELECT',
2 => 'UPDATE',
3 => 'INSERT',
4 => 'DELETE'
);
/**
* public array aDir
* array to store all the log folders and log files
*/
public $aDir = array ();
/**
* private object oXml
* a simple_xml object
*/
private $oXml = null;
/**
* public function __construct
* the constructor
* initailizes the simple_xml object if needed
* @param (string) file : the xml log file from which will be set the simple_xml object property
*/
public function __construct ($file = '') {
if (!empty ($file)) {
$this -> oXml = simplexml_load_file(self::sLogDir.'/'.$file);
}
}
/**
* public function init
* initializes the logger
* gets the sql query, the user id, current date, filename, query type, and builds the aLogs array with all of that
* @param (string) sSql : the sql query we want to log
* @param (int) destId : the user id (depends on your system)
*/
public function init ($sSql, $destId) {
$page = $_SERVER['PHP_SELF'];
$this -> checkDir ($destId);
$date = date ('H:i:s');
$file = date ('Ymd').'.xml';
$sSql = trim (preg_replace ('@(\s)+@', ' ', $sSql));
$aSql = explode (' ', $sSql);
if (false === ($level = array_search ($aSql[0], $this -> aLevels))) {
$level = 0;
}
$this -> aLogs = array (
'PAGE' => $page,
'DATE' => $date,
'QUERY' => $sSql,
'TYPE' => $this -> aLevels[$level]
);
$this -> logIt ($file, $destId);
}
/**
* private function checkDir
* used to check if a log folder exists for a given user id. If not, creates it.
* @param (int) id : the user id
*/
private function checkDir ($id) {
if (!file_exists (self::sLogDir.'/'.$id)) {
mkdir (self::sLogDir.'/'.$id);
}
}
/**
* private function logIt
* build the xml from the aLogs array, and saves it into the given file
* if the given file already exists, it appends the new xml to the existing one
* @param (string) file : the filename in which the xml log will be written
* @param (int) destId : the user id (depends on your system)
*/
private function logIt ($file, $destId) {
if (file_exists (self::sLogDir.'/'.$destId.'/'.$file)) {
$docXml = DOMDocument::load (self::sLogDir.'/'.$destId.'/'.$file);
$root = $docXml -> documentElement;
} else {
$docXml = new DOMDocument('1.0', 'iso-8859-1');
$root = $docXml -> createElement ('logs');
$root = $docXml -> appendChild ($root);
}
$log = $docXml -> createElement ('log');
$log = $root -> appendChild ($log);
foreach ($this -> aLogs as $clef => $val) {
$xmlClef = $docXml -> createElement ($clef);
$xmlClef = $log -> appendChild ($xmlClef);
$xmlVal = $docXml -> createTextNode ($val);
$xmlVal = $xmlClef -> appendChild ($xmlVal);
}
$docXml -> save (self::sLogDir.'/'.$destId.'/'.$file);
$this -> aLogs = array ();
}
/**
* public function getaDir
* builds the aDir array, in which are stored all the log folders and log files
* @param (bool) ordID : if set to true, orders the array by users id ASC
*/
public function getaDir ($ordID = false) {
$aDestLogs = scandir (self::sLogDir);
$aDestLogs = array_splice ($aDestLogs, 2);
if (true === $ordID) {
sort ($aDestLogs, SORT_NUMERIC);
}
if (!empty ($aDestLogs)) {
foreach ($aDestLogs as $v) {
$aFiles = scandir (self::sLogDir.'/'.$v);
$aFiles = array_splice ($aFiles, 2);
$this -> aDir[$v] = $aFiles;
}
} else {
$this -> aDir = array ();
}
}
/**
* public function getList
* builds an array from the oXml simple_xml object with all the values it contains in the $type xml element (the available types are the aLogs array keys)
* used for the logs UI : with this method, I can display only the UPDATE, or the INSERT, or only a given page on the logged website...
* @param (string) type : the type on wihch we want to filter. Must be a valid aLogs key.
*/
public function getList ($type) {
if (!array_key_exists ($type, $this -> aLogs)) {
trigger_error ('Type '.$type.' non reconnu', E_USER_ERROR);
}
$oTypes = $this -> oXml -> xpath ('log/'.$type);
$aType = array_unique ($oTypes);
return $aType;
}
/**
* public function getDetail
* transforms the xml in a log file to html. Could unfortunately not use the XSLTProcessor, because my server did not implement it :-(
* the html can, be changed, of course. The javascript is a javascript function used to get a filter, if needed.
* @param (bool) ord : if set to true, we reverse the xml; as the xml is logged chronologically, we will reverse the dates.
* @param (string) type : if not empty, we filter on that type.
* @param (string) page : if not empty, we filter on that page.
*/
public function getDetail ($ord = false, $type = '', $page = '') {
$sXml = '';
$oLignes = $this -> oXml -> xpath ('log');
if (true === $ord) {
$oLignes = array_reverse ($oLignes);
}
$iCpt = 0;
foreach ($oLignes as $log) {
if (!empty ($type) && $log -> TYPE != $type) {
continue;
}
if (!empty ($page) && $log -> PAGE != $page) {
continue;
}
$sColor = ($iCpt%2) ? 'ct1' : 'ct2';
$sXml .= <<<HTML
<tr>
<td class="$sColor">{$log -> DATE}</td>
<td class="$sColor"><a href="javascript:filtrePage('{$log -> PAGE}');">{$log -> PAGE}</a></td>
<td class="$sColor"><a href="javascript:filtreType('{$log -> TYPE}');">{$log -> TYPE}</a></td>
<td class="$sColor">{$log -> QUERY}</td>
</tr>
HTML;
$iCpt ++;
}
return $sXml;
}
}
?>
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Classe XML pour php4 [ par dandy54 ]
Salut !Exist-t-il une classe compatible avec php4 pour manipuler les ficheirs Xml et si possible aussi simple que SimpleXml (oui je suis exigeant) ??M
Visibilité des membres d'une classe avec autoload ? [ par petitelarve ]
Bonjour, ca m'énérve !!! J'ai une classe que je veut instancier dans un autre script avec autoload. L'objectif étant de récupé
php - intranet - MysqL [ par ben272 ]
Bonsoir à tous, j'ai quelques questions à poser. Voilà dans mon collège on va mettre en place un intranet ( section informatique seulement ),et c'est
Lecture de fichier XML [ par stigmate101 ]
Bonjour,J'ai écris un code qui dois chercher un enregistrement dans un fichier XML. Ce code ne me m'affiche rien et ne me retourne pas d'erreur! Cl
Appel d'une classe dans une classe [ par qntoinOo ]
Bonjour à tous,Je suis face à un petit problème, je fait appel dans mon site à plusieurs classes une pour mes requêtes mysql, une pour mon système de
classe générique pour parser tout type de fichier xml [ par mams004 ]
Bonjour, je cherche desespérement une classe php générique pour parser tout type de ficher XML Si vous connaisser des liens ou tuto? merci pour
Faut il un parseur XML ou tout réécrire ? [ par slhuilli ]
Bonjour, Je bosse sur un flux XML que je trouve très bizarre (mais c'est peut etre moi qui me trompe !). Ce flux est généré par google meteo. Je vous
probleme d'instance de classe [ par gretata ]
bonjour a tous !! j'ai un problème au niveau des objets en PHP, je ne comprend pas bien comment ils fonctionnent. j'essai de faire un get sur un obj
Erreur xml [ par ouzb ]
Bonjour je veux recuperer des infos envoyez par un client en xml. Le client utilise curl pour les envoyer et je dois le recuperer en php par une métho
J'aurai besoin d'un peut d'aide svp [ par Underskill ]
Bonsoir J'aurais besoin d'aide. Je n'arrive pas afficher les fonction correctement pour afficher le script esceque vous pouriez m'aider svp Le script
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|