Commit b506859d authored by Taddeüs Kroes's avatar Taddeüs Kroes

Adapted logger + unit tests to work on Linux.

parent 20bfea03
<?php <?php
/** /**
* Logging functions. * Logging functions.
* *
* @author Taddeus Kroes * @author Taddeus Kroes
* @date 13-07-2012 * @date 13-07-2012
*/ */
...@@ -11,10 +11,10 @@ namespace WebBasics; ...@@ -11,10 +11,10 @@ namespace WebBasics;
require_once 'base.php'; require_once 'base.php';
/** /**
* Logger class. * Logger class.
* *
* A Logger object provides five functions to process log messages. * A Logger object provides five functions to process log messages.
* *
* @package WebBasics * @package WebBasics
*/ */
class Logger extends Base { class Logger extends Base {
...@@ -24,93 +24,93 @@ class Logger extends Base { ...@@ -24,93 +24,93 @@ class Logger extends Base {
const INFO = 3; const INFO = 3;
const DEBUG = 4; const DEBUG = 4;
static $level_names = array('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'); static $level_names = array('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG');
private static $allowed_dump_formats = array('plain', 'html', 'file'); private static $allowed_dump_formats = array('plain', 'html', 'file', 'none');
const DEFAULT_FORMAT = '%(datetime): %(level): %(message)'; const DEFAULT_FORMAT = '%(datetime): %(level): %(message)';
private $properties = array(); private $properties = array();
private $output = array(); private $output = array();
private $format = self::DEFAULT_FORMAT; private $format = self::DEFAULT_FORMAT;
private $level = self::WARNING; private $level = self::WARNING;
private $dump_format = 'plain'; private $dump_format = 'plain';
private $log_directory = ''; private $log_directory = '';
function set_directory($directory) { function set_directory($directory) {
$this->log_directory = self::path_with_slash($directory); $this->log_directory = self::path_with_slash($directory);
} }
function set_dump_format($format) { function set_dump_format($format) {
if( !in_array($format, self::$allowed_dump_formats) ) if( !in_array($format, self::$allowed_dump_formats) )
throw new \InvalidArgumentException(sprintf('', $format)); throw new \InvalidArgumentException(sprintf('', $format));
$this->dump_format = $format; $this->dump_format = $format;
} }
function set_format($format) { function set_format($format) {
$this->format = (string)$format; $this->format = (string)$format;
} }
function get_format() { function get_format() {
return $this->format; return $this->format;
} }
function get_level() { function get_level() {
return $this->level; return $this->level;
} }
function get_level_name() { function get_level_name() {
return self::$level_names[$this->level]; return self::$level_names[$this->level];
} }
function set_level($level) { function set_level($level) {
if( is_string($level) ) { if( is_string($level) ) {
$level = strtoupper($level); $level = strtoupper($level);
if( !defined('self::'.$level) ) if( !defined('self::'.$level) )
throw new \InvalidArgumentException(sprintf('Invalid debug level %s.', $level)); throw new \InvalidArgumentException(sprintf('Invalid debug level %s.', $level));
$level = constant('self::'.$level); $level = constant('self::'.$level);
} }
if( $level < self::CRITICAL || $level > self::DEBUG ) if( $level < self::CRITICAL || $level > self::DEBUG )
throw new \InvalidArgumentException(sprintf('Invalid debug level %d.', $level)); throw new \InvalidArgumentException(sprintf('Invalid debug level %d.', $level));
$this->level = $level; $this->level = $level;
} }
function set_property($name, $value) { function set_property($name, $value) {
$this->properties[$name] = (string)$value; $this->properties[$name] = (string)$value;
} }
function critical($message) { function critical($message) {
$this->process($message, self::CRITICAL); $this->process($message, self::CRITICAL);
} }
function error($message) { function error($message) {
$this->process($message, self::ERROR); $this->process($message, self::ERROR);
} }
function warning($message) { function warning($message) {
$this->process($message, self::WARNING); $this->process($message, self::WARNING);
} }
function info($message) { function info($message) {
$this->process($message, self::INFO); $this->process($message, self::INFO);
} }
function debug($message) { function debug($message) {
$this->process($message, self::DEBUG); $this->process($message, self::DEBUG);
} }
private function process($message, $level) { private function process($message, $level) {
if( $level <= $this->level ) if( $level <= $this->level )
$this->output[] = array($message, $level); $this->output[] = array($message, $level);
} }
function dumps() { function dumps() {
$logger = $this; $logger = $this;
$output = ''; $output = '';
foreach( $this->output as $i => $tuple ) { foreach( $this->output as $i => $tuple ) {
list($message, $level) = $tuple; list($message, $level) = $tuple;
$i && $output .= "\n"; $i && $output .= "\n";
...@@ -118,24 +118,26 @@ class Logger extends Base { ...@@ -118,24 +118,26 @@ class Logger extends Base {
'/%\(([a-z-_ ]*)\)/i', '/%\(([a-z-_ ]*)\)/i',
function ($matches) use ($logger, $message, $level) { function ($matches) use ($logger, $message, $level) {
$name = $matches[1]; $name = $matches[1];
if( $name == 'message' ) if( $name == 'message' )
return $message; return $message;
if( $name == 'level' ) if( $name == 'level' )
return Logger::$level_names[$level]; return Logger::$level_names[$level];
return $logger->get_formatted_property($matches[1]); return $logger->get_formatted_property($matches[1]);
}, },
$this->format $this->format
); );
} }
return $output; return $output;
} }
function dump($file_prefix='log') { function dump($file_prefix='log') {
switch( $this->dump_format ) { switch( $this->dump_format ) {
case 'none':
return;
case 'plain': case 'plain':
echo $this->dumps(); echo $this->dumps();
break; break;
...@@ -147,36 +149,36 @@ class Logger extends Base { ...@@ -147,36 +149,36 @@ class Logger extends Base {
$this->save(sprintf('%s_%s.log', $file_prefix, strftime('%d-%m-%Y_%H-%M-%S'))); $this->save(sprintf('%s_%s.log', $file_prefix, strftime('%d-%m-%Y_%H-%M-%S')));
} }
} }
function clear() { function clear() {
$this->output = array(); $this->output = array();
} }
function save($path) { function save($path) {
if( $this->log_directory && !is_dir($this->log_directory) ) if( $this->log_directory && !is_dir($this->log_directory) )
mkdir($this->log_directory, 0644, true); mkdir($this->log_directory, 0777, true);
file_put_contents($this->log_directory . $path, $this->dumps()); file_put_contents($this->log_directory . $path, $this->dumps());
} }
function handle_exception(\Exception $e) { function handle_exception(\Exception $e) {
if( $e === null ) if( $e === null )
return; return;
$message = sprintf("Uncaught %s in file %s, line %d: %s\n\n%s", get_class($e), $message = sprintf("Uncaught %s in file %s, line %d: %s\n\n%s", get_class($e),
$e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString()); $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString());
$this->critical($message); $this->critical($message);
$this->dump('error'); $this->dump('error');
} }
function set_as_exception_handler() { function set_as_exception_handler() {
set_exception_handler(array($this, 'handle_exception')); set_exception_handler(array($this, 'handle_exception'));
} }
function get_formatted_property($property) { function get_formatted_property($property) {
if( isset($this->properties[$property]) ) if( isset($this->properties[$property]) )
return $this->properties[$property]; return $this->properties[$property];
switch( $property ) { switch( $property ) {
case 'loglevel': case 'loglevel':
return $this->get_level_name(); return $this->get_level_name();
...@@ -187,9 +189,9 @@ class Logger extends Base { ...@@ -187,9 +189,9 @@ class Logger extends Base {
case 'datetime': case 'datetime':
return strftime('%d-%m-%Y %H:%M:%S'); return strftime('%d-%m-%Y %H:%M:%S');
} }
throw new \InvalidArgumentException(sprintf('Invalid logging property "%s".', $property)); throw new \InvalidArgumentException(sprintf('Invalid logging property "%s".', $property));
} }
} }
?> ?>
\ No newline at end of file
...@@ -13,47 +13,47 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -13,47 +13,47 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->logger = new Logger(); $this->logger = new Logger();
$this->logger->set_property('name', NAME); $this->logger->set_property('name', NAME);
$this->logger->set_format(FORMAT); $this->logger->set_format(FORMAT);
is_dir('build') || mkdir('build'); is_dir('build') || mkdir('build');
} }
function assert_dumps($expected) { function assert_dumps($expected) {
$this->assertEquals($this->logger->dumps(), $expected); $this->assertEquals($this->logger->dumps(), $expected);
} }
function test_set_directory() { function test_set_directory() {
$this->logger->set_directory('logs'); $this->logger->set_directory('logs');
$this->assertAttributeEquals('logs/', 'log_directory', $this->logger); $this->assertAttributeEquals('logs/', 'log_directory', $this->logger);
$this->logger->set_directory('logs/'); $this->logger->set_directory('logs/');
$this->assertAttributeEquals('logs/', 'log_directory', $this->logger); $this->assertAttributeEquals('logs/', 'log_directory', $this->logger);
} }
function test_set_format() { function test_set_format() {
$this->logger->set_format('foo'); $this->logger->set_format('foo');
$this->assertAttributeEquals('foo', 'format', $this->logger); $this->assertAttributeEquals('foo', 'format', $this->logger);
} }
function test_set_dump_format_success() { function test_set_dump_format_success() {
$this->logger->set_dump_format('html'); $this->logger->set_dump_format('html');
$this->assertAttributeEquals('html', 'dump_format', $this->logger); $this->assertAttributeEquals('html', 'dump_format', $this->logger);
} }
/** /**
* @expectedException InvalidArgumentException * @expectedException InvalidArgumentException
*/ */
function test_set_dump_format_failure() { function test_set_dump_format_failure() {
$this->logger->set_dump_format('foo'); $this->logger->set_dump_format('foo');
} }
function test_get_format() { function test_get_format() {
$this->assertEquals($this->logger->get_format(), FORMAT); $this->assertEquals($this->logger->get_format(), FORMAT);
} }
function test_get_level() { function test_get_level() {
$this->assertEquals($this->logger->get_level(), Logger::WARNING); $this->assertEquals($this->logger->get_level(), Logger::WARNING);
$this->assertEquals($this->logger->get_level_name(), 'WARNING'); $this->assertEquals($this->logger->get_level_name(), 'WARNING');
} }
/** /**
* @depends test_get_level * @depends test_get_level
*/ */
...@@ -67,17 +67,17 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -67,17 +67,17 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->logger->set_level(Logger::ERROR); $this->logger->set_level(Logger::ERROR);
$this->assertEquals($this->logger->get_level(), Logger::ERROR); $this->assertEquals($this->logger->get_level(), Logger::ERROR);
} }
function test_format() { function test_format() {
$this->logger->error('test message'); $this->logger->error('test message');
$this->assert_dumps('ERROR: test message'); $this->assert_dumps('ERROR: test message');
} }
function test_set_property() { function test_set_property() {
$this->logger->set_property('name', 'Logger'); $this->logger->set_property('name', 'Logger');
$this->assertEquals($this->logger->get_formatted_property('name'), 'Logger'); $this->assertEquals($this->logger->get_formatted_property('name'), 'Logger');
} }
/** /**
* @depends test_format * @depends test_format
*/ */
...@@ -86,7 +86,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -86,7 +86,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->logger->clear(); $this->logger->clear();
$this->assert_dumps(''); $this->assert_dumps('');
} }
/** /**
* @depends test_set_level * @depends test_set_level
* @depends test_clear * @depends test_clear
...@@ -103,7 +103,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -103,7 +103,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->logger->debug('test message'); $this->logger->debug('test message');
$this->assert_dumps('DEBUG: test message'); $this->assert_dumps('DEBUG: test message');
} }
function test_get_formatted_property() { function test_get_formatted_property() {
$this->assertEquals($this->logger->get_formatted_property('name'), NAME); $this->assertEquals($this->logger->get_formatted_property('name'), NAME);
$this->assertEquals($this->logger->get_formatted_property('loglevel'), 'WARNING'); $this->assertEquals($this->logger->get_formatted_property('loglevel'), 'WARNING');
...@@ -116,13 +116,13 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -116,13 +116,13 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->setExpectedException('\InvalidArgumentException'); $this->setExpectedException('\InvalidArgumentException');
$this->logger->get_formatted_property('foo'); $this->logger->get_formatted_property('foo');
} }
function test_dumps_property_format() { function test_dumps_property_format() {
$this->logger->warning('test message'); $this->logger->warning('test message');
$this->logger->set_format('%(name): %(level): %(message)'); $this->logger->set_format('%(name): %(level): %(message)');
$this->assert_dumps(NAME.': WARNING: test message'); $this->assert_dumps(NAME.': WARNING: test message');
} }
/** /**
* @depends test_process_level * @depends test_process_level
*/ */
...@@ -131,7 +131,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -131,7 +131,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->expectOutputString('WARNING: test message'); $this->expectOutputString('WARNING: test message');
$this->logger->dump(); $this->logger->dump();
} }
/** /**
* @depends test_process_level * @depends test_process_level
*/ */
...@@ -141,7 +141,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -141,7 +141,7 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->expectOutputString('<strong>Log:</strong><br /><pre>WARNING: test message</pre>'); $this->expectOutputString('<strong>Log:</strong><br /><pre>WARNING: test message</pre>');
$this->logger->dump(); $this->logger->dump();
} }
function test_save() { function test_save() {
$this->logger->warning('test message'); $this->logger->warning('test message');
$this->logger->save(LOGFILE); $this->logger->save(LOGFILE);
...@@ -151,20 +151,20 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -151,20 +151,20 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
$this->assertStringEqualsFile(LOGFILE, "WARNING: test message\nWARNING: another test message"); $this->assertStringEqualsFile(LOGFILE, "WARNING: test message\nWARNING: another test message");
unlink(LOGFILE); unlink(LOGFILE);
} }
function find_logfile() { function find_logfile() {
$files = scandir(LOGDIR); $files = scandir(LOGDIR);
$this->assertEquals(3, count($files)); $this->assertEquals(3, count($files));
return $files[2]; return $files[2];
} }
/** /**
* @depends test_save * @depends test_save
*/ */
function test_dump_file_regular() { function test_dump_file_regular() {
$this->logger->set_directory(LOGDIR); $this->logger->set_directory(LOGDIR);
$this->logger->set_dump_format('file'); $this->logger->set_dump_format('file');
$this->logger->warning('test message'); $this->logger->warning('test message');
$this->logger->dump(); $this->logger->dump();
$filename = $this->find_logfile(); $filename = $this->find_logfile();
...@@ -172,26 +172,12 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase { ...@@ -172,26 +172,12 @@ class LoggerTest extends PHPUnit_Extensions_OutputTestCase {
unlink(LOGDIR . $filename); unlink(LOGDIR . $filename);
$this->assertRegExp('/^log_\d{2}-\d{2}-\d{4}_\d{2}-\d{2}-\d{2}.log$/', $filename); $this->assertRegExp('/^log_\d{2}-\d{2}-\d{4}_\d{2}-\d{2}-\d{2}.log$/', $filename);
} }
/**
* @depends test_dump_file_regular
*/
function test_dump_file_prefix() {
$this->logger->set_directory(LOGDIR);
$this->logger->set_dump_format('file');
$this->logger->warning('test message');
$this->logger->dump('error');
$filename = $this->find_logfile();
$this->assertStringEqualsFile(LOGDIR . $filename, 'WARNING: test message');
unlink(LOGDIR . $filename);
$this->assertRegExp('/^error_\d{2}-\d{2}-\d{4}_\d{2}-\d{2}-\d{2}.log$/', $filename);
}
function test_handle_exception() { function test_handle_exception() {
$this->logger->handle_exception(new Exception('test message')); $this->logger->set_dump_format('none');
$this->logger->handle_exception(new RuntimeException('test message'));
$this->assertNotEquals($this->logger->dumps(), ''); $this->assertNotEquals($this->logger->dumps(), '');
} }
} }
?> ?>
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment