Created
June 22, 2015 07:38
-
-
Save kevinchappell/09130ee9036f5954ac8f to your computer and use it in GitHub Desktop.
Light Logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Super simple class for logging. Generates regular logs and csv files | |
* @package lightLogger | |
* @author Kevin Chappell <[email protected]> | |
* @license http://opensource.org/licenses/MIT The MIT License (MIT) | |
* @since lightLogger .5 | |
*/ | |
/** | |
* # Log Usage | |
* $log = new Logger(); | |
* $log->error( 'Something went wrong' ); | |
* ## Output | |
* Jun-19-2015 05:53:32 | Error: Something went wrong | |
* | |
* # CSV Usage | |
* $csv = new Logger('my.csv'); | |
* $row = array( 'name', 'email', 'phone' ); | |
* $csv->add_row( $row ); | |
* ## Output | |
* name,email,phone | |
*/ | |
class Logger { | |
private $log_file; | |
private $log = array(); | |
/** | |
* define the log file to be used | |
* @param string $filename | |
*/ | |
public function __construct( $filename = null ) { | |
$log_dir = __DIR__ . '/logs/'; | |
if ( ! file_exists( $log_dir ) ) { | |
mkdir( $log_dir, 0600, true ); | |
} | |
$this->log_file = is_null( $filename ) ? $log_dir.'log' : $log_dir.$filename; | |
} | |
/** | |
* Writes to log file before class is unloaded from memory | |
*/ | |
public function __destruct() { | |
$log_file = fopen( $this->log_file, 'a' ); | |
if ( ! empty( $this->log ) ) { | |
$this->log[] = ''; | |
$log = implode( PHP_EOL, $this->log ); | |
if ( ! fwrite( $log_file, $log ) ) { | |
chmod( $this->log_file, 0600 ); | |
if ( ! fwrite( $log_file, $log ) ) { | |
// log a problem with the logger | |
error_log( 'Could not write to ' . $log_file, 0 ); | |
} | |
} | |
fclose( $log_file ); | |
} | |
} | |
/** | |
* Use overloading to for dynamic log types | |
* @param string $method | |
* @param array $args | |
* @return function returns add_log() | |
*/ | |
public function __call( $method, $args ) { | |
return $this->add_log( ucfirst( $method ), $args[0] ); | |
} | |
/** | |
* Add the timestamped log | |
* @param string $type log type | |
* @param string $text text to be logged | |
*/ | |
public function add_log( $type, $text ) { | |
$date = date( 'M-d-Y H:i:s' ); | |
$this->log[] = "$date | $type: $text"; | |
return true; | |
} | |
/** | |
* add a row to a csv file | |
* @param array $columns array of columns to be added to the CSV | |
*/ | |
public function add_row( $columns ) { | |
$columns = array_map( function( $column ){ | |
return addslashes( $column ); | |
}, $columns ); | |
$this->log[] = implode( ',', $columns ); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment