piątek, 4 września 2009

Zapis logów do pliku w PHP

Ostatnio napisałem sobie Loggera w PHP. Prosta aczkolwiek bardzo przydatna klasa. Poniżej zamieszczam pełny kod.

<?php
define( 'LOGGER_NEW_LINE' , "\r\n" ) ;

class Logger
{
/**
* Jedyna instancja klasy
* @var Logger
*/
private static $_instance = null ; 

/**
* Zwraca jedyną instancję klasy
* 
* @return Logger
*/
public static function getInstance()
{
if( is_null( self::$_instance ) )
{
self::$_instance = new Logger() ;
}

return self::$_instance ;
}

private $absolute_path ;
private $logs_path ;
private $date ;
private $log_file ;

/**
* W konstruktorze następuje połaczenie z bazą danych.
* 
* @return Logger
*/
private function __construct()
{
$this->absolute_path = dirname( __FILE__ ) . '/' ;
$this->logs_path = $this->absolute_path . 'logs/' ;
$this->date = date( 'Y_m_d' ) ;
$this->log_file = $this->logs_path . 'logs_' . $this->date . '.log' ;

$this->clearOldLogs( 5 ) ;
}

/**
* Usuwa stare pliki logów
* @return unknown_type
*/
private function clearOldLogs( $maxHistory )
{
$files = glob( $this->logs_path.'*.log' ) ;

$this->log( $files , __FUNCTION__ , __CLASS__ , __FILE__ , __LINE__ ) ;

// przerwanie usunięcia jeśli plików jest zbyt mało
if( sizeof( $files ) <= $maxHistory )
return ;

for ($i = 0; $i < sizeof( $files ) - $maxHistory; $i++ )
{
unlink( $files[ $i ] ) ;
}
}

/**
* Zapis danych do pliku
* @param $data        Dane do zapisania w logu
* @param $function    Zawsze jako parametr podawać __FUNCTION__
* @param $class    Zawsze jako parametr podawać __CLASS__
* @param $file        Zawsze jako parametr podawać __FILE__
* @param $line        Zawsze jako parametr podawać __LINE__
*/
public function log( $data , $function , $class = null , $file = null , $line = null )
{
ob_start( $log_str ) ;
echo date( 'H:i:s' ) , '    ' , $class , '::' , $function , '    in    ' , $file , '    on line    ' , $line , LOGGER_NEW_LINE ;
var_dump( $data ) ;
echo LOGGER_NEW_LINE , LOGGER_NEW_LINE ;
$log_str = ob_get_contents() ;
ob_end_clean() ;

$log_str = str_replace( array( "\r\n" , "\n" ) , LOGGER_NEW_LINE , $log_str );
file_put_contents( $this->log_file , $log_str , FILE_APPEND ) ;
}
}

?>

A o to przykład użycia:

Logger::getInstance()->log( $someData , __FUNCTION__ , __CLASS__ , __FILE__ , __LINE__ ) ;

Logger zapisuje dane w formie wyświetlanej przez funkcję var_dump.

Brak komentarzy:

Prześlij komentarz