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
.
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.



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