Una clase php para hacer archivos log

4 05 2009

Actualmente estoy trabajando en un sistema legacy de PHP,  en algunas partes del código quiero saber que hay en las variables, si trato de hacer un var_dump / print_r no sale nunca en pantalla, me dirán “pero existe xdebug”, en efecto existe pero algunas veces si hay mod_rewrite no funciona bien por lo que no sirve de nada.

Para eso me cree una clase pequeña, que permite crear un archivo de log a el cual le agrega la hora y fecha además si es una arreglo lo muestra formateado, a éste archivo de log se le dice el path y el te va a decir si puede crearlo o no, además va a agregar linea tras linea, asi que cuidado de dejarlo habilitado porque despues de más 1.000.000 puede hacerse grande el archivo :P .

El codigo de archivo:

< ?php

	/**
	 * myLogger
	 * @author Edder Rojas Douglas
	 * @version 0.2
	 */

	class myLogger  {

		protected $_path;
		protected $_fileName = 'myLogger.log';

		/**
		 * @param string $path can be a directory o a file path
		 */
		public function __construct($path) {
			if (empty($path)){
				Throw new Exception("Path must be filled");
			}
			if (!file_exists($path)) {
				Throw new Exception("The Path doesn't exists.");
			}
			if (!is_writeable($path)) {
				Throw new Exception("You can write on the give path");
			}
			$this->_path = $this->_parsePath($path);
		}	

		/**
		 * Validate the path the add the filename to the path
		 * @param String $path
		 * @return String
		 */
		protected function _parsePath($path) {
			$strLenght = strlen($path);
        	$lastChar = substr($path, $strLenght - 1, $strLenght);
        	$path = $lastChar != "/" ? $path . "/" : $path;

        	if ( is_dir($path) ) {
        		return $path . $this->_fileName;
        	} else {
        		return $path;
        	}
		}

		/**
		 * Will save the path on the give path
		 * @param String $line
		 */
		protected function _save($line) {
			$fhandle = fopen($this->_path, "a+");
			fwrite($fhandle, $line);
			fclose($fhandle);
		}

		/**
		 * main function to add lines to the logging file
		 * @param String $line
		 */
		public function addLine($line){
			$line = is_array($line) ? print_r($line, true) : $line;
			$line = date("d-m-Y h:i:s") . ": $line\n";
			$this->_save($line);
		}
	}

Su utilización es sencilla:

// cargar la clasesita
require_once('myLogger.php');

$log = new myLogger(dirname(__FILE__) . "/tmp");
$log->addLine(array("testing", "my", 'data'));
// si en éste punto no muestra errores, todo bien =D

Actualización: Hice unas pequeñas modificaciones para mostrar mejor los resultados si lo que se loguea es un objecto.


Acciones

Información

4 respuestas

16 06 2009
Clase de Logs para PHP

[...] Vía: Pain Dev [...]

24 06 2010
24 06 2010
Esther32

Felicidades por el blog, aquí http://www.vertutoriales.com/index.php/tag/php/ y otra qa que no recuerdo ahora

12 07 2010
Paulo McNally

Con esto me basto.

Muchas gracias por el ejemplo. Saludos

Deja un comentario

Fill in your details below or click an icon to log in:

Logo de WordPress.com

You are commenting using your WordPress.com account. Log Out / Cambiar )

Twitter picture

You are commenting using your Twitter account. Log Out / Cambiar )

Facebook photo

You are commenting using your Facebook account. Log Out / Cambiar )

Connecting to %s




Seguir

Get every new post delivered to your Inbox.

Únete a otros 33 seguidores