Last active
October 2, 2015 13:38
-
-
Save kanduvisla/2251545 to your computer and use it in GitHub Desktop.
Small Logger Class
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 | |
/* | |
* SmallLog | |
* | |
* Usage: | |
* | |
* SmallLog::instance()->setPath('path/to/log/directory'); | |
* SmallLog::add('This line is added to the log'); | |
* SmallLog::add('This line too'); | |
* SmallLog::write('logfile.log'); | |
*/ | |
// Comment this line to disable error logging: | |
set_error_handler(array('SmallLog', 'errorHandlerCallback')); | |
class SmallLog | |
{ | |
private $_log; | |
private $_path; | |
protected static $_instance; | |
private function __construct() | |
{ | |
$this->_log = array(); | |
} | |
/** | |
* @static | |
* @return SmallLog | |
*/ | |
public static function instance() | |
{ | |
if(!self::$_instance) | |
{ | |
self::$_instance = new SmallLog(); | |
} | |
return self::$_instance; | |
} | |
/** | |
* Set the path where the logs are stored. | |
* @param $path | |
*/ | |
public function setPath($path) | |
{ | |
$this->_path = $path; | |
} | |
/** | |
* Add a line to the log | |
* @param $line | |
*/ | |
public function add($line) | |
{ | |
$this->_log[] = '['.date('Y-m-d H:i:s').'] : '.$line; | |
} | |
/** | |
* Write the log | |
* @param string $file filename | |
* @param bool $appendDate append the date to the filename | |
*/ | |
public function write($file, $appendDate = true) | |
{ | |
if($appendDate) | |
{ | |
$info = pathinfo($this->_path.'/'.$file); | |
$path = $info['dirname'].'/'.$info['filename'].'.'.strftime('%Y-%m-%d', time()).'.'.$info['extension']; | |
} else { | |
$path = $this->_path.'/'.$file; | |
} | |
file_put_contents($path, implode("\n", $this->_log)."\n\n---\n\n", FILE_APPEND); | |
} | |
/** | |
* Public function to output log in case of a script-stopping-error | |
* @param $code | |
* @param $string | |
* @param $file | |
* @param $line | |
* @param $context | |
*/ | |
public static function errorHandlerCallback($code, $string, $file, $line, $context) | |
{ | |
self::instance()->add('!!! Fatal Error !!!'); | |
self::instance()->add('code: '.$code); | |
self::instance()->add('string: '.$string); | |
self::instance()->add('file: '.$file); | |
self::instance()->add('line: '.$line); | |
self::instance()->write('error.log'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment