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

Adapted logger + unit tests to work on Linux.

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