Fixed code formatting to conform to PSR-2
Used the PHP Coding Standards Fixer by Sensio Labs
(http://cs.sensiolabs.org/).
Signed-off-by: Ivan Habunek <ivan.habunek@gmail.com>
diff --git a/src/AppenderPool.php b/src/AppenderPool.php
index ca57179..92f9455 100644
--- a/src/AppenderPool.php
+++ b/src/AppenderPool.php
@@ -28,70 +28,77 @@
* appender can be linked to multiple loggers. This makes sure duplicate
* appenders are not created.
*/
-class AppenderPool {
+class AppenderPool
+{
+ /** Holds appenders indexed by their name */
+ public static $appenders = array();
- /** Holds appenders indexed by their name */
- public static $appenders = array();
+ /**
+ * Adds an appender to the pool.
+ * The appender must be named for this operation.
+ * @param Appender $appender
+ */
+ public static function add(AbstractAppender $appender)
+ {
+ $name = $appender->getName();
- /**
- * Adds an appender to the pool.
- * The appender must be named for this operation.
- * @param Appender $appender
- */
- public static function add(AbstractAppender $appender) {
- $name = $appender->getName();
+ if (empty($name)) {
+ trigger_error('log4php: Cannot add unnamed appender to pool.', E_USER_WARNING);
- if(empty($name)) {
- trigger_error('log4php: Cannot add unnamed appender to pool.', E_USER_WARNING);
- return;
- }
+ return;
+ }
- if (isset(self::$appenders[$name])) {
- trigger_error("log4php: Appender [$name] already exists in pool. Overwriting existing appender.", E_USER_WARNING);
- }
+ if (isset(self::$appenders[$name])) {
+ trigger_error("log4php: Appender [$name] already exists in pool. Overwriting existing appender.", E_USER_WARNING);
+ }
- self::$appenders[$name] = $appender;
- }
+ self::$appenders[$name] = $appender;
+ }
- /**
- * Retrieves an appender from the pool by name.
- * @param string $name Name of the appender to retrieve.
- * @return Appender The named appender or NULL if no such appender
- * exists in the pool.
- */
- public static function get($name) {
- return isset(self::$appenders[$name]) ? self::$appenders[$name] : null;
- }
+ /**
+ * Retrieves an appender from the pool by name.
+ * @param string $name Name of the appender to retrieve.
+ * @return Appender The named appender or NULL if no such appender
+ * exists in the pool.
+ */
+ public static function get($name)
+ {
+ return isset(self::$appenders[$name]) ? self::$appenders[$name] : null;
+ }
- /**
- * Removes an appender from the pool by name.
- * @param string $name Name of the appender to remove.
- */
- public static function delete($name) {
- unset(self::$appenders[$name]);
- }
+ /**
+ * Removes an appender from the pool by name.
+ * @param string $name Name of the appender to remove.
+ */
+ public static function delete($name)
+ {
+ unset(self::$appenders[$name]);
+ }
- /**
- * Returns all appenders from the pool.
- * @return array Array of Appender objects.
- */
- public static function getAppenders() {
- return self::$appenders;
- }
+ /**
+ * Returns all appenders from the pool.
+ * @return array Array of Appender objects.
+ */
+ public static function getAppenders()
+ {
+ return self::$appenders;
+ }
- /**
- * Checks whether an appender exists in the pool.
- * @param string $name Name of the appender to look for.
- * @return boolean TRUE if the appender with the given name exists.
- */
- public static function exists($name) {
- return isset(self::$appenders[$name]);
- }
+ /**
+ * Checks whether an appender exists in the pool.
+ * @param string $name Name of the appender to look for.
+ * @return boolean TRUE if the appender with the given name exists.
+ */
+ public static function exists($name)
+ {
+ return isset(self::$appenders[$name]);
+ }
- /**
- * Clears all appenders from the pool.
- */
- public static function clear() {
- self::$appenders = array();
- }
-}
\ No newline at end of file
+ /**
+ * Clears all appenders from the pool.
+ */
+ public static function clear()
+ {
+ self::$appenders = array();
+ }
+}
diff --git a/src/Appenders/AbstractAppender.php b/src/Appenders/AbstractAppender.php
index 9ac29e1..52ffe07 100644
--- a/src/Appenders/AbstractAppender.php
+++ b/src/Appenders/AbstractAppender.php
@@ -26,263 +26,283 @@
/**
* Abstract class that defines output logs strategies.
*/
-abstract class AbstractAppender extends Configurable {
+abstract class AbstractAppender extends Configurable
+{
+ /**
+ * Set to true when the appender is closed. A closed appender will not
+ * accept any logging requests.
+ * @var boolean
+ */
+ protected $closed = false;
- /**
- * Set to true when the appender is closed. A closed appender will not
- * accept any logging requests.
- * @var boolean
- */
- protected $closed = false;
+ /**
+ * The first filter in the filter chain.
+ * @var AbstractFilter
+ */
+ protected $filter;
- /**
- * The first filter in the filter chain.
- * @var AbstractFilter
- */
- protected $filter;
+ /**
+ * The appender's layout. Can be null if the appender does not use
+ * a layout.
+ * @var Layout
+ */
+ protected $layout;
- /**
- * The appender's layout. Can be null if the appender does not use
- * a layout.
- * @var Layout
- */
- protected $layout;
+ /**
+ * Appender name. Used by other components to identify this appender.
+ * @var string
+ */
+ protected $name;
- /**
- * Appender name. Used by other components to identify this appender.
- * @var string
- */
- protected $name;
+ /**
+ * Appender threshold level. Events whose level is below the threshold
+ * will not be logged.
+ * @var Level
+ */
+ protected $threshold;
- /**
- * Appender threshold level. Events whose level is below the threshold
- * will not be logged.
- * @var Level
- */
- protected $threshold;
+ /**
+ * Set to true if the appender requires a layout.
+ *
+ * True by default, appenders which do not use a layout should override
+ * this property to false.
+ *
+ * @var boolean
+ */
+ protected $requiresLayout = true;
- /**
- * Set to true if the appender requires a layout.
- *
- * True by default, appenders which do not use a layout should override
- * this property to false.
- *
- * @var boolean
- */
- protected $requiresLayout = true;
+ /**
+ * Default constructor.
+ * @param string $name Appender name
+ */
+ public function __construct($name = '')
+ {
+ $this->name = $name;
- /**
- * Default constructor.
- * @param string $name Appender name
- */
- public function __construct($name = '') {
- $this->name = $name;
+ if ($this->requiresLayout) {
+ $this->layout = $this->getDefaultLayout();
+ }
+ }
- if ($this->requiresLayout) {
- $this->layout = $this->getDefaultLayout();
- }
- }
+ public function __destruct()
+ {
+ $this->close();
+ }
- public function __destruct() {
- $this->close();
- }
+ /**
+ * Returns the default layout for this appender. Can be overriden by
+ * derived appenders.
+ *
+ * @return Layout
+ */
+ public function getDefaultLayout()
+ {
+ return new SimpleLayout();
+ }
- /**
- * Returns the default layout for this appender. Can be overriden by
- * derived appenders.
- *
- * @return Layout
- */
- public function getDefaultLayout() {
- return new SimpleLayout();
- }
+ /**
+ * Adds a filter to the end of the filter chain.
+ * @param AbstractFilter $filter add a new AbstractFilter
+ */
+ public function addFilter($filter)
+ {
+ if ($this->filter === null) {
+ $this->filter = $filter;
+ } else {
+ $this->filter->addNext($filter);
+ }
+ }
- /**
- * Adds a filter to the end of the filter chain.
- * @param AbstractFilter $filter add a new AbstractFilter
- */
- public function addFilter($filter) {
- if($this->filter === null) {
- $this->filter = $filter;
- } else {
- $this->filter->addNext($filter);
- }
- }
+ /**
+ * Clears the filter chain by removing all the filters in it.
+ */
+ public function clearFilters()
+ {
+ $this->filter = null;
+ }
- /**
- * Clears the filter chain by removing all the filters in it.
- */
- public function clearFilters() {
- $this->filter = null;
- }
+ /**
+ * Returns the first filter in the filter chain.
+ * The return value may be <i>null</i> if no is filter is set.
+ * @return AbstractFilter
+ */
+ public function getFilter()
+ {
+ return $this->filter;
+ }
- /**
- * Returns the first filter in the filter chain.
- * The return value may be <i>null</i> if no is filter is set.
- * @return AbstractFilter
- */
- public function getFilter() {
- return $this->filter;
- }
+ /**
+ * Returns the first filter in the filter chain.
+ * The return value may be <i>null</i> if no is filter is set.
+ * @return AbstractFilter
+ */
+ public function getFirstFilter()
+ {
+ return $this->filter;
+ }
- /**
- * Returns the first filter in the filter chain.
- * The return value may be <i>null</i> if no is filter is set.
- * @return AbstractFilter
- */
- public function getFirstFilter() {
- return $this->filter;
- }
+ /**
+ * Performs threshold checks and invokes filters before delegating logging
+ * to the subclass' specific <i>append()</i> method.
+ * @see Appender::append()
+ * @param LoggingEvent $event
+ */
+ public function doAppend(LoggingEvent $event)
+ {
+ if ($this->closed) {
+ return;
+ }
- /**
- * Performs threshold checks and invokes filters before delegating logging
- * to the subclass' specific <i>append()</i> method.
- * @see Appender::append()
- * @param LoggingEvent $event
- */
- public function doAppend(LoggingEvent $event) {
- if($this->closed) {
- return;
- }
+ if (!$this->isAsSevereAsThreshold($event->getLevel())) {
+ return;
+ }
- if(!$this->isAsSevereAsThreshold($event->getLevel())) {
- return;
- }
+ $filter = $this->getFirstFilter();
+ while ($filter !== null) {
+ switch ($filter->decide($event)) {
+ case AbstractFilter::DENY: return;
+ case AbstractFilter::ACCEPT: return $this->append($event);
+ case AbstractFilter::NEUTRAL: $filter = $filter->getNext();
+ }
+ }
+ $this->append($event);
+ }
- $filter = $this->getFirstFilter();
- while($filter !== null) {
- switch ($filter->decide($event)) {
- case AbstractFilter::DENY: return;
- case AbstractFilter::ACCEPT: return $this->append($event);
- case AbstractFilter::NEUTRAL: $filter = $filter->getNext();
- }
- }
- $this->append($event);
- }
+ /**
+ * Sets the appender layout.
+ * @param Layout $layout
+ */
+ public function setLayout($layout)
+ {
+ if ($this->requiresLayout()) {
+ $this->layout = $layout;
+ }
+ }
- /**
- * Sets the appender layout.
- * @param Layout $layout
- */
- public function setLayout($layout) {
- if($this->requiresLayout()) {
- $this->layout = $layout;
- }
- }
+ /**
+ * Returns the appender layout.
+ * @return Layout
+ */
+ public function getLayout()
+ {
+ return $this->layout;
+ }
- /**
- * Returns the appender layout.
- * @return Layout
- */
- public function getLayout() {
- return $this->layout;
- }
+ /**
+ * Configurators call this method to determine if the appender
+ * requires a layout.
+ *
+ * <p>If this method returns <i>true</i>, meaning that layout is required,
+ * then the configurator will configure a layout using the configuration
+ * information at its disposal. If this method returns <i>false</i>,
+ * meaning that a layout is not required, then layout configuration will be
+ * skipped even if there is available layout configuration
+ * information at the disposal of the configurator.</p>
+ *
+ * <p>In the rather exceptional case, where the appender
+ * implementation admits a layout but can also work without it, then
+ * the appender should return <i>true</i>.</p>
+ *
+ * @return boolean
+ */
+ public function requiresLayout()
+ {
+ return $this->requiresLayout;
+ }
- /**
- * Configurators call this method to determine if the appender
- * requires a layout.
- *
- * <p>If this method returns <i>true</i>, meaning that layout is required,
- * then the configurator will configure a layout using the configuration
- * information at its disposal. If this method returns <i>false</i>,
- * meaning that a layout is not required, then layout configuration will be
- * skipped even if there is available layout configuration
- * information at the disposal of the configurator.</p>
- *
- * <p>In the rather exceptional case, where the appender
- * implementation admits a layout but can also work without it, then
- * the appender should return <i>true</i>.</p>
- *
- * @return boolean
- */
- public function requiresLayout() {
- return $this->requiresLayout;
- }
+ /**
+ * Retruns the appender name.
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
- /**
- * Retruns the appender name.
- * @return string
- */
- public function getName() {
- return $this->name;
- }
+ /**
+ * Sets the appender name.
+ * @param string $name
+ */
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- /**
- * Sets the appender name.
- * @param string $name
- */
- public function setName($name) {
- $this->name = $name;
- }
+ /**
+ * Returns the appender's threshold level.
+ * @return Level
+ */
+ public function getThreshold()
+ {
+ return $this->threshold;
+ }
- /**
- * Returns the appender's threshold level.
- * @return Level
- */
- public function getThreshold() {
- return $this->threshold;
- }
+ /**
+ * Sets the appender threshold.
+ *
+ * @param Level|string $threshold Either a {@link Level}
+ * object or a string equivalent.
+ * @see OptionConverter::toLevel()
+ */
+ public function setThreshold($threshold)
+ {
+ $this->setLevel('threshold', $threshold);
+ }
- /**
- * Sets the appender threshold.
- *
- * @param Level|string $threshold Either a {@link Level}
- * object or a string equivalent.
- * @see OptionConverter::toLevel()
- */
- public function setThreshold($threshold) {
- $this->setLevel('threshold', $threshold);
- }
+ /**
+ * Checks whether the message level is below the appender's threshold.
+ *
+ * If there is no threshold set, then the return value is always <i>true</i>.
+ *
+ * @param Level $level
+ * @return boolean Returns true if level is greater or equal than
+ * threshold, or if the threshold is not set. Otherwise returns false.
+ */
+ public function isAsSevereAsThreshold($level)
+ {
+ if ($this->threshold === null) {
+ return true;
+ }
- /**
- * Checks whether the message level is below the appender's threshold.
- *
- * If there is no threshold set, then the return value is always <i>true</i>.
- *
- * @param Level $level
- * @return boolean Returns true if level is greater or equal than
- * threshold, or if the threshold is not set. Otherwise returns false.
- */
- public function isAsSevereAsThreshold($level) {
- if($this->threshold === null) {
- return true;
- }
- return $level->isGreaterOrEqual($this->getThreshold());
- }
+ return $level->isGreaterOrEqual($this->getThreshold());
+ }
- /**
- * Prepares the appender for logging.
- *
- * Derived appenders should override this method if option structure
- * requires it.
- */
- public function activateOptions() {
- $this->closed = false;
- }
+ /**
+ * Prepares the appender for logging.
+ *
+ * Derived appenders should override this method if option structure
+ * requires it.
+ */
+ public function activateOptions()
+ {
+ $this->closed = false;
+ }
- /**
- * Forwards the logging event to the destination.
- *
- * Derived appenders should implement this method to perform actual logging.
- *
- * @param LoggingEvent $event
- */
- abstract protected function append(LoggingEvent $event);
+ /**
+ * Forwards the logging event to the destination.
+ *
+ * Derived appenders should implement this method to perform actual logging.
+ *
+ * @param LoggingEvent $event
+ */
+ abstract protected function append(LoggingEvent $event);
- /**
- * Releases any resources allocated by the appender.
- *
- * Derived appenders should override this method to perform proper closing
- * procedures.
- */
- public function close() {
- $this->closed = true;
- }
+ /**
+ * Releases any resources allocated by the appender.
+ *
+ * Derived appenders should override this method to perform proper closing
+ * procedures.
+ */
+ public function close()
+ {
+ $this->closed = true;
+ }
- /** Triggers a warning for this logger with the given message. */
- protected function warn($message) {
- $id = get_class($this) . (empty($this->name) ? '' : ":{$this->name}");
- trigger_error("log4php: [$id]: $message", E_USER_WARNING);
- }
+ /** Triggers a warning for this logger with the given message. */
+ protected function warn($message)
+ {
+ $id = get_class($this) . (empty($this->name) ? '' : ":{$this->name}");
+ trigger_error("log4php: [$id]: $message", E_USER_WARNING);
+ }
}
diff --git a/src/Appenders/ConsoleAppender.php b/src/Appenders/ConsoleAppender.php
index def5230..d32fd9e 100644
--- a/src/Appenders/ConsoleAppender.php
+++ b/src/Appenders/ConsoleAppender.php
@@ -35,69 +35,73 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/console.html Appender documentation
*/
- class ConsoleAppender extends AbstractAppender {
+ class ConsoleAppender extends AbstractAppender
+ {
+ /** The standard otuput stream. */
+ const STDOUT = 'php://stdout';
- /** The standard otuput stream. */
- const STDOUT = 'php://stdout';
+ /** The standard error stream.*/
+ const STDERR = 'php://stderr';
- /** The standard error stream.*/
- const STDERR = 'php://stderr';
+ /** The 'target' parameter. */
+ protected $target = self::STDOUT;
- /** The 'target' parameter. */
- protected $target = self::STDOUT;
+ /**
+ * Stream resource for the target stream.
+ * @var resource
+ */
+ protected $fp = null;
- /**
- * Stream resource for the target stream.
- * @var resource
- */
- protected $fp = null;
+ public function activateOptions()
+ {
+ $this->fp = fopen($this->target, 'w');
+ if (is_resource($this->fp) && $this->layout !== null) {
+ fwrite($this->fp, $this->layout->getHeader());
+ }
+ $this->closed = (bool) is_resource($this->fp) === false;
+ }
- public function activateOptions() {
- $this->fp = fopen($this->target, 'w');
- if(is_resource($this->fp) && $this->layout !== null) {
- fwrite($this->fp, $this->layout->getHeader());
- }
- $this->closed = (bool)is_resource($this->fp) === false;
- }
+ public function close()
+ {
+ if ($this->closed != true) {
+ if (is_resource($this->fp) && $this->layout !== null) {
+ fwrite($this->fp, $this->layout->getFooter());
+ fclose($this->fp);
+ }
+ $this->closed = true;
+ }
+ }
+ public function append(LoggingEvent $event)
+ {
+ if (is_resource($this->fp) && $this->layout !== null) {
+ fwrite($this->fp, $this->layout->format($event));
+ }
+ }
- public function close() {
- if($this->closed != true) {
- if (is_resource($this->fp) && $this->layout !== null) {
- fwrite($this->fp, $this->layout->getFooter());
- fclose($this->fp);
- }
- $this->closed = true;
- }
- }
+ /**
+ * Sets the 'target' parameter.
+ * @param string $target
+ */
+ public function setTarget($target)
+ {
+ $value = trim($target);
+ if ($value == self::STDOUT || strtoupper($value) == 'STDOUT') {
+ $this->target = self::STDOUT;
+ } elseif ($value == self::STDERR || strtoupper($value) == 'STDERR') {
+ $this->target = self::STDERR;
+ } else {
+ $target = var_export($target);
+ $this->warn("Invalid value given for 'target' property: [$target]. Property not set.");
+ }
+ }
- public function append(LoggingEvent $event) {
- if (is_resource($this->fp) && $this->layout !== null) {
- fwrite($this->fp, $this->layout->format($event));
- }
- }
-
- /**
- * Sets the 'target' parameter.
- * @param string $target
- */
- public function setTarget($target) {
- $value = trim($target);
- if ($value == self::STDOUT || strtoupper($value) == 'STDOUT') {
- $this->target = self::STDOUT;
- } elseif ($value == self::STDERR || strtoupper($value) == 'STDERR') {
- $this->target = self::STDERR;
- } else {
- $target = var_export($target);
- $this->warn("Invalid value given for 'target' property: [$target]. Property not set.");
- }
- }
-
- /**
- * Returns the value of the 'target' parameter.
- * @return string
- */
- public function getTarget() {
- return $this->target;
- }
+ /**
+ * Returns the value of the 'target' parameter.
+ * @return string
+ */
+ public function getTarget()
+ {
+ return $this->target;
+ }
}
diff --git a/src/Appenders/DailyFileAppender.php b/src/Appenders/DailyFileAppender.php
index 7ca1cc7..3464246 100644
--- a/src/Appenders/DailyFileAppender.php
+++ b/src/Appenders/DailyFileAppender.php
@@ -40,91 +40,98 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/daily-file.html Appender documentation
*/
-class DailyFileAppender extends FileAppender {
+class DailyFileAppender extends FileAppender
+{
+ /**
+ * The 'datePattern' parameter.
+ * Determines how date will be formatted in file name.
+ * @var string
+ */
+ protected $datePattern = "Ymd";
- /**
- * The 'datePattern' parameter.
- * Determines how date will be formatted in file name.
- * @var string
- */
- protected $datePattern = "Ymd";
+ /**
+ * Current date which was used when opening a file.
+ * Used to determine if a rollover is needed when the date changes.
+ * @var string
+ */
+ protected $currentDate;
- /**
- * Current date which was used when opening a file.
- * Used to determine if a rollover is needed when the date changes.
- * @var string
- */
- protected $currentDate;
+ /** Additional validation for the date pattern. */
+ public function activateOptions()
+ {
+ parent::activateOptions();
- /** Additional validation for the date pattern. */
- public function activateOptions() {
- parent::activateOptions();
+ if (empty($this->datePattern)) {
+ $this->warn("Required parameter 'datePattern' not set. Closing appender.");
+ $this->closed = true;
- if (empty($this->datePattern)) {
- $this->warn("Required parameter 'datePattern' not set. Closing appender.");
- $this->closed = true;
- return;
- }
- }
+ return;
+ }
+ }
- /**
- * Appends a logging event.
- *
- * If the target file changes because of passage of time (e.g. at midnight)
- * the current file is closed. A new file, with the new date, will be
- * opened by the write() method.
- */
- public function append(LoggingEvent $event) {
- $eventDate = $this->getDate($event->getTimestamp());
+ /**
+ * Appends a logging event.
+ *
+ * If the target file changes because of passage of time (e.g. at midnight)
+ * the current file is closed. A new file, with the new date, will be
+ * opened by the write() method.
+ */
+ public function append(LoggingEvent $event)
+ {
+ $eventDate = $this->getDate($event->getTimestamp());
- // Initial setting of current date
- if (!isset($this->currentDate)) {
- $this->currentDate = $eventDate;
- }
+ // Initial setting of current date
+ if (!isset($this->currentDate)) {
+ $this->currentDate = $eventDate;
+ }
- // Check if rollover is needed
- else if ($this->currentDate !== $eventDate) {
- $this->currentDate = $eventDate;
+ // Check if rollover is needed
+ else if ($this->currentDate !== $eventDate) {
+ $this->currentDate = $eventDate;
- // Close the file if it's open.
- // Note: $this->close() is not called here because it would set
- // $this->closed to true and the appender would not recieve
- // any more logging requests
- if (is_resource($this->fp)) {
- $this->write($this->layout->getFooter());
- fclose($this->fp);
- }
- $this->fp = null;
- }
+ // Close the file if it's open.
+ // Note: $this->close() is not called here because it would set
+ // $this->closed to true and the appender would not recieve
+ // any more logging requests
+ if (is_resource($this->fp)) {
+ $this->write($this->layout->getFooter());
+ fclose($this->fp);
+ }
+ $this->fp = null;
+ }
- parent::append($event);
- }
+ parent::append($event);
+ }
- /** Renders the date using the configured <var>datePattern<var>. */
- protected function getDate($timestamp = null) {
- return date($this->datePattern, $timestamp);
- }
+ /** Renders the date using the configured <var>datePattern<var>. */
+ protected function getDate($timestamp = null)
+ {
+ return date($this->datePattern, $timestamp);
+ }
- /**
- * Determines target file. Replaces %s in file path with a date.
- */
- protected function getTargetFile() {
- return str_replace('%s', $this->currentDate, $this->file);
- }
+ /**
+ * Determines target file. Replaces %s in file path with a date.
+ */
+ protected function getTargetFile()
+ {
+ return str_replace('%s', $this->currentDate, $this->file);
+ }
- /**
- * Sets the 'datePattern' parameter.
- * @param string $datePattern
- */
- public function setDatePattern($datePattern) {
- $this->setString('datePattern', $datePattern);
- }
+ /**
+ * Sets the 'datePattern' parameter.
+ * @param string $datePattern
+ */
+ public function setDatePattern($datePattern)
+ {
+ $this->setString('datePattern', $datePattern);
+ }
- /**
- * Returns the 'datePattern' parameter.
- * @return string
- */
- public function getDatePattern() {
- return $this->datePattern;
- }
+ /**
+ * Returns the 'datePattern' parameter.
+ * @return string
+ */
+ public function getDatePattern()
+ {
+ return $this->datePattern;
+ }
}
diff --git a/src/Appenders/EchoAppender.php b/src/Appenders/EchoAppender.php
index 1b47ff9..58d21b4 100644
--- a/src/Appenders/EchoAppender.php
+++ b/src/Appenders/EchoAppender.php
@@ -34,56 +34,59 @@
*/
class EchoAppender extends AbstractAppender
{
- /**
- * Used to mark first append. Set to false after first append.
- * @var boolean
- */
- protected $firstAppend = true;
+ /**
+ * Used to mark first append. Set to false after first append.
+ * @var boolean
+ */
+ protected $firstAppend = true;
- /**
- * If set to true, a <br /> element will be inserted before each line
- * break in the logged message. Default value is false. @var boolean
- */
- protected $htmlLineBreaks = false;
+ /**
+ * If set to true, a <br /> element will be inserted before each line
+ * break in the logged message. Default value is false. @var boolean
+ */
+ protected $htmlLineBreaks = false;
- public function close() {
- if($this->closed != true) {
- if(!$this->firstAppend) {
- echo $this->layout->getFooter();
- }
- }
- $this->closed = true;
- }
+ public function close()
+ {
+ if ($this->closed != true) {
+ if (!$this->firstAppend) {
+ echo $this->layout->getFooter();
+ }
+ }
+ $this->closed = true;
+ }
- public function append(LoggingEvent $event) {
- if($this->layout !== null) {
- if($this->firstAppend) {
- echo $this->layout->getHeader();
- $this->firstAppend = false;
- }
- $text = $this->layout->format($event);
+ public function append(LoggingEvent $event)
+ {
+ if ($this->layout !== null) {
+ if ($this->firstAppend) {
+ echo $this->layout->getHeader();
+ $this->firstAppend = false;
+ }
+ $text = $this->layout->format($event);
- if ($this->htmlLineBreaks) {
- $text = nl2br($text);
- }
- echo $text;
- }
- }
+ if ($this->htmlLineBreaks) {
+ $text = nl2br($text);
+ }
+ echo $text;
+ }
+ }
- /**
- * Sets the 'htmlLineBreaks' parameter.
- * @param boolean $value
- */
- public function setHtmlLineBreaks($value) {
- $this->setBoolean('htmlLineBreaks', $value);
- }
+ /**
+ * Sets the 'htmlLineBreaks' parameter.
+ * @param boolean $value
+ */
+ public function setHtmlLineBreaks($value)
+ {
+ $this->setBoolean('htmlLineBreaks', $value);
+ }
- /**
- * Returns the 'htmlLineBreaks' parameter.
- * @returns boolean
- */
- public function getHtmlLineBreaks() {
- return $this->htmlLineBreaks;
- }
+ /**
+ * Returns the 'htmlLineBreaks' parameter.
+ * @returns boolean
+ */
+ public function getHtmlLineBreaks()
+ {
+ return $this->htmlLineBreaks;
+ }
}
-
diff --git a/src/Appenders/FileAppender.php b/src/Appenders/FileAppender.php
index 5f0cfd4..4d67f2d 100644
--- a/src/Appenders/FileAppender.php
+++ b/src/Appenders/FileAppender.php
@@ -34,192 +34,209 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/file.html Appender documentation
*/
-class FileAppender extends AbstractAppender {
+class FileAppender extends AbstractAppender
+{
+ /**
+ * If set to true, the file is locked before appending. This allows
+ * concurrent access. However, appending without locking is faster so
+ * it should be used where appropriate.
+ *
+ * TODO: make this a configurable parameter
+ *
+ * @var boolean
+ */
+ protected $locking = true;
- /**
- * If set to true, the file is locked before appending. This allows
- * concurrent access. However, appending without locking is faster so
- * it should be used where appropriate.
- *
- * TODO: make this a configurable parameter
- *
- * @var boolean
- */
- protected $locking = true;
+ /**
+ * If set to true, appends to file. Otherwise overwrites it.
+ * @var boolean
+ */
+ protected $append = true;
- /**
- * If set to true, appends to file. Otherwise overwrites it.
- * @var boolean
- */
- protected $append = true;
+ /**
+ * Path to the target file.
+ * @var string
+ */
+ protected $file;
- /**
- * Path to the target file.
- * @var string
- */
- protected $file;
+ /**
+ * The file resource.
+ * @var resource
+ */
+ protected $fp;
- /**
- * The file resource.
- * @var resource
- */
- protected $fp;
+ /**
+ * Helper function which can be easily overriden by daily file appender.
+ */
+ protected function getTargetFile()
+ {
+ return $this->file;
+ }
- /**
- * Helper function which can be easily overriden by daily file appender.
- */
- protected function getTargetFile() {
- return $this->file;
- }
+ /**
+ * Acquires the target file resource, creates the destination folder if
+ * necessary. Writes layout header to file.
+ *
+ * @return boolean FALSE if opening failed
+ */
+ protected function openFile()
+ {
+ $file = $this->getTargetFile();
- /**
- * Acquires the target file resource, creates the destination folder if
- * necessary. Writes layout header to file.
- *
- * @return boolean FALSE if opening failed
- */
- protected function openFile() {
- $file = $this->getTargetFile();
+ // Create the target folder if needed
+ if (!is_file($file)) {
+ $dir = dirname($file);
- // Create the target folder if needed
- if(!is_file($file)) {
- $dir = dirname($file);
+ if (!is_dir($dir)) {
+ $success = mkdir($dir, 0777, true);
+ if ($success === false) {
+ $this->warn("Failed creating target directory [$dir]. Closing appender.");
+ $this->closed = true;
- if(!is_dir($dir)) {
- $success = mkdir($dir, 0777, true);
- if ($success === false) {
- $this->warn("Failed creating target directory [$dir]. Closing appender.");
- $this->closed = true;
- return false;
- }
- }
- }
+ return false;
+ }
+ }
+ }
- $mode = $this->append ? 'a' : 'w';
- $this->fp = fopen($file, $mode);
- if ($this->fp === false) {
- $this->warn("Failed opening target file. Closing appender.");
- $this->fp = null;
- $this->closed = true;
- return false;
- }
+ $mode = $this->append ? 'a' : 'w';
+ $this->fp = fopen($file, $mode);
+ if ($this->fp === false) {
+ $this->warn("Failed opening target file. Closing appender.");
+ $this->fp = null;
+ $this->closed = true;
- // Required when appending with concurrent access
- if($this->append) {
- fseek($this->fp, 0, SEEK_END);
- }
+ return false;
+ }
- // Write the header
- $this->write($this->layout->getHeader());
- }
+ // Required when appending with concurrent access
+ if ($this->append) {
+ fseek($this->fp, 0, SEEK_END);
+ }
- /**
- * Writes a string to the target file. Opens file if not already open.
- * @param string $string Data to write.
- */
- protected function write($string) {
- // Lazy file open
- if(!isset($this->fp)) {
- if ($this->openFile() === false) {
- return; // Do not write if file open failed.
- }
- }
+ // Write the header
+ $this->write($this->layout->getHeader());
+ }
- if ($this->locking) {
- $this->writeWithLocking($string);
- } else {
- $this->writeWithoutLocking($string);
- }
- }
+ /**
+ * Writes a string to the target file. Opens file if not already open.
+ * @param string $string Data to write.
+ */
+ protected function write($string)
+ {
+ // Lazy file open
+ if (!isset($this->fp)) {
+ if ($this->openFile() === false) {
+ return; // Do not write if file open failed.
+ }
+ }
- protected function writeWithLocking($string) {
- if(flock($this->fp, LOCK_EX)) {
- if(fwrite($this->fp, $string) === false) {
- $this->warn("Failed writing to file. Closing appender.");
- $this->closed = true;
- }
- flock($this->fp, LOCK_UN);
- } else {
- $this->warn("Failed locking file for writing. Closing appender.");
- $this->closed = true;
- }
- }
+ if ($this->locking) {
+ $this->writeWithLocking($string);
+ } else {
+ $this->writeWithoutLocking($string);
+ }
+ }
- protected function writeWithoutLocking($string) {
- if(fwrite($this->fp, $string) === false) {
- $this->warn("Failed writing to file. Closing appender.");
- $this->closed = true;
- }
- }
+ protected function writeWithLocking($string)
+ {
+ if (flock($this->fp, LOCK_EX)) {
+ if (fwrite($this->fp, $string) === false) {
+ $this->warn("Failed writing to file. Closing appender.");
+ $this->closed = true;
+ }
+ flock($this->fp, LOCK_UN);
+ } else {
+ $this->warn("Failed locking file for writing. Closing appender.");
+ $this->closed = true;
+ }
+ }
- public function activateOptions() {
- if (empty($this->file)) {
- $this->warn("Required parameter 'file' not set. Closing appender.");
- $this->closed = true;
- return;
- }
- }
+ protected function writeWithoutLocking($string)
+ {
+ if (fwrite($this->fp, $string) === false) {
+ $this->warn("Failed writing to file. Closing appender.");
+ $this->closed = true;
+ }
+ }
- public function close() {
- if (is_resource($this->fp)) {
- $this->write($this->layout->getFooter());
- fclose($this->fp);
- }
- $this->fp = null;
- $this->closed = true;
- }
+ public function activateOptions()
+ {
+ if (empty($this->file)) {
+ $this->warn("Required parameter 'file' not set. Closing appender.");
+ $this->closed = true;
- public function append(LoggingEvent $event) {
- $this->write($this->layout->format($event));
- }
+ return;
+ }
+ }
- /**
- * Sets the 'file' parameter.
- * @param string $file
- */
- public function setFile($file) {
- $this->setString('file', $file);
- }
+ public function close()
+ {
+ if (is_resource($this->fp)) {
+ $this->write($this->layout->getFooter());
+ fclose($this->fp);
+ }
+ $this->fp = null;
+ $this->closed = true;
+ }
- /**
- * Returns the 'file' parameter.
- * @return string
- */
- public function getFile() {
- return $this->file;
- }
+ public function append(LoggingEvent $event)
+ {
+ $this->write($this->layout->format($event));
+ }
- /**
- * Returns the 'append' parameter.
- * @return boolean
- */
- public function getAppend() {
- return $this->append;
- }
+ /**
+ * Sets the 'file' parameter.
+ * @param string $file
+ */
+ public function setFile($file)
+ {
+ $this->setString('file', $file);
+ }
- /**
- * Sets the 'append' parameter.
- * @param boolean $append
- */
- public function setAppend($append) {
- $this->setBoolean('append', $append);
- }
+ /**
+ * Returns the 'file' parameter.
+ * @return string
+ */
+ public function getFile()
+ {
+ return $this->file;
+ }
- /**
- * Sets the 'file' parmeter. Left for legacy reasons.
- * @param string $fileName
- * @deprecated Use setFile() instead.
- */
- public function setFileName($fileName) {
- $this->setFile($fileName);
- }
+ /**
+ * Returns the 'append' parameter.
+ * @return boolean
+ */
+ public function getAppend()
+ {
+ return $this->append;
+ }
- /**
- * Returns the 'file' parmeter. Left for legacy reasons.
- * @return string
- * @deprecated Use getFile() instead.
- */
- public function getFileName() {
- return $this->getFile();
- }
+ /**
+ * Sets the 'append' parameter.
+ * @param boolean $append
+ */
+ public function setAppend($append)
+ {
+ $this->setBoolean('append', $append);
+ }
+
+ /**
+ * Sets the 'file' parmeter. Left for legacy reasons.
+ * @param string $fileName
+ * @deprecated Use setFile() instead.
+ */
+ public function setFileName($fileName)
+ {
+ $this->setFile($fileName);
+ }
+
+ /**
+ * Returns the 'file' parmeter. Left for legacy reasons.
+ * @return string
+ * @deprecated Use getFile() instead.
+ */
+ public function getFileName()
+ {
+ return $this->getFile();
+ }
}
diff --git a/src/Appenders/MailAppender.php b/src/Appenders/MailAppender.php
index 796167e..d34dce1 100644
--- a/src/Appenders/MailAppender.php
+++ b/src/Appenders/MailAppender.php
@@ -40,97 +40,106 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/mail.html Appender documentation
*/
-class MailAppender extends AbstractAppender {
+class MailAppender extends AbstractAppender
+{
+ /**
+ * Email address to put in From field of the email.
+ * @var string
+ */
+ protected $from = null;
- /**
- * Email address to put in From field of the email.
- * @var string
- */
- protected $from = null;
+ /**
+ * The subject of the email.
+ * @var string
+ */
+ protected $subject = 'Log4php Report';
- /**
- * The subject of the email.
- * @var string
- */
- protected $subject = 'Log4php Report';
+ /**
+ * One or more comma separated email addresses to which to send the email.
+ * @var string
+ */
+ protected $to = null;
- /**
- * One or more comma separated email addresses to which to send the email.
- * @var string
- */
- protected $to = null;
+ /**
+ * Indiciates whether this appender should run in dry mode.
+ * @deprecated
+ * @var boolean
+ */
+ protected $dry = false;
- /**
- * Indiciates whether this appender should run in dry mode.
- * @deprecated
- * @var boolean
- */
- protected $dry = false;
+ /**
+ * Buffer which holds the email contents before it is sent.
+ * @var string
+ */
+ protected $body = '';
- /**
- * Buffer which holds the email contents before it is sent.
- * @var string
- */
- protected $body = '';
+ public function append(LoggingEvent $event)
+ {
+ if ($this->layout !== null) {
+ $this->body .= $this->layout->format($event);
+ }
+ }
- public function append(LoggingEvent $event) {
- if($this->layout !== null) {
- $this->body .= $this->layout->format($event);
- }
- }
+ public function close()
+ {
+ if ($this->closed != true) {
+ $from = $this->from;
+ $to = $this->to;
- public function close() {
- if($this->closed != true) {
- $from = $this->from;
- $to = $this->to;
+ if (!empty($this->body) and $from !== null and $to !== null and $this->layout !== null) {
+ $subject = $this->subject;
+ if (!$this->dry) {
+ mail(
+ $to, $subject,
+ $this->layout->getHeader() . $this->body . $this->layout->getFooter(),
+ "From: {$from}\r\n");
+ } else {
+ echo "DRY MODE OF MAIL APP.: Send mail to: ".$to." with content: ".$this->body;
+ }
+ }
+ $this->closed = true;
+ }
+ }
- if(!empty($this->body) and $from !== null and $to !== null and $this->layout !== null) {
- $subject = $this->subject;
- if(!$this->dry) {
- mail(
- $to, $subject,
- $this->layout->getHeader() . $this->body . $this->layout->getFooter(),
- "From: {$from}\r\n");
- } else {
- echo "DRY MODE OF MAIL APP.: Send mail to: ".$to." with content: ".$this->body;
- }
- }
- $this->closed = true;
- }
- }
+ /** Sets the 'subject' parameter. */
+ public function setSubject($subject)
+ {
+ $this->setString('subject', $subject);
+ }
- /** Sets the 'subject' parameter. */
- public function setSubject($subject) {
- $this->setString('subject', $subject);
- }
+ /** Returns the 'subject' parameter. */
+ public function getSubject()
+ {
+ return $this->subject;
+ }
- /** Returns the 'subject' parameter. */
- public function getSubject() {
- return $this->subject;
- }
+ /** Sets the 'to' parameter. */
+ public function setTo($to)
+ {
+ $this->setString('to', $to);
+ }
- /** Sets the 'to' parameter. */
- public function setTo($to) {
- $this->setString('to', $to);
- }
+ /** Returns the 'to' parameter. */
+ public function getTo()
+ {
+ return $this->to;
+ }
- /** Returns the 'to' parameter. */
- public function getTo() {
- return $this->to;
- }
+ /** Sets the 'from' parameter. */
+ public function setFrom($from)
+ {
+ $this->setString('from', $from);
+ }
- /** Sets the 'from' parameter. */
- public function setFrom($from) {
- $this->setString('from', $from);
- }
+ /** Returns the 'from' parameter. */
+ public function getFrom()
+ {
+ return $this->from;
+ }
- /** Returns the 'from' parameter. */
- public function getFrom() {
- return $this->from;
- }
-
- /** Enables or disables dry mode. */
- public function setDry($dry) {
- $this->setBoolean('dry', $dry);
- }
+ /** Enables or disables dry mode. */
+ public function setDry($dry)
+ {
+ $this->setBoolean('dry', $dry);
+ }
}
diff --git a/src/Appenders/MailEventAppender.php b/src/Appenders/MailEventAppender.php
index c49ba12..6a0ff70 100644
--- a/src/Appenders/MailEventAppender.php
+++ b/src/Appenders/MailEventAppender.php
@@ -40,141 +40,156 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/mail-event.html Appender documentation
*/
-class MailEventAppender extends AbstractAppender {
+class MailEventAppender extends AbstractAppender
+{
+ /**
+ * Email address to put in From field of the email.
+ * @var string
+ */
+ protected $from;
- /**
- * Email address to put in From field of the email.
- * @var string
- */
- protected $from;
+ /**
+ * Mail server port (widnows only).
+ * @var integer
+ */
+ protected $port = 25;
- /**
- * Mail server port (widnows only).
- * @var integer
- */
- protected $port = 25;
+ /**
+ * Mail server hostname (windows only).
+ * @var string
+ */
+ protected $smtpHost;
- /**
- * Mail server hostname (windows only).
- * @var string
- */
- protected $smtpHost;
+ /**
+ * The subject of the email.
+ * @var string
+ */
+ protected $subject = 'Log4php Report';
- /**
- * The subject of the email.
- * @var string
- */
- protected $subject = 'Log4php Report';
+ /**
+ * One or more comma separated email addresses to which to send the email.
+ * @var string
+ */
+ protected $to = null;
- /**
- * One or more comma separated email addresses to which to send the email.
- * @var string
- */
- protected $to = null;
+ /**
+ * Indiciates whether this appender should run in dry mode.
+ * @deprecated
+ * @var boolean
+ */
+ protected $dry = false;
- /**
- * Indiciates whether this appender should run in dry mode.
- * @deprecated
- * @var boolean
- */
- protected $dry = false;
+ public function activateOptions()
+ {
+ if (empty($this->to)) {
+ $this->warn("Required parameter 'to' not set. Closing appender.");
+ $this->close = true;
- public function activateOptions() {
- if (empty($this->to)) {
- $this->warn("Required parameter 'to' not set. Closing appender.");
- $this->close = true;
- return;
- }
+ return;
+ }
- $sendmail_from = ini_get('sendmail_from');
- if (empty($this->from) and empty($sendmail_from)) {
- $this->warn("Required parameter 'from' not set. Closing appender.");
- $this->close = true;
- return;
- }
+ $sendmail_from = ini_get('sendmail_from');
+ if (empty($this->from) and empty($sendmail_from)) {
+ $this->warn("Required parameter 'from' not set. Closing appender.");
+ $this->close = true;
- $this->closed = false;
- }
+ return;
+ }
- public function append(LoggingEvent $event) {
- $smtpHost = $this->smtpHost;
- $prevSmtpHost = ini_get('SMTP');
- if(!empty($smtpHost)) {
- ini_set('SMTP', $smtpHost);
- }
+ $this->closed = false;
+ }
- $smtpPort = $this->port;
- $prevSmtpPort= ini_get('smtp_port');
- if($smtpPort > 0 and $smtpPort < 65535) {
- ini_set('smtp_port', $smtpPort);
- }
+ public function append(LoggingEvent $event)
+ {
+ $smtpHost = $this->smtpHost;
+ $prevSmtpHost = ini_get('SMTP');
+ if (!empty($smtpHost)) {
+ ini_set('SMTP', $smtpHost);
+ }
- // On unix only sendmail_path, which is PHP_INI_SYSTEM i.e. not changeable here, is used.
+ $smtpPort = $this->port;
+ $prevSmtpPort= ini_get('smtp_port');
+ if ($smtpPort > 0 and $smtpPort < 65535) {
+ ini_set('smtp_port', $smtpPort);
+ }
- $addHeader = empty($this->from) ? '' : "From: {$this->from}\r\n";
+ // On unix only sendmail_path, which is PHP_INI_SYSTEM i.e. not changeable here, is used.
- if(!$this->dry) {
- $result = mail($this->to, $this->subject, $this->layout->getHeader() . $this->layout->format($event) . $this->layout->getFooter($event), $addHeader);
- } else {
- echo "DRY MODE OF MAIL APP.: Send mail to: ".$this->to." with additional headers '".trim($addHeader)."' and content: ".$this->layout->format($event);
- }
+ $addHeader = empty($this->from) ? '' : "From: {$this->from}\r\n";
- ini_set('SMTP', $prevSmtpHost);
- ini_set('smtp_port', $prevSmtpPort);
- }
+ if (!$this->dry) {
+ $result = mail($this->to, $this->subject, $this->layout->getHeader() . $this->layout->format($event) . $this->layout->getFooter($event), $addHeader);
+ } else {
+ echo "DRY MODE OF MAIL APP.: Send mail to: ".$this->to." with additional headers '".trim($addHeader)."' and content: ".$this->layout->format($event);
+ }
- /** Sets the 'from' parameter. */
- public function setFrom($from) {
- $this->setString('from', $from);
- }
+ ini_set('SMTP', $prevSmtpHost);
+ ini_set('smtp_port', $prevSmtpPort);
+ }
- /** Returns the 'from' parameter. */
- public function getFrom() {
- return $this->from;
- }
+ /** Sets the 'from' parameter. */
+ public function setFrom($from)
+ {
+ $this->setString('from', $from);
+ }
- /** Sets the 'port' parameter. */
- public function setPort($port) {
- $this->setPositiveInteger('port', $port);
- }
+ /** Returns the 'from' parameter. */
+ public function getFrom()
+ {
+ return $this->from;
+ }
- /** Returns the 'port' parameter. */
- public function getPort() {
- return $this->port;
- }
+ /** Sets the 'port' parameter. */
+ public function setPort($port)
+ {
+ $this->setPositiveInteger('port', $port);
+ }
- /** Sets the 'smtpHost' parameter. */
- public function setSmtpHost($smtpHost) {
- $this->setString('smtpHost', $smtpHost);
- }
+ /** Returns the 'port' parameter. */
+ public function getPort()
+ {
+ return $this->port;
+ }
- /** Returns the 'smtpHost' parameter. */
- public function getSmtpHost() {
- return $this->smtpHost;
- }
+ /** Sets the 'smtpHost' parameter. */
+ public function setSmtpHost($smtpHost)
+ {
+ $this->setString('smtpHost', $smtpHost);
+ }
- /** Sets the 'subject' parameter. */
- public function setSubject($subject) {
- $this->setString('subject', $subject);
- }
+ /** Returns the 'smtpHost' parameter. */
+ public function getSmtpHost()
+ {
+ return $this->smtpHost;
+ }
- /** Returns the 'subject' parameter. */
- public function getSubject() {
- return $this->subject;
- }
+ /** Sets the 'subject' parameter. */
+ public function setSubject($subject)
+ {
+ $this->setString('subject', $subject);
+ }
- /** Sets the 'to' parameter. */
- public function setTo($to) {
- $this->setString('to', $to);
- }
+ /** Returns the 'subject' parameter. */
+ public function getSubject()
+ {
+ return $this->subject;
+ }
- /** Returns the 'to' parameter. */
- public function getTo() {
- return $this->to;
- }
+ /** Sets the 'to' parameter. */
+ public function setTo($to)
+ {
+ $this->setString('to', $to);
+ }
- /** Enables or disables dry mode. */
- public function setDry($dry) {
- $this->setBoolean('dry', $dry);
- }
+ /** Returns the 'to' parameter. */
+ public function getTo()
+ {
+ return $this->to;
+ }
+
+ /** Enables or disables dry mode. */
+ public function setDry($dry)
+ {
+ $this->setBoolean('dry', $dry);
+ }
}
diff --git a/src/Appenders/MongoDBAppender.php b/src/Appenders/MongoDBAppender.php
index 38d7dca..0ff180b 100644
--- a/src/Appenders/MongoDBAppender.php
+++ b/src/Appenders/MongoDBAppender.php
@@ -46,321 +46,343 @@
* @link http://github.com/log4mongo/log4mongo-php Vladimir Gorej's original submission.
* @link http://www.mongodb.org/ MongoDB website.
*/
-class MongoDBAppender extends AbstractAppender {
+class MongoDBAppender extends AbstractAppender
+{
+ // ******************************************
+ // ** Constants **
+ // ******************************************
- // ******************************************
- // ** Constants **
- // ******************************************
+ /** Default prefix for the {@link $host}. */
+ const DEFAULT_MONGO_URL_PREFIX = 'mongodb://';
- /** Default prefix for the {@link $host}. */
- const DEFAULT_MONGO_URL_PREFIX = 'mongodb://';
+ /** Default value for {@link $host}, without a prefix. */
+ const DEFAULT_MONGO_HOST = 'localhost';
- /** Default value for {@link $host}, without a prefix. */
- const DEFAULT_MONGO_HOST = 'localhost';
+ /** Default value for {@link $port} */
+ const DEFAULT_MONGO_PORT = 27017;
- /** Default value for {@link $port} */
- const DEFAULT_MONGO_PORT = 27017;
+ /** Default value for {@link $databaseName} */
+ const DEFAULT_DB_NAME = 'log4php_mongodb';
- /** Default value for {@link $databaseName} */
- const DEFAULT_DB_NAME = 'log4php_mongodb';
+ /** Default value for {@link $collectionName} */
+ const DEFAULT_COLLECTION_NAME = 'logs';
- /** Default value for {@link $collectionName} */
- const DEFAULT_COLLECTION_NAME = 'logs';
+ /** Default value for {@link $timeout} */
+ const DEFAULT_TIMEOUT_VALUE = 3000;
- /** Default value for {@link $timeout} */
- const DEFAULT_TIMEOUT_VALUE = 3000;
+ // ******************************************
+ // ** Configurable parameters **
+ // ******************************************
- // ******************************************
- // ** Configurable parameters **
- // ******************************************
+ /** Server on which mongodb instance is located. */
+ protected $host;
- /** Server on which mongodb instance is located. */
- protected $host;
+ /** Port on which the instance is bound. */
+ protected $port;
- /** Port on which the instance is bound. */
- protected $port;
+ /** Name of the database to which to log. */
+ protected $databaseName;
- /** Name of the database to which to log. */
- protected $databaseName;
+ /** Name of the collection within the given database. */
+ protected $collectionName;
- /** Name of the collection within the given database. */
- protected $collectionName;
+ /** Username used to connect to the database. */
+ protected $userName;
- /** Username used to connect to the database. */
- protected $userName;
+ /** Password used to connect to the database. */
+ protected $password;
- /** Password used to connect to the database. */
- protected $password;
+ /** Timeout value used when connecting to the database (in milliseconds). */
+ protected $timeout;
- /** Timeout value used when connecting to the database (in milliseconds). */
- protected $timeout;
+ // ******************************************
+ // ** Member variables **
+ // ******************************************
- // ******************************************
- // ** Member variables **
- // ******************************************
+ /**
+ * Connection to the MongoDB instance.
+ * @var Mongo
+ */
+ protected $connection;
- /**
- * Connection to the MongoDB instance.
- * @var Mongo
- */
- protected $connection;
+ /**
+ * The collection to which log is written.
+ * @var MongoCollection
+ */
+ protected $collection;
- /**
- * The collection to which log is written.
- * @var MongoCollection
- */
- protected $collection;
+ public function __construct($name = '')
+ {
+ parent::__construct($name);
+ $this->host = self::DEFAULT_MONGO_URL_PREFIX . self::DEFAULT_MONGO_HOST;
+ $this->port = self::DEFAULT_MONGO_PORT;
+ $this->databaseName = self::DEFAULT_DB_NAME;
+ $this->collectionName = self::DEFAULT_COLLECTION_NAME;
+ $this->timeout = self::DEFAULT_TIMEOUT_VALUE;
+ $this->requiresLayout = false;
+ }
- public function __construct($name = '') {
- parent::__construct($name);
- $this->host = self::DEFAULT_MONGO_URL_PREFIX . self::DEFAULT_MONGO_HOST;
- $this->port = self::DEFAULT_MONGO_PORT;
- $this->databaseName = self::DEFAULT_DB_NAME;
- $this->collectionName = self::DEFAULT_COLLECTION_NAME;
- $this->timeout = self::DEFAULT_TIMEOUT_VALUE;
- $this->requiresLayout = false;
- }
+ /**
+ * Setup db connection.
+ * Based on defined options, this method connects to the database and
+ * creates a {@link $collection}.
+ */
+ public function activateOptions()
+ {
+ try {
+ $this->connection = new Mongo(sprintf('%s:%d', $this->host, $this->port), array('timeout' => $this->timeout));
+ $db = $this->connection->selectDB($this->databaseName);
+ if ($this->userName !== null && $this->password !== null) {
+ $authResult = $db->authenticate($this->userName, $this->password);
+ if ($authResult['ok'] == floatval(0)) {
+ throw new Exception($authResult['errmsg'], $authResult['ok']);
+ }
+ }
+ $this->collection = $db->selectCollection($this->collectionName);
+ } catch (\MongoConnectionException $ex) {
+ $this->closed = true;
+ $this->warn(sprintf('Failed to connect to mongo deamon: %s', $ex->getMessage()));
+ } catch (\InvalidArgumentException $ex) {
+ $this->closed = true;
+ $this->warn(sprintf('Error while selecting mongo database: %s', $ex->getMessage()));
+ } catch (\Exception $ex) {
+ $this->closed = true;
+ $this->warn('Invalid credentials for mongo database authentication');
+ }
+ }
- /**
- * Setup db connection.
- * Based on defined options, this method connects to the database and
- * creates a {@link $collection}.
- */
- public function activateOptions() {
- try {
- $this->connection = new Mongo(sprintf('%s:%d', $this->host, $this->port), array('timeout' => $this->timeout));
- $db = $this->connection->selectDB($this->databaseName);
- if ($this->userName !== null && $this->password !== null) {
- $authResult = $db->authenticate($this->userName, $this->password);
- if ($authResult['ok'] == floatval(0)) {
- throw new Exception($authResult['errmsg'], $authResult['ok']);
- }
- }
- $this->collection = $db->selectCollection($this->collectionName);
- } catch (\MongoConnectionException $ex) {
- $this->closed = true;
- $this->warn(sprintf('Failed to connect to mongo deamon: %s', $ex->getMessage()));
- } catch (\InvalidArgumentException $ex) {
- $this->closed = true;
- $this->warn(sprintf('Error while selecting mongo database: %s', $ex->getMessage()));
- } catch (\Exception $ex) {
- $this->closed = true;
- $this->warn('Invalid credentials for mongo database authentication');
- }
- }
+ /**
+ * Appends a new event to the mongo database.
+ *
+ * @param LoggingEvent $event
+ */
+ public function append(LoggingEvent $event)
+ {
+ try {
+ if ($this->collection != null) {
+ $this->collection->insert($this->format($event));
+ }
+ } catch (\MongoCursorException $ex) {
+ $this->warn(sprintf('Error while writing to mongo collection: %s', $ex->getMessage()));
+ }
+ }
- /**
- * Appends a new event to the mongo database.
- *
- * @param LoggingEvent $event
- */
- public function append(LoggingEvent $event) {
- try {
- if ($this->collection != null) {
- $this->collection->insert($this->format($event));
- }
- } catch (\MongoCursorException $ex) {
- $this->warn(sprintf('Error while writing to mongo collection: %s', $ex->getMessage()));
- }
- }
+ /**
+ * Converts the logging event into an array which can be logged to mongodb.
+ *
+ * @param LoggingEvent $event
+ * @return array The array representation of the logging event.
+ */
+ protected function format(LoggingEvent $event)
+ {
+ $timestampSec = (int) $event->getTimestamp();
+ $timestampUsec = (int) (($event->getTimestamp() - $timestampSec) * 1000000);
- /**
- * Converts the logging event into an array which can be logged to mongodb.
- *
- * @param LoggingEvent $event
- * @return array The array representation of the logging event.
- */
- protected function format(LoggingEvent $event) {
- $timestampSec = (int) $event->getTimestamp();
- $timestampUsec = (int) (($event->getTimestamp() - $timestampSec) * 1000000);
+ $document = array(
+ 'timestamp' => new MongoDate($timestampSec, $timestampUsec),
+ 'level' => $event->getLevel()->toString(),
+ 'thread' => (int) $event->getThreadName(),
+ 'message' => $event->getMessage(),
+ 'loggerName' => $event->getLoggerName()
+ );
- $document = array(
- 'timestamp' => new MongoDate($timestampSec, $timestampUsec),
- 'level' => $event->getLevel()->toString(),
- 'thread' => (int) $event->getThreadName(),
- 'message' => $event->getMessage(),
- 'loggerName' => $event->getLoggerName()
- );
+ $locationInfo = $event->getLocationInformation();
+ if ($locationInfo != null) {
+ $document['fileName'] = $locationInfo->getFileName();
+ $document['method'] = $locationInfo->getMethodName();
+ $document['lineNumber'] = ($locationInfo->getLineNumber() == 'NA') ? 'NA' : (int) $locationInfo->getLineNumber();
+ $document['className'] = $locationInfo->getClassName();
+ }
- $locationInfo = $event->getLocationInformation();
- if ($locationInfo != null) {
- $document['fileName'] = $locationInfo->getFileName();
- $document['method'] = $locationInfo->getMethodName();
- $document['lineNumber'] = ($locationInfo->getLineNumber() == 'NA') ? 'NA' : (int) $locationInfo->getLineNumber();
- $document['className'] = $locationInfo->getClassName();
- }
+ $throwableInfo = $event->getThrowableInformation();
+ if ($throwableInfo != null) {
+ $document['exception'] = $this->formatThrowable($throwableInfo->getThrowable());
+ }
- $throwableInfo = $event->getThrowableInformation();
- if ($throwableInfo != null) {
- $document['exception'] = $this->formatThrowable($throwableInfo->getThrowable());
- }
+ return $document;
+ }
- return $document;
- }
+ /**
+ * Converts an Exception into an array which can be logged to mongodb.
+ *
+ * Supports innner exceptions (PHP >= 5.3)
+ *
+ * @param Exception $ex
+ * @return array
+ */
+ protected function formatThrowable(Exception $ex)
+ {
+ $array = array(
+ 'message' => $ex->getMessage(),
+ 'code' => $ex->getCode(),
+ 'stackTrace' => $ex->getTraceAsString(),
+ );
- /**
- * Converts an Exception into an array which can be logged to mongodb.
- *
- * Supports innner exceptions (PHP >= 5.3)
- *
- * @param Exception $ex
- * @return array
- */
- protected function formatThrowable(Exception $ex) {
- $array = array(
- 'message' => $ex->getMessage(),
- 'code' => $ex->getCode(),
- 'stackTrace' => $ex->getTraceAsString(),
- );
+ if (method_exists($ex, 'getPrevious') && $ex->getPrevious() !== null) {
+ $array['innerException'] = $this->formatThrowable($ex->getPrevious());
+ }
- if (method_exists($ex, 'getPrevious') && $ex->getPrevious() !== null) {
- $array['innerException'] = $this->formatThrowable($ex->getPrevious());
- }
+ return $array;
+ }
- return $array;
- }
+ /**
+ * Closes the connection to the logging database
+ */
+ public function close()
+ {
+ if ($this->closed != true) {
+ $this->collection = null;
+ if ($this->connection !== null) {
+ $this->connection->close();
+ $this->connection = null;
+ }
+ $this->closed = true;
+ }
+ }
- /**
- * Closes the connection to the logging database
- */
- public function close() {
- if($this->closed != true) {
- $this->collection = null;
- if ($this->connection !== null) {
- $this->connection->close();
- $this->connection = null;
- }
- $this->closed = true;
- }
- }
+ /**
+ * Sets the value of {@link $host} parameter.
+ * @param string $host
+ */
+ public function setHost($host)
+ {
+ if (!preg_match('/^mongodb\:\/\//', $host)) {
+ $host = self::DEFAULT_MONGO_URL_PREFIX . $host;
+ }
+ $this->host = $host;
+ }
- /**
- * Sets the value of {@link $host} parameter.
- * @param string $host
- */
- public function setHost($host) {
- if (!preg_match('/^mongodb\:\/\//', $host)) {
- $host = self::DEFAULT_MONGO_URL_PREFIX . $host;
- }
- $this->host = $host;
- }
+ /**
+ * Returns the value of {@link $host} parameter.
+ * @return string
+ */
+ public function getHost()
+ {
+ return $this->host;
+ }
- /**
- * Returns the value of {@link $host} parameter.
- * @return string
- */
- public function getHost() {
- return $this->host;
- }
+ /**
+ * Sets the value of {@link $port} parameter.
+ * @param int $port
+ */
+ public function setPort($port)
+ {
+ $this->setPositiveInteger('port', $port);
+ }
- /**
- * Sets the value of {@link $port} parameter.
- * @param int $port
- */
- public function setPort($port) {
- $this->setPositiveInteger('port', $port);
- }
+ /**
+ * Returns the value of {@link $port} parameter.
+ * @return int
+ */
+ public function getPort()
+ {
+ return $this->port;
+ }
- /**
- * Returns the value of {@link $port} parameter.
- * @return int
- */
- public function getPort() {
- return $this->port;
- }
+ /**
+ * Sets the value of {@link $databaseName} parameter.
+ * @param string $databaseName
+ */
+ public function setDatabaseName($databaseName)
+ {
+ $this->setString('databaseName', $databaseName);
+ }
- /**
- * Sets the value of {@link $databaseName} parameter.
- * @param string $databaseName
- */
- public function setDatabaseName($databaseName) {
- $this->setString('databaseName', $databaseName);
- }
+ /**
+ * Returns the value of {@link $databaseName} parameter.
+ * @return string
+ */
+ public function getDatabaseName()
+ {
+ return $this->databaseName;
+ }
- /**
- * Returns the value of {@link $databaseName} parameter.
- * @return string
- */
- public function getDatabaseName() {
- return $this->databaseName;
- }
+ /**
+ * Sets the value of {@link $collectionName} parameter.
+ * @param string $collectionName
+ */
+ public function setCollectionName($collectionName)
+ {
+ $this->setString('collectionName', $collectionName);
+ }
- /**
- * Sets the value of {@link $collectionName} parameter.
- * @param string $collectionName
- */
- public function setCollectionName($collectionName) {
- $this->setString('collectionName', $collectionName);
- }
+ /**
+ * Returns the value of {@link $collectionName} parameter.
+ * @return string
+ */
+ public function getCollectionName()
+ {
+ return $this->collectionName;
+ }
- /**
- * Returns the value of {@link $collectionName} parameter.
- * @return string
- */
- public function getCollectionName() {
- return $this->collectionName;
- }
+ /**
+ * Sets the value of {@link $userName} parameter.
+ * @param string $userName
+ */
+ public function setUserName($userName)
+ {
+ $this->setString('userName', $userName, true);
+ }
- /**
- * Sets the value of {@link $userName} parameter.
- * @param string $userName
- */
- public function setUserName($userName) {
- $this->setString('userName', $userName, true);
- }
+ /**
+ * Returns the value of {@link $userName} parameter.
+ * @return string
+ */
+ public function getUserName()
+ {
+ return $this->userName;
+ }
- /**
- * Returns the value of {@link $userName} parameter.
- * @return string
- */
- public function getUserName() {
- return $this->userName;
- }
+ /**
+ * Sets the value of {@link $password} parameter.
+ * @param string $password
+ */
+ public function setPassword($password)
+ {
+ $this->setString('password', $password, true);
+ }
- /**
- * Sets the value of {@link $password} parameter.
- * @param string $password
- */
- public function setPassword($password) {
- $this->setString('password', $password, true);
- }
+ /**
+ * Returns the value of {@link $password} parameter.
+ * @return string
+ */
+ public function getPassword()
+ {
+ return $this->password;
+ }
- /**
- * Returns the value of {@link $password} parameter.
- * @return string
- */
- public function getPassword() {
- return $this->password;
- }
+ /**
+ * Sets the value of {@link $timeout} parameter.
+ * @param int $timeout
+ */
+ public function setTimeout($timeout)
+ {
+ $this->setPositiveInteger('timeout', $timeout);
+ }
- /**
- * Sets the value of {@link $timeout} parameter.
- * @param int $timeout
- */
- public function setTimeout($timeout) {
- $this->setPositiveInteger('timeout', $timeout);
- }
+ /**
+ * Returns the value of {@link $timeout} parameter.
+ * @return int
+ */
+ public function getTimeout()
+ {
+ return $this->timeout;
+ }
+ /**
+ * Returns the mongodb connection.
+ * @return Mongo
+ */
+ public function getConnection()
+ {
+ return $this->connection;
+ }
- /**
- * Returns the value of {@link $timeout} parameter.
- * @return int
- */
- public function getTimeout() {
- return $this->timeout;
- }
- /**
- * Returns the mongodb connection.
- * @return Mongo
- */
- public function getConnection() {
- return $this->connection;
- }
-
- /**
- * Returns the active mongodb collection.
- * @return MongoCollection
- */
- public function getCollection() {
- return $this->collection;
- }
+ /**
+ * Returns the active mongodb collection.
+ * @return MongoCollection
+ */
+ public function getCollection()
+ {
+ return $this->collection;
+ }
}
diff --git a/src/Appenders/NullAppender.php b/src/Appenders/NullAppender.php
index e599013..dd41040 100644
--- a/src/Appenders/NullAppender.php
+++ b/src/Appenders/NullAppender.php
@@ -27,18 +27,19 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/null.html Appender documentation
*/
-class NullAppender extends AbstractAppender {
+class NullAppender extends AbstractAppender
+{
+ /**
+ * This appender does not require a layout.
+ */
+ protected $requiresLayout = false;
- /**
- * This appender does not require a layout.
- */
- protected $requiresLayout = false;
-
- /**
- * Do nothing.
- *
- * @param LoggingEvent $event
- */
- public function append(LoggingEvent $event) {
- }
+ /**
+ * Do nothing.
+ *
+ * @param LoggingEvent $event
+ */
+ public function append(LoggingEvent $event)
+ {
+ }
}
diff --git a/src/Appenders/PdoAppender.php b/src/Appenders/PdoAppender.php
index 87c81bf..431b9d6 100644
--- a/src/Appenders/PdoAppender.php
+++ b/src/Appenders/PdoAppender.php
@@ -44,244 +44,263 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/pdo.html Appender documentation
*/
-class PDOAppender extends AbstractAppender {
+class PdoAppender extends AbstractAppender
+{
+ // ******************************************
+ // *** Configurable parameters ***
+ // ******************************************
- // ******************************************
- // *** Configurable parameters ***
- // ******************************************
+ /**
+ * DSN string used to connect to the database.
+ * @see http://www.php.net/manual/en/pdo.construct.php
+ */
+ protected $dsn;
- /**
- * DSN string used to connect to the database.
- * @see http://www.php.net/manual/en/pdo.construct.php
- */
- protected $dsn;
+ /** Database user name. */
+ protected $user;
- /** Database user name. */
- protected $user;
+ /** Database password. */
+ protected $password;
- /** Database password. */
- protected $password;
+ /**
+ * The insert query.
+ *
+ * The __TABLE__ placeholder will be replaced by the table name from
+ * {@link $table}.
+ *
+ * The questionmarks are part of the prepared statement, and they must
+ * match the number of conversion specifiers in {@link insertPattern}.
+ */
+ protected $insertSQL = "INSERT INTO __TABLE__ (timestamp, logger, level, message, thread, file, line) VALUES (?, ?, ?, ?, ?, ?, ?)";
- /**
- * The insert query.
- *
- * The __TABLE__ placeholder will be replaced by the table name from
- * {@link $table}.
- *
- * The questionmarks are part of the prepared statement, and they must
- * match the number of conversion specifiers in {@link insertPattern}.
- */
- protected $insertSQL = "INSERT INTO __TABLE__ (timestamp, logger, level, message, thread, file, line) VALUES (?, ?, ?, ?, ?, ?, ?)";
+ /**
+ * A comma separated list of {@link LoggerPatternLayout} format strings
+ * which replace the "?" in {@link $insertSQL}.
+ *
+ * Must contain the same number of comma separated conversion patterns as
+ * there are question marks in {@link insertSQL}.
+ *
+ * @see LoggerPatternLayout For conversion patterns.
+ */
+ protected $insertPattern = "%date{Y-m-d H:i:s},%logger,%level,%message,%pid,%file,%line";
- /**
- * A comma separated list of {@link LoggerPatternLayout} format strings
- * which replace the "?" in {@link $insertSQL}.
- *
- * Must contain the same number of comma separated conversion patterns as
- * there are question marks in {@link insertSQL}.
- *
- * @see LoggerPatternLayout For conversion patterns.
- */
- protected $insertPattern = "%date{Y-m-d H:i:s},%logger,%level,%message,%pid,%file,%line";
+ /** Name of the table to which to append log events. */
+ protected $table = 'log4php_log';
- /** Name of the table to which to append log events. */
- protected $table = 'log4php_log';
-
- /** The number of recconect attempts to make on failed append. */
- protected $reconnectAttempts = 3;
+ /** The number of recconect attempts to make on failed append. */
+ protected $reconnectAttempts = 3;
- // ******************************************
- // *** Private memebers ***
- // ******************************************
+ // ******************************************
+ // *** Private memebers ***
+ // ******************************************
- /**
- * The PDO instance.
- * @var PDO
- */
- protected $db;
+ /**
+ * The PDO instance.
+ * @var PDO
+ */
+ protected $db;
- /**
- * Prepared statement for the insert query.
- * @var PDOStatement
- */
- protected $preparedInsert;
+ /**
+ * Prepared statement for the insert query.
+ * @var PDOStatement
+ */
+ protected $preparedInsert;
- /** This appender does not require a layout. */
- protected $requiresLayout = false;
+ /** This appender does not require a layout. */
+ protected $requiresLayout = false;
- // ******************************************
- // *** Appender methods ***
- // ******************************************
+ // ******************************************
+ // *** Appender methods ***
+ // ******************************************
- /**
- * Acquires a database connection based on parameters.
- * Parses the insert pattern to create a chain of converters which will be
- * used in forming query parameters from logging events.
- */
- public function activateOptions() {
- try {
- $this->establishConnection();
- } catch (PDOException $e) {
- $this->warn("Failed connecting to database. Closing appender. Error: " . $e->getMessage());
- $this->close();
- return;
- }
+ /**
+ * Acquires a database connection based on parameters.
+ * Parses the insert pattern to create a chain of converters which will be
+ * used in forming query parameters from logging events.
+ */
+ public function activateOptions()
+ {
+ try {
+ $this->establishConnection();
+ } catch (PDOException $e) {
+ $this->warn("Failed connecting to database. Closing appender. Error: " . $e->getMessage());
+ $this->close();
- // Parse the insert patterns; pattern parts are comma delimited
- $pieces = explode(',', $this->insertPattern);
- $converterMap = PatternLayout::getDefaultConverterMap();
- foreach($pieces as $pattern) {
- $parser = new PatternParser($pattern, $converterMap);
- $this->converters[] = $parser->parse();
- }
+ return;
+ }
- $this->closed = false;
- }
+ // Parse the insert patterns; pattern parts are comma delimited
+ $pieces = explode(',', $this->insertPattern);
+ $converterMap = PatternLayout::getDefaultConverterMap();
+ foreach ($pieces as $pattern) {
+ $parser = new PatternParser($pattern, $converterMap);
+ $this->converters[] = $parser->parse();
+ }
- /**
- * Connects to the database, and prepares the insert query.
- * @throws PDOException If connect or prepare fails.
- */
- protected function establishConnection() {
- // Acquire database connection
- $this->db = new PDO($this->dsn, $this->user, $this->password);
- $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ $this->closed = false;
+ }
- // Prepare the insert statement
- $insertSQL = str_replace('__TABLE__', $this->table, $this->insertSQL);
- $this->preparedInsert = $this->db->prepare($insertSQL);
- }
+ /**
+ * Connects to the database, and prepares the insert query.
+ * @throws PDOException If connect or prepare fails.
+ */
+ protected function establishConnection()
+ {
+ // Acquire database connection
+ $this->db = new PDO($this->dsn, $this->user, $this->password);
+ $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- /**
- * Appends a new event to the database.
- *
- * If writing to database fails, it will retry by re-establishing the
- * connection up to $reconnectAttempts times. If writing still fails,
- * the appender will close.
- */
- public function append(LoggingEvent $event) {
+ // Prepare the insert statement
+ $insertSQL = str_replace('__TABLE__', $this->table, $this->insertSQL);
+ $this->preparedInsert = $this->db->prepare($insertSQL);
+ }
- for ($attempt = 1; $attempt <= $this->reconnectAttempts + 1; $attempt++) {
- try {
- // Attempt to write to database
- $this->preparedInsert->execute($this->format($event));
- $this->preparedInsert->closeCursor();
- break;
- } catch (PDOException $e) {
- $this->warn("Failed writing to database: ". $e->getMessage());
+ /**
+ * Appends a new event to the database.
+ *
+ * If writing to database fails, it will retry by re-establishing the
+ * connection up to $reconnectAttempts times. If writing still fails,
+ * the appender will close.
+ */
+ public function append(LoggingEvent $event)
+ {
+ for ($attempt = 1; $attempt <= $this->reconnectAttempts + 1; $attempt++) {
+ try {
+ // Attempt to write to database
+ $this->preparedInsert->execute($this->format($event));
+ $this->preparedInsert->closeCursor();
+ break;
+ } catch (PDOException $e) {
+ $this->warn("Failed writing to database: ". $e->getMessage());
- // Close the appender if it's the last attempt
- if ($attempt > $this->reconnectAttempts) {
- $this->warn("Failed writing to database after {$this->reconnectAttempts} reconnect attempts. Closing appender.");
- $this->close();
- // Otherwise reconnect and try to write again
- } else {
- $this->warn("Attempting a reconnect (attempt $attempt of {$this->reconnectAttempts}).");
- $this->establishConnection();
- }
- }
- }
- }
+ // Close the appender if it's the last attempt
+ if ($attempt > $this->reconnectAttempts) {
+ $this->warn("Failed writing to database after {$this->reconnectAttempts} reconnect attempts. Closing appender.");
+ $this->close();
+ // Otherwise reconnect and try to write again
+ } else {
+ $this->warn("Attempting a reconnect (attempt $attempt of {$this->reconnectAttempts}).");
+ $this->establishConnection();
+ }
+ }
+ }
+ }
- /**
- * Converts the logging event to a series of database parameters by using
- * the converter chain which was set up on activation.
- */
- protected function format(LoggingEvent $event) {
- $params = array();
- foreach($this->converters as $converter) {
- $buffer = '';
- while ($converter !== null) {
- $converter->format($buffer, $event);
- $converter = $converter->next;
- }
- $params[] = $buffer;
- }
- return $params;
- }
+ /**
+ * Converts the logging event to a series of database parameters by using
+ * the converter chain which was set up on activation.
+ */
+ protected function format(LoggingEvent $event)
+ {
+ $params = array();
+ foreach ($this->converters as $converter) {
+ $buffer = '';
+ while ($converter !== null) {
+ $converter->format($buffer, $event);
+ $converter = $converter->next;
+ }
+ $params[] = $buffer;
+ }
- /**
- * Closes the connection to the logging database
- */
- public function close() {
- // Close the connection (if any)
- $this->db = null;
+ return $params;
+ }
- // Close the appender
- $this->closed = true;
- }
+ /**
+ * Closes the connection to the logging database
+ */
+ public function close()
+ {
+ // Close the connection (if any)
+ $this->db = null;
- // ******************************************
- // *** Accessor methods ***
- // ******************************************
+ // Close the appender
+ $this->closed = true;
+ }
- /**
- * Returns the active database handle or null if not established.
- * @return PDO
- */
- public function getDatabaseHandle() {
- return $this->db;
- }
+ // ******************************************
+ // *** Accessor methods ***
+ // ******************************************
- /** Sets the username. */
- public function setUser($user) {
- $this->setString('user', $user);
- }
+ /**
+ * Returns the active database handle or null if not established.
+ * @return PDO
+ */
+ public function getDatabaseHandle()
+ {
+ return $this->db;
+ }
- /** Returns the username. */
- public function getUser($user) {
- return $this->user;
- }
+ /** Sets the username. */
+ public function setUser($user)
+ {
+ $this->setString('user', $user);
+ }
- /** Sets the password. */
- public function setPassword($password) {
- $this->setString('password', $password);
- }
+ /** Returns the username. */
+ public function getUser($user)
+ {
+ return $this->user;
+ }
- /** Returns the password. */
- public function getPassword($password) {
- return $this->password;
- }
+ /** Sets the password. */
+ public function setPassword($password)
+ {
+ $this->setString('password', $password);
+ }
- /** Sets the insert SQL. */
- public function setInsertSQL($sql) {
- $this->setString('insertSQL', $sql);
- }
+ /** Returns the password. */
+ public function getPassword($password)
+ {
+ return $this->password;
+ }
- /** Returns the insert SQL. */
- public function getInsertSQL($sql) {
- return $this->insertSQL;
- }
+ /** Sets the insert SQL. */
+ public function setInsertSQL($sql)
+ {
+ $this->setString('insertSQL', $sql);
+ }
- /** Sets the insert pattern. */
- public function setInsertPattern($pattern) {
- $this->setString('insertPattern', $pattern);
- }
+ /** Returns the insert SQL. */
+ public function getInsertSQL($sql)
+ {
+ return $this->insertSQL;
+ }
- /** Returns the insert pattern. */
- public function getInsertPattern($pattern) {
- return $this->insertPattern;
- }
+ /** Sets the insert pattern. */
+ public function setInsertPattern($pattern)
+ {
+ $this->setString('insertPattern', $pattern);
+ }
- /** Sets the table name. */
- public function setTable($table) {
- $this->setString('table', $table);
- }
+ /** Returns the insert pattern. */
+ public function getInsertPattern($pattern)
+ {
+ return $this->insertPattern;
+ }
- /** Returns the table name. */
- public function getTable($table) {
- return $this->table;
- }
+ /** Sets the table name. */
+ public function setTable($table)
+ {
+ $this->setString('table', $table);
+ }
- /** Sets the DSN string. */
- public function setDSN($dsn) {
- $this->setString('dsn', $dsn);
- }
+ /** Returns the table name. */
+ public function getTable($table)
+ {
+ return $this->table;
+ }
- /** Returns the DSN string. */
- public function getDSN($dsn) {
- return $this->setString('dsn', $dsn);
- }
+ /** Sets the DSN string. */
+ public function setDSN($dsn)
+ {
+ $this->setString('dsn', $dsn);
+ }
+
+ /** Returns the DSN string. */
+ public function getDSN($dsn)
+ {
+ return $this->setString('dsn', $dsn);
+ }
}
diff --git a/src/Appenders/PhpAppender.php b/src/Appenders/PhpAppender.php
index 287c56a..6d6c6c9 100644
--- a/src/Appenders/PhpAppender.php
+++ b/src/Appenders/PhpAppender.php
@@ -35,16 +35,17 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/php.html Appender documentation
*/
-class PhpAppender extends AbstractAppender {
-
- public function append(LoggingEvent $event) {
- $level = $event->getLevel();
- if($level->isGreaterOrEqual(Level::getLevelError())) {
- trigger_error($this->layout->format($event), E_USER_ERROR);
- } else if ($level->isGreaterOrEqual(Level::getLevelWarn())) {
- trigger_error($this->layout->format($event), E_USER_WARNING);
- } else {
- trigger_error($this->layout->format($event), E_USER_NOTICE);
- }
- }
+class PhpAppender extends AbstractAppender
+{
+ public function append(LoggingEvent $event)
+ {
+ $level = $event->getLevel();
+ if ($level->isGreaterOrEqual(Level::getLevelError())) {
+ trigger_error($this->layout->format($event), E_USER_ERROR);
+ } elseif ($level->isGreaterOrEqual(Level::getLevelWarn())) {
+ trigger_error($this->layout->format($event), E_USER_WARNING);
+ } else {
+ trigger_error($this->layout->format($event), E_USER_NOTICE);
+ }
+ }
}
diff --git a/src/Appenders/RollingFileAppender.php b/src/Appenders/RollingFileAppender.php
index 8d54a4a..8e7024b 100644
--- a/src/Appenders/RollingFileAppender.php
+++ b/src/Appenders/RollingFileAppender.php
@@ -18,8 +18,6 @@
namespace Apache\Log4php\Appenders;
-use Apache\Log4php\LoggingEvent;
-
/**
* RollingFileAppender writes logging events to a specified file. The
* file is rolled over after a specified size has been reached.
@@ -40,264 +38,280 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/rolling-file.html Appender documentation
*/
-class RollingFileAppender extends FileAppender {
+class RollingFileAppender extends FileAppender
+{
+ /** Compressing backup files is done in chunks, this determines how large. */
+ const COMPRESS_CHUNK_SIZE = 102400; // 100KB
- /** Compressing backup files is done in chunks, this determines how large. */
- const COMPRESS_CHUNK_SIZE = 102400; // 100KB
+ /**
+ * The maximum size (in bytes) that the output file is allowed to reach
+ * before being rolled over to backup files.
+ *
+ * The default maximum file size is 10MB (10485760 bytes). Maximum value
+ * for this option may depend on the file system.
+ *
+ * @var integer
+ */
+ protected $maxFileSize = 10485760;
- /**
- * The maximum size (in bytes) that the output file is allowed to reach
- * before being rolled over to backup files.
- *
- * The default maximum file size is 10MB (10485760 bytes). Maximum value
- * for this option may depend on the file system.
- *
- * @var integer
- */
- protected $maxFileSize = 10485760;
+ /**
+ * Set the maximum number of backup files to keep around.
+ *
+ * Determines how many backup files are kept before the oldest is erased.
+ * This option takes a positive integer value. If set to zero, then there
+ * will be no backup files and the log file will be truncated when it
+ * reaches <var>maxFileSize</var>.
+ *
+ * There is one backup file by default.
+ *
+ * @var integer
+ */
+ protected $maxBackupIndex = 1;
- /**
- * Set the maximum number of backup files to keep around.
- *
- * Determines how many backup files are kept before the oldest is erased.
- * This option takes a positive integer value. If set to zero, then there
- * will be no backup files and the log file will be truncated when it
- * reaches <var>maxFileSize</var>.
- *
- * There is one backup file by default.
- *
- * @var integer
- */
- protected $maxBackupIndex = 1;
+ /**
+ * The <var>compress</var> parameter determindes the compression with zlib.
+ * If set to true, the rollover files are compressed and saved with the .gz extension.
+ * @var boolean
+ */
+ protected $compress = false;
- /**
- * The <var>compress</var> parameter determindes the compression with zlib.
- * If set to true, the rollover files are compressed and saved with the .gz extension.
- * @var boolean
- */
- protected $compress = false;
+ /**
+ * Set to true in the constructor if PHP >= 5.3.0. In that case clearstatcache
+ * supports conditional clearing of statistics.
+ * @var boolean
+ * @see http://php.net/manual/en/function.clearstatcache.php
+ */
+ private $clearConditional = false;
- /**
- * Set to true in the constructor if PHP >= 5.3.0. In that case clearstatcache
- * supports conditional clearing of statistics.
- * @var boolean
- * @see http://php.net/manual/en/function.clearstatcache.php
- */
- private $clearConditional = false;
+ /**
+ * Get the maximum size that the output file is allowed to reach
+ * before being rolled over to backup files.
+ * @return integer
+ */
+ public function getMaximumFileSize()
+ {
+ return $this->maxFileSize;
+ }
- /**
- * Get the maximum size that the output file is allowed to reach
- * before being rolled over to backup files.
- * @return integer
- */
- public function getMaximumFileSize() {
- return $this->maxFileSize;
- }
+ public function __construct($name = '')
+ {
+ parent::__construct($name);
+ if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
+ $this->clearConditional = true;
+ }
+ }
- public function __construct($name = '') {
- parent::__construct($name);
- if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
- $this->clearConditional = true;
- }
- }
+ /**
+ * Implements the usual roll over behaviour.
+ *
+ * If MaxBackupIndex is positive, then files File.1, ..., File.MaxBackupIndex -1 are renamed to File.2, ..., File.MaxBackupIndex.
+ * Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.
+ *
+ * If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created.
+ *
+ * Rollover must be called while the file is locked so that it is safe for concurrent access.
+ *
+ * @throws LoggerException If any part of the rollover procedure fails.
+ */
+ private function rollOver()
+ {
+ // If maxBackups <= 0, then there is no file renaming to be done.
+ if ($this->maxBackupIndex > 0) {
+ // Delete the oldest file, to keep Windows happy.
+ $file = $this->file . '.' . $this->maxBackupIndex;
- /**
- * Implements the usual roll over behaviour.
- *
- * If MaxBackupIndex is positive, then files File.1, ..., File.MaxBackupIndex -1 are renamed to File.2, ..., File.MaxBackupIndex.
- * Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.
- *
- * If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created.
- *
- * Rollover must be called while the file is locked so that it is safe for concurrent access.
- *
- * @throws LoggerException If any part of the rollover procedure fails.
- */
- private function rollOver() {
- // If maxBackups <= 0, then there is no file renaming to be done.
- if($this->maxBackupIndex > 0) {
- // Delete the oldest file, to keep Windows happy.
- $file = $this->file . '.' . $this->maxBackupIndex;
+ if (file_exists($file) && !unlink($file)) {
+ throw new LoggerException("Unable to delete oldest backup file from [$file].");
+ }
- if (file_exists($file) && !unlink($file)) {
- throw new LoggerException("Unable to delete oldest backup file from [$file].");
- }
+ // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
+ $this->renameArchievedLogs($this->file);
- // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
- $this->renameArchievedLogs($this->file);
+ // Backup the active file
+ $this->moveToBackup($this->file);
+ }
- // Backup the active file
- $this->moveToBackup($this->file);
- }
+ // Truncate the active file
+ ftruncate($this->fp, 0);
+ rewind($this->fp);
+ }
- // Truncate the active file
- ftruncate($this->fp, 0);
- rewind($this->fp);
- }
+ private function moveToBackup($source)
+ {
+ if ($this->compress) {
+ $target = $source . '.1.gz';
+ $this->compressFile($source, $target);
+ } else {
+ $target = $source . '.1';
+ copy($source, $target);
+ }
+ }
- private function moveToBackup($source) {
- if ($this->compress) {
- $target = $source . '.1.gz';
- $this->compressFile($source, $target);
- } else {
- $target = $source . '.1';
- copy($source, $target);
- }
- }
+ private function compressFile($source, $target)
+ {
+ $target = 'compress.zlib://' . $target;
- private function compressFile($source, $target) {
- $target = 'compress.zlib://' . $target;
+ $fin = fopen($source, 'rb');
+ if ($fin === false) {
+ throw new LoggerException("Unable to open file for reading: [$source].");
+ }
- $fin = fopen($source, 'rb');
- if ($fin === false) {
- throw new LoggerException("Unable to open file for reading: [$source].");
- }
+ $fout = fopen($target, 'wb');
+ if ($fout === false) {
+ throw new LoggerException("Unable to open file for writing: [$target].");
+ }
- $fout = fopen($target, 'wb');
- if ($fout === false) {
- throw new LoggerException("Unable to open file for writing: [$target].");
- }
+ while (!feof($fin)) {
+ $chunk = fread($fin, self::COMPRESS_CHUNK_SIZE);
+ if (false === fwrite($fout, $chunk)) {
+ throw new LoggerException("Failed writing to compressed file.");
+ }
+ }
- while (!feof($fin)) {
- $chunk = fread($fin, self::COMPRESS_CHUNK_SIZE);
- if (false === fwrite($fout, $chunk)) {
- throw new LoggerException("Failed writing to compressed file.");
- }
- }
+ fclose($fin);
+ fclose($fout);
+ }
- fclose($fin);
- fclose($fout);
- }
+ private function renameArchievedLogs($fileName)
+ {
+ for ($i = $this->maxBackupIndex - 1; $i >= 1; $i--) {
- private function renameArchievedLogs($fileName) {
- for($i = $this->maxBackupIndex - 1; $i >= 1; $i--) {
+ $source = $fileName . "." . $i;
+ if ($this->compress) {
+ $source .= '.gz';
+ }
- $source = $fileName . "." . $i;
- if ($this->compress) {
- $source .= '.gz';
- }
+ if (file_exists($source)) {
+ $target = $fileName . '.' . ($i + 1);
+ if ($this->compress) {
+ $target .= '.gz';
+ }
- if(file_exists($source)) {
- $target = $fileName . '.' . ($i + 1);
- if ($this->compress) {
- $target .= '.gz';
- }
+ rename($source, $target);
+ }
+ }
+ }
- rename($source, $target);
- }
- }
- }
+ /**
+ * Writes a string to the target file. Opens file if not already open.
+ * @param string $string Data to write.
+ */
+ protected function write($string)
+ {
+ // Lazy file open
+ if (!isset($this->fp)) {
+ if ($this->openFile() === false) {
+ return; // Do not write if file open failed.
+ }
+ }
- /**
- * Writes a string to the target file. Opens file if not already open.
- * @param string $string Data to write.
- */
- protected function write($string) {
- // Lazy file open
- if(!isset($this->fp)) {
- if ($this->openFile() === false) {
- return; // Do not write if file open failed.
- }
- }
+ // Lock the file while writing and possible rolling over
+ if (flock($this->fp, LOCK_EX)) {
- // Lock the file while writing and possible rolling over
- if(flock($this->fp, LOCK_EX)) {
+ // Write to locked file
+ if (fwrite($this->fp, $string) === false) {
+ $this->warn("Failed writing to file. Closing appender.");
+ $this->closed = true;
+ }
- // Write to locked file
- if(fwrite($this->fp, $string) === false) {
- $this->warn("Failed writing to file. Closing appender.");
- $this->closed = true;
- }
+ // Stats cache must be cleared, otherwise filesize() returns cached results
+ // If supported (PHP 5.3+), clear only the state cache for the target file
+ if ($this->clearConditional) {
+ clearstatcache(true, $this->file);
+ } else {
+ clearstatcache();
+ }
- // Stats cache must be cleared, otherwise filesize() returns cached results
- // If supported (PHP 5.3+), clear only the state cache for the target file
- if ($this->clearConditional) {
- clearstatcache(true, $this->file);
- } else {
- clearstatcache();
- }
+ // Rollover if needed
+ if (filesize($this->file) > $this->maxFileSize) {
+ try {
+ $this->rollOver();
+ } catch (LoggerException $ex) {
+ $this->warn("Rollover failed: " . $ex->getMessage() . " Closing appender.");
+ $this->closed = true;
+ }
+ }
- // Rollover if needed
- if (filesize($this->file) > $this->maxFileSize) {
- try {
- $this->rollOver();
- } catch (LoggerException $ex) {
- $this->warn("Rollover failed: " . $ex->getMessage() . " Closing appender.");
- $this->closed = true;
- }
- }
+ flock($this->fp, LOCK_UN);
+ } else {
+ $this->warn("Failed locking file for writing. Closing appender.");
+ $this->closed = true;
+ }
+ }
- flock($this->fp, LOCK_UN);
- } else {
- $this->warn("Failed locking file for writing. Closing appender.");
- $this->closed = true;
- }
- }
+ public function activateOptions()
+ {
+ parent::activateOptions();
- public function activateOptions() {
- parent::activateOptions();
+ if ($this->compress && !extension_loaded('zlib')) {
+ $this->warn("The 'zlib' extension is required for file compression. Disabling compression.");
+ $this->compression = false;
+ }
+ }
- if ($this->compress && !extension_loaded('zlib')) {
- $this->warn("The 'zlib' extension is required for file compression. Disabling compression.");
- $this->compression = false;
- }
- }
+ /**
+ * Set the 'maxBackupIndex' parameter.
+ * @param integer $maxBackupIndex
+ */
+ public function setMaxBackupIndex($maxBackupIndex)
+ {
+ $this->setPositiveInteger('maxBackupIndex', $maxBackupIndex);
+ }
- /**
- * Set the 'maxBackupIndex' parameter.
- * @param integer $maxBackupIndex
- */
- public function setMaxBackupIndex($maxBackupIndex) {
- $this->setPositiveInteger('maxBackupIndex', $maxBackupIndex);
- }
+ /**
+ * Returns the 'maxBackupIndex' parameter.
+ * @return integer
+ */
+ public function getMaxBackupIndex()
+ {
+ return $this->maxBackupIndex;
+ }
- /**
- * Returns the 'maxBackupIndex' parameter.
- * @return integer
- */
- public function getMaxBackupIndex() {
- return $this->maxBackupIndex;
- }
+ /**
+ * Set the 'maxFileSize' parameter.
+ * @param mixed $maxFileSize
+ */
+ public function setMaxFileSize($maxFileSize)
+ {
+ $this->setFileSize('maxFileSize', $maxFileSize);
+ }
- /**
- * Set the 'maxFileSize' parameter.
- * @param mixed $maxFileSize
- */
- public function setMaxFileSize($maxFileSize) {
- $this->setFileSize('maxFileSize', $maxFileSize);
- }
+ /**
+ * Returns the 'maxFileSize' parameter.
+ * @return integer
+ */
+ public function getMaxFileSize()
+ {
+ return $this->maxFileSize;
+ }
- /**
- * Returns the 'maxFileSize' parameter.
- * @return integer
- */
- public function getMaxFileSize() {
- return $this->maxFileSize;
- }
+ /**
+ * Set the 'maxFileSize' parameter (kept for backward compatibility).
+ * @param mixed $maxFileSize
+ * @deprecated Use setMaxFileSize() instead.
+ */
+ public function setMaximumFileSize($maxFileSize)
+ {
+ $this->warn("The 'maximumFileSize' parameter is deprecated. Use 'maxFileSize' instead.");
- /**
- * Set the 'maxFileSize' parameter (kept for backward compatibility).
- * @param mixed $maxFileSize
- * @deprecated Use setMaxFileSize() instead.
- */
- public function setMaximumFileSize($maxFileSize) {
- $this->warn("The 'maximumFileSize' parameter is deprecated. Use 'maxFileSize' instead.");
- return $this->setMaxFileSize($maxFileSize);
- }
+ return $this->setMaxFileSize($maxFileSize);
+ }
- /**
- * Sets the 'compress' parameter.
- * @param boolean $compress
- */
- public function setCompress($compress) {
- $this->setBoolean('compress', $compress);
- }
+ /**
+ * Sets the 'compress' parameter.
+ * @param boolean $compress
+ */
+ public function setCompress($compress)
+ {
+ $this->setBoolean('compress', $compress);
+ }
- /**
- * Returns the 'compress' parameter.
- * @param boolean
- */
- public function getCompress() {
- return $this->compress;
- }
+ /**
+ * Returns the 'compress' parameter.
+ * @param boolean
+ */
+ public function getCompress()
+ {
+ return $this->compress;
+ }
}
diff --git a/src/Appenders/SocketAppender.php b/src/Appenders/SocketAppender.php
index 024c91f..4f8325b 100644
--- a/src/Appenders/SocketAppender.php
+++ b/src/Appenders/SocketAppender.php
@@ -35,89 +35,100 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/socket.html Appender documentation
*/
-class SocketAppender extends AbstractAppender {
+class SocketAppender extends AbstractAppender
+{
+ /**
+ * Target host.
+ * @see http://php.net/manual/en/function.fsockopen.php
+ */
+ protected $remoteHost;
- /**
- * Target host.
- * @see http://php.net/manual/en/function.fsockopen.php
- */
- protected $remoteHost;
+ /** Target port */
+ protected $port = 4446;
- /** Target port */
- protected $port = 4446;
+ /** Connection timeout in ms. */
+ protected $timeout;
- /** Connection timeout in ms. */
- protected $timeout;
+ // ******************************************
+ // *** Appender methods ***
+ // ******************************************
- // ******************************************
- // *** Appender methods ***
- // ******************************************
+ /** Override the default layout to use serialized. */
+ public function getDefaultLayout()
+ {
+ return new SerializedLayout();
+ }
- /** Override the default layout to use serialized. */
- public function getDefaultLayout() {
- return new SerializedLayout();
- }
+ public function activateOptions()
+ {
+ if (empty($this->remoteHost)) {
+ $this->warn("Required parameter [remoteHost] not set. Closing appender.");
+ $this->closed = true;
- public function activateOptions() {
- if (empty($this->remoteHost)) {
- $this->warn("Required parameter [remoteHost] not set. Closing appender.");
- $this->closed = true;
- return;
- }
+ return;
+ }
- if (empty($this->timeout)) {
- $this->timeout = ini_get("default_socket_timeout");
- }
+ if (empty($this->timeout)) {
+ $this->timeout = ini_get("default_socket_timeout");
+ }
- $this->closed = false;
- }
+ $this->closed = false;
+ }
- public function append(LoggingEvent $event) {
- $socket = fsockopen($this->remoteHost, $this->port, $errno, $errstr, $this->timeout);
- if ($socket === false) {
- $this->warn("Could not open socket to {$this->remoteHost}:{$this->port}. Closing appender.");
- $this->closed = true;
- return;
- }
+ public function append(LoggingEvent $event)
+ {
+ $socket = fsockopen($this->remoteHost, $this->port, $errno, $errstr, $this->timeout);
+ if ($socket === false) {
+ $this->warn("Could not open socket to {$this->remoteHost}:{$this->port}. Closing appender.");
+ $this->closed = true;
- if (false === fwrite($socket, $this->layout->format($event))) {
- $this->warn("Error writing to socket. Closing appender.");
- $this->closed = true;
- }
- fclose($socket);
- }
+ return;
+ }
- // ******************************************
- // *** Accessor methods ***
- // ******************************************
+ if (false === fwrite($socket, $this->layout->format($event))) {
+ $this->warn("Error writing to socket. Closing appender.");
+ $this->closed = true;
+ }
+ fclose($socket);
+ }
- /** Sets the target host. */
- public function setRemoteHost($hostname) {
- $this->setString('remoteHost', $hostname);
- }
+ // ******************************************
+ // *** Accessor methods ***
+ // ******************************************
- /** Sets the target port */
- public function setPort($port) {
- $this->setPositiveInteger('port', $port);
- }
+ /** Sets the target host. */
+ public function setRemoteHost($hostname)
+ {
+ $this->setString('remoteHost', $hostname);
+ }
- /** Sets the timeout. */
- public function setTimeout($timeout) {
- $this->setPositiveInteger('timeout', $timeout);
- }
+ /** Sets the target port */
+ public function setPort($port)
+ {
+ $this->setPositiveInteger('port', $port);
+ }
- /** Returns the target host. */
- public function getRemoteHost() {
- return $this->getRemoteHost();
- }
+ /** Sets the timeout. */
+ public function setTimeout($timeout)
+ {
+ $this->setPositiveInteger('timeout', $timeout);
+ }
- /** Returns the target port. */
- public function getPort() {
- return $this->port;
- }
+ /** Returns the target host. */
+ public function getRemoteHost()
+ {
+ return $this->getRemoteHost();
+ }
- /** Returns the timeout */
- public function getTimeout() {
- return $this->timeout;
- }
+ /** Returns the target port. */
+ public function getPort()
+ {
+ return $this->port;
+ }
+
+ /** Returns the timeout */
+ public function getTimeout()
+ {
+ return $this->timeout;
+ }
}
diff --git a/src/Appenders/SyslogAppender.php b/src/Appenders/SyslogAppender.php
index ae7351b..b6fc0c0 100644
--- a/src/Appenders/SyslogAppender.php
+++ b/src/Appenders/SyslogAppender.php
@@ -70,235 +70,253 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/appenders/syslog.html Appender documentation
*/
-class SyslogAppender extends AbstractAppender {
+class SyslogAppender extends AbstractAppender
+{
+ /**
+ * The ident string is added to each message. Typically the name of your application.
+ *
+ * @var string
+ */
+ protected $ident = "Apache log4php";
- /**
- * The ident string is added to each message. Typically the name of your application.
- *
- * @var string
- */
- protected $ident = "Apache log4php";
+ /**
+ * The syslog priority to use when overriding priority. This setting is
+ * required if {@link overridePriority} is set to true.
+ *
+ * @var string
+ */
+ protected $priority;
- /**
- * The syslog priority to use when overriding priority. This setting is
- * required if {@link overridePriority} is set to true.
- *
- * @var string
- */
- protected $priority;
+ /**
+ * The option used when opening the syslog connection.
+ *
+ * @var string
+ */
+ protected $option = 'PID|CONS';
- /**
- * The option used when opening the syslog connection.
- *
- * @var string
- */
- protected $option = 'PID|CONS';
+ /**
+ * The facility value indicates the source of the message.
+ *
+ * @var string
+ */
+ protected $facility = 'USER';
- /**
- * The facility value indicates the source of the message.
- *
- * @var string
- */
- protected $facility = 'USER';
+ /**
+ * If set to true, the message priority will always use the value defined
+ * in {@link $priority}, otherwise the priority will be determined by the
+ * message's log level.
+ *
+ * @var string
+ */
+ protected $overridePriority = false;
- /**
- * If set to true, the message priority will always use the value defined
- * in {@link $priority}, otherwise the priority will be determined by the
- * message's log level.
- *
- * @var string
- */
- protected $overridePriority = false;
+ /**
+ * Holds the int value of the {@link $priority}.
+ * @var int
+ */
+ private $intPriority;
- /**
- * Holds the int value of the {@link $priority}.
- * @var int
- */
- private $intPriority;
+ /**
+ * Holds the int value of the {@link $facility}.
+ * @var int
+ */
+ private $intFacility;
- /**
- * Holds the int value of the {@link $facility}.
- * @var int
- */
- private $intFacility;
+ /**
+ * Holds the int value of the {@link $option}.
+ * @var int
+ */
+ private $intOption;
- /**
- * Holds the int value of the {@link $option}.
- * @var int
- */
- private $intOption;
+ /**
+ * Sets the {@link $ident}.
+ *
+ * @param string $ident
+ */
+ public function setIdent($ident)
+ {
+ $this->ident = $ident;
+ }
- /**
- * Sets the {@link $ident}.
- *
- * @param string $ident
- */
- public function setIdent($ident) {
- $this->ident = $ident;
- }
+ /**
+ * Sets the {@link $priority}.
+ *
+ * @param string $priority
+ */
+ public function setPriority($priority)
+ {
+ $this->priority = $priority;
+ }
- /**
- * Sets the {@link $priority}.
- *
- * @param string $priority
- */
- public function setPriority($priority) {
- $this->priority = $priority;
- }
+ /**
+ * Sets the {@link $facility}.
+ *
+ * @param string $facility
+ */
+ public function setFacility($facility)
+ {
+ $this->facility = $facility;
+ }
- /**
- * Sets the {@link $facility}.
- *
- * @param string $facility
- */
- public function setFacility($facility) {
- $this->facility = $facility;
- }
+ /**
+ * Sets the {@link $overridePriority}.
+ *
+ * @param string $overridePriority
+ */
+ public function setOverridePriority($overridePriority)
+ {
+ $this->overridePriority = $overridePriority;
+ }
- /**
- * Sets the {@link $overridePriority}.
- *
- * @param string $overridePriority
- */
- public function setOverridePriority($overridePriority) {
- $this->overridePriority = $overridePriority;
- }
+ /**
+ * Sets the 'option' parameter.
+ *
+ * @param string $option
+ */
+ public function setOption($option)
+ {
+ $this->option = $option;
+ }
- /**
- * Sets the 'option' parameter.
- *
- * @param string $option
- */
- public function setOption($option) {
- $this->option = $option;
- }
+ /**
+ * Returns the 'ident' parameter.
+ *
+ * @return string $ident
+ */
+ public function getIdent()
+ {
+ return $this->ident;
+ }
- /**
- * Returns the 'ident' parameter.
- *
- * @return string $ident
- */
- public function getIdent() {
- return $this->ident;
- }
+ /**
+ * Returns the 'priority' parameter.
+ *
+ * @return string
+ */
+ public function getPriority()
+ {
+ return $this->priority;
+ }
- /**
- * Returns the 'priority' parameter.
- *
- * @return string
- */
- public function getPriority() {
- return $this->priority;
- }
+ /**
+ * Returns the 'facility' parameter.
+ *
+ * @return string
+ */
+ public function getFacility()
+ {
+ return $this->facility;
+ }
- /**
- * Returns the 'facility' parameter.
- *
- * @return string
- */
- public function getFacility() {
- return $this->facility;
- }
+ /**
+ * Returns the 'overridePriority' parameter.
+ *
+ * @return string
+ */
+ public function getOverridePriority()
+ {
+ return $this->overridePriority;
+ }
- /**
- * Returns the 'overridePriority' parameter.
- *
- * @return string
- */
- public function getOverridePriority() {
- return $this->overridePriority;
- }
+ /**
+ * Returns the 'option' parameter.
+ *
+ * @return string
+ */
+ public function getOption()
+ {
+ return $this->option;
+ }
- /**
- * Returns the 'option' parameter.
- *
- * @return string
- */
- public function getOption() {
- return $this->option;
- }
+ public function activateOptions()
+ {
+ $this->intPriority = $this->parsePriority();
+ $this->intOption = $this->parseOption();
+ $this->intFacility = $this->parseFacility();
+ $this->closed = false;
+ }
- public function activateOptions() {
- $this->intPriority = $this->parsePriority();
- $this->intOption = $this->parseOption();
- $this->intFacility = $this->parseFacility();
+ public function close()
+ {
+ if ($this->closed != true) {
+ closelog();
+ $this->closed = true;
+ }
+ }
- $this->closed = false;
- }
+ /**
+ * Appends the event to syslog.
+ *
+ * Log is opened and closed each time because if it is not closed, it
+ * can cause the Apache httpd server to log to whatever ident/facility
+ * was used in openlog().
+ *
+ * @see http://www.php.net/manual/en/function.syslog.php#97843
+ */
+ public function append(LoggingEvent $event)
+ {
+ $priority = $this->getSyslogPriority($event->getLevel());
+ $message = $this->layout->format($event);
- public function close() {
- if($this->closed != true) {
- closelog();
- $this->closed = true;
- }
- }
+ openlog($this->ident, $this->intOption, $this->intFacility);
+ syslog($priority, $message);
+ closelog();
+ }
- /**
- * Appends the event to syslog.
- *
- * Log is opened and closed each time because if it is not closed, it
- * can cause the Apache httpd server to log to whatever ident/facility
- * was used in openlog().
- *
- * @see http://www.php.net/manual/en/function.syslog.php#97843
- */
- public function append(LoggingEvent $event) {
- $priority = $this->getSyslogPriority($event->getLevel());
- $message = $this->layout->format($event);
+ /** Determines which syslog priority to use based on the given level. */
+ private function getSyslogPriority(Level $level)
+ {
+ if ($this->overridePriority) {
+ return $this->intPriority;
+ }
- openlog($this->ident, $this->intOption, $this->intFacility);
- syslog($priority, $message);
- closelog();
- }
+ return $level->getSyslogEquivalent();
+ }
- /** Determines which syslog priority to use based on the given level. */
- private function getSyslogPriority(Level $level) {
- if($this->overridePriority) {
- return $this->intPriority;
- }
- return $level->getSyslogEquivalent();
- }
+ /** Parses a syslog option string and returns the correspodning int value. */
+ private function parseOption()
+ {
+ $value = 0;
+ $options = explode('|', $this->option);
- /** Parses a syslog option string and returns the correspodning int value. */
- private function parseOption() {
- $value = 0;
- $options = explode('|', $this->option);
+ foreach ($options as $option) {
+ if (!empty($option)) {
+ $constant = "LOG_" . trim($option);
+ if (defined($constant)) {
+ $value |= constant($constant);
+ } else {
+ trigger_error("log4php: Invalid syslog option provided: $option. Whole option string: {$this->option}.", E_USER_WARNING);
+ }
+ }
+ }
- foreach($options as $option) {
- if (!empty($option)) {
- $constant = "LOG_" . trim($option);
- if (defined($constant)) {
- $value |= constant($constant);
- } else {
- trigger_error("log4php: Invalid syslog option provided: $option. Whole option string: {$this->option}.", E_USER_WARNING);
- }
- }
- }
- return $value;
- }
+ return $value;
+ }
- /** Parses the facility string and returns the corresponding int value. */
- private function parseFacility() {
- if (!empty($this->facility)) {
- $constant = "LOG_" . trim($this->facility);
- if (defined($constant)) {
- return constant($constant);
- } else {
- trigger_error("log4php: Invalid syslog facility provided: {$this->facility}.", E_USER_WARNING);
- }
- }
- }
+ /** Parses the facility string and returns the corresponding int value. */
+ private function parseFacility()
+ {
+ if (!empty($this->facility)) {
+ $constant = "LOG_" . trim($this->facility);
+ if (defined($constant)) {
+ return constant($constant);
+ } else {
+ trigger_error("log4php: Invalid syslog facility provided: {$this->facility}.", E_USER_WARNING);
+ }
+ }
+ }
- /** Parses the priority string and returns the corresponding int value. */
- private function parsePriority() {
- if (!empty($this->priority)) {
- $constant = "LOG_" . trim($this->priority);
- if (defined($constant)) {
- return constant($constant);
- } else {
- trigger_error("log4php: Invalid syslog priority provided: {$this->priority}.", E_USER_WARNING);
- }
- }
- }
+ /** Parses the priority string and returns the corresponding int value. */
+ private function parsePriority()
+ {
+ if (!empty($this->priority)) {
+ $constant = "LOG_" . trim($this->priority);
+ if (defined($constant)) {
+ return constant($constant);
+ } else {
+ trigger_error("log4php: Invalid syslog priority provided: {$this->priority}.", E_USER_WARNING);
+ }
+ }
+ }
}
diff --git a/src/Autoloader.php b/src/Autoloader.php
index fe6b8d3..d4fc666 100644
--- a/src/Autoloader.php
+++ b/src/Autoloader.php
@@ -23,31 +23,31 @@
*/
class Autoloader
{
- const BASE_NAMESPACE = 'Apache\\Log4php\\';
+ const BASE_NAMESPACE = 'Apache\\Log4php\\';
- public function autoload($class)
- {
- // Base directory for the namespace prefix
- $baseDir = __DIR__ . '/../src/';
+ public function autoload($class)
+ {
+ // Base directory for the namespace prefix
+ $baseDir = __DIR__ . '/../src/';
- // Skip classes which are not in base namespace
- $len = strlen(self::BASE_NAMESPACE);
- if (strncmp(self::BASE_NAMESPACE, $class, $len) !== 0) {
- return;
- }
+ // Skip classes which are not in base namespace
+ $len = strlen(self::BASE_NAMESPACE);
+ if (strncmp(self::BASE_NAMESPACE, $class, $len) !== 0) {
+ return;
+ }
- // Locate the class in base dir, based on namespace
- $classPath = str_replace('\\', '/', substr($class, $len));
- $file = $baseDir . $classPath . '.php';
+ // Locate the class in base dir, based on namespace
+ $classPath = str_replace('\\', '/', substr($class, $len));
+ $file = $baseDir . $classPath . '.php';
- // If the file exists, require it
- if (file_exists($file)) {
- require $file;
- }
- }
+ // If the file exists, require it
+ if (file_exists($file)) {
+ require $file;
+ }
+ }
- public function register()
- {
- spl_autoload_register(array($this, 'autoload'));
- }
+ public function register()
+ {
+ spl_autoload_register(array($this, 'autoload'));
+ }
}
diff --git a/src/Configurable.php b/src/Configurable.php
index 352aa23..258e6ec 100644
--- a/src/Configurable.php
+++ b/src/Configurable.php
@@ -29,90 +29,98 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @since 2.2
*/
-abstract class Configurable {
+abstract class Configurable
+{
+ /** Setter function for boolean type. */
+ protected function setBoolean($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toBooleanEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a boolean value. Property not changed.");
+ }
+ }
- /** Setter function for boolean type. */
- protected function setBoolean($property, $value) {
- try {
- $this->$property = OptionConverter::toBooleanEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a boolean value. Property not changed.");
- }
- }
+ /** Setter function for integer type. */
+ protected function setInteger($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toIntegerEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected an integer. Property not changed.");
+ }
+ }
- /** Setter function for integer type. */
- protected function setInteger($property, $value) {
- try {
- $this->$property = OptionConverter::toIntegerEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected an integer. Property not changed.");
- }
- }
+ /** Setter function for Level values. */
+ protected function setLevel($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toLevelEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a level value. Property not changed.");
+ }
+ }
- /** Setter function for Level values. */
- protected function setLevel($property, $value) {
- try {
- $this->$property = OptionConverter::toLevelEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a level value. Property not changed.");
- }
- }
+ /** Setter function for integer type. */
+ protected function setPositiveInteger($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toPositiveIntegerEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a positive integer. Property not changed.");
+ }
+ }
- /** Setter function for integer type. */
- protected function setPositiveInteger($property, $value) {
- try {
- $this->$property = OptionConverter::toPositiveIntegerEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a positive integer. Property not changed.");
- }
- }
+ /** Setter for file size. */
+ protected function setFileSize($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toFileSizeEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a file size value. Property not changed.");
+ }
+ }
- /** Setter for file size. */
- protected function setFileSize($property, $value) {
- try {
- $this->$property = OptionConverter::toFileSizeEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a file size value. Property not changed.");
- }
- }
+ /** Setter function for numeric type. */
+ protected function setNumeric($property, $value)
+ {
+ try {
+ $this->$property = OptionConverter::toNumericEx($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a number. Property not changed.");
+ }
+ }
- /** Setter function for numeric type. */
- protected function setNumeric($property, $value) {
- try {
- $this->$property = OptionConverter::toNumericEx($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a number. Property not changed.");
- }
- }
+ /** Setter function for string type. */
+ protected function setString($property, $value, $nullable = false)
+ {
+ if ($value === null) {
+ if ($nullable) {
+ $this->$property= null;
+ } else {
+ $this->warn("Null value given for '$property' property. Expected a string. Property not changed.");
+ }
+ } else {
+ try {
+ $value = OptionConverter::toStringEx($value);
+ $this->$property = OptionConverter::substConstants($value);
+ } catch (Exception $ex) {
+ $value = var_export($value, true);
+ $this->warn("Invalid value given for '$property' property: [$value]. Expected a string. Property not changed.");
+ }
+ }
+ }
- /** Setter function for string type. */
- protected function setString($property, $value, $nullable = false) {
- if ($value === null) {
- if($nullable) {
- $this->$property= null;
- } else {
- $this->warn("Null value given for '$property' property. Expected a string. Property not changed.");
- }
- } else {
- try {
- $value = OptionConverter::toStringEx($value);
- $this->$property = OptionConverter::substConstants($value);
- } catch (Exception $ex) {
- $value = var_export($value, true);
- $this->warn("Invalid value given for '$property' property: [$value]. Expected a string. Property not changed.");
- }
- }
- }
-
- /** Triggers a warning. */
- protected function warn($message) {
- $class = get_class($this);
- trigger_error("log4php: $class: $message", E_USER_WARNING);
- }
+ /** Triggers a warning. */
+ protected function warn($message)
+ {
+ $class = get_class($this);
+ trigger_error("log4php: $class: $message", E_USER_WARNING);
+ }
}
diff --git a/src/Configuration/ConfiguratorInterface.php b/src/Configuration/ConfiguratorInterface.php
index a4a8e21..f58fc41 100644
--- a/src/Configuration/ConfiguratorInterface.php
+++ b/src/Configuration/ConfiguratorInterface.php
@@ -27,15 +27,15 @@
*/
interface ConfiguratorInterface
{
- /**
- * Configures log4php based on the given configuration.
- *
- * All configurators implementations must implement this interface.
- *
- * @param Hierarchy $hierarchy The hierarchy on which to perform
- * the configuration.
- * @param mixed $input Either path to the config file or the
- * configuration as an array.
- */
- public function configure(Hierarchy $hierarchy, $input = null);
-}
\ No newline at end of file
+ /**
+ * Configures log4php based on the given configuration.
+ *
+ * All configurators implementations must implement this interface.
+ *
+ * @param Hierarchy $hierarchy The hierarchy on which to perform
+ * the configuration.
+ * @param mixed $input Either path to the config file or the
+ * configuration as an array.
+ */
+ public function configure(Hierarchy $hierarchy, $input = null);
+}
diff --git a/src/Configuration/DefaultConfigurator.php b/src/Configuration/DefaultConfigurator.php
index 9e4e6bd..7ef223b 100644
--- a/src/Configuration/DefaultConfigurator.php
+++ b/src/Configuration/DefaultConfigurator.php
@@ -36,24 +36,24 @@
*/
class DefaultConfigurator implements ConfiguratorInterface
{
- /** XML configuration file format. */
- const FORMAT_XML = 'xml';
+ /** XML configuration file format. */
+ const FORMAT_XML = 'xml';
- /** PHP configuration file format. */
- const FORMAT_PHP = 'php';
+ /** PHP configuration file format. */
+ const FORMAT_PHP = 'php';
- /** INI (properties) configuration file format. */
- const FORMAT_INI = 'ini';
+ /** INI (properties) configuration file format. */
+ const FORMAT_INI = 'ini';
- /** Defines which adapter should be used for parsing which format. */
- private $adapters = array(
- self::FORMAT_XML => 'XmlAdapter',
- self::FORMAT_INI => 'IniAdapter',
- self::FORMAT_PHP => 'PhpAdapter',
- );
+ /** Defines which adapter should be used for parsing which format. */
+ private $adapters = array(
+ self::FORMAT_XML => 'XmlAdapter',
+ self::FORMAT_INI => 'IniAdapter',
+ self::FORMAT_PHP => 'PhpAdapter',
+ );
- /** Default configuration; used if no configuration file is provided. */
- private static $defaultConfiguration = array(
+ /** Default configuration; used if no configuration file is provided. */
+ private static $defaultConfiguration = array(
'threshold' => 'ALL',
'rootLogger' => array(
'level' => 'DEBUG',
@@ -64,449 +64,475 @@
'class' => '\\Apache\\Log4php\\Appenders\\EchoAppender'
),
),
- );
+ );
- /** Holds the appenders before they are linked to loggers. */
- private $appenders = array();
+ /** Holds the appenders before they are linked to loggers. */
+ private $appenders = array();
- /**
- * Configures log4php based on the given configuration. The input can
- * either be a path to the config file, or a PHP array holding the
- * configuration.
- *
- * If no configuration is given, or if the given configuration cannot be
- * parsed for whatever reason, a warning will be issued, and log4php
- * will use the default configuration contained in
- * {@link $defaultConfiguration}.
- *
- * @param Hierarchy $hierarchy The hierarchy on which to perform
- * the configuration.
- * @param string|array $input Either path to the config file or the
- * configuration as an array. If not set, default configuration
- * will be used.
- */
- public function configure(Hierarchy $hierarchy, $input = null) {
- $config = $this->parse($input);
- $this->doConfigure($hierarchy, $config);
- }
+ /**
+ * Configures log4php based on the given configuration. The input can
+ * either be a path to the config file, or a PHP array holding the
+ * configuration.
+ *
+ * If no configuration is given, or if the given configuration cannot be
+ * parsed for whatever reason, a warning will be issued, and log4php
+ * will use the default configuration contained in
+ * {@link $defaultConfiguration}.
+ *
+ * @param Hierarchy $hierarchy The hierarchy on which to perform
+ * the configuration.
+ * @param string|array $input Either path to the config file or the
+ * configuration as an array. If not set, default configuration
+ * will be used.
+ */
+ public function configure(Hierarchy $hierarchy, $input = null)
+ {
+ $config = $this->parse($input);
+ $this->doConfigure($hierarchy, $config);
+ }
- /**
- * Parses the given configuration and returns the parsed configuration
- * as a PHP array. Does not perform any configuration.
- *
- * If no configuration is given, or if the given configuration cannot be
- * parsed for whatever reason, a warning will be issued, and the default
- * configuration will be returned ({@link $defaultConfiguration}).
- *
- * @param string|array $input Either path to the config file or the
- * configuration as an array. If not set, default configuration
- * will be used.
- * @return array The parsed configuration.
- */
- public function parse($input) {
- // No input - use default configuration
- if (!isset($input)) {
- $config = self::$defaultConfiguration;
- }
+ /**
+ * Parses the given configuration and returns the parsed configuration
+ * as a PHP array. Does not perform any configuration.
+ *
+ * If no configuration is given, or if the given configuration cannot be
+ * parsed for whatever reason, a warning will be issued, and the default
+ * configuration will be returned ({@link $defaultConfiguration}).
+ *
+ * @param string|array $input Either path to the config file or the
+ * configuration as an array. If not set, default configuration
+ * will be used.
+ * @return array The parsed configuration.
+ */
+ public function parse($input)
+ {
+ // No input - use default configuration
+ if (!isset($input)) {
+ $config = self::$defaultConfiguration;
+ }
- // Array input - contains configuration within the array
- else if (is_array($input)) {
- $config = $input;
- }
+ // Array input - contains configuration within the array
+ else if (is_array($input)) {
+ $config = $input;
+ }
- // String input - contains path to configuration file
- else if (is_string($input)) {
- try {
- $config = $this->parseFile($input);
- } catch (LoggerException $e) {
- $this->warn("Configuration failed. " . $e->getMessage() . " Using default configuration.");
- $config = self::$defaultConfiguration;
- }
- }
+ // String input - contains path to configuration file
+ else if (is_string($input)) {
+ try {
+ $config = $this->parseFile($input);
+ } catch (LoggerException $e) {
+ $this->warn("Configuration failed. " . $e->getMessage() . " Using default configuration.");
+ $config = self::$defaultConfiguration;
+ }
+ }
- // Anything else is an error
- else {
- $this->warn("Invalid configuration param given. Reverting to default configuration.");
- $config = self::$defaultConfiguration;
- }
+ // Anything else is an error
+ else {
+ $this->warn("Invalid configuration param given. Reverting to default configuration.");
+ $config = self::$defaultConfiguration;
+ }
- return $config;
- }
+ return $config;
+ }
- /**
- * Returns the default log4php configuration.
- * @return array
- */
- public static function getDefaultConfiguration() {
- return self::$defaultConfiguration;
- }
+ /**
+ * Returns the default log4php configuration.
+ * @return array
+ */
+ public static function getDefaultConfiguration()
+ {
+ return self::$defaultConfiguration;
+ }
- /**
- * Loads the configuration file from the given URL, determines which
- * adapter to use, converts the configuration to a PHP array and
- * returns it.
- *
- * @param string $url Path to the config file.
- * @return The configuration from the config file, as a PHP array.
- * @throws LoggerException If the configuration file cannot be loaded, or
- * if the parsing fails.
- */
- private function parseFile($url) {
+ /**
+ * Loads the configuration file from the given URL, determines which
+ * adapter to use, converts the configuration to a PHP array and
+ * returns it.
+ *
+ * @param string $url Path to the config file.
+ * @return The configuration from the config file, as a PHP array.
+ * @throws LoggerException If the configuration file cannot be loaded, or
+ * if the parsing fails.
+ */
+ private function parseFile($url)
+ {
+ if (!file_exists($url)) {
+ throw new LoggerException("File not found at [$url].");
+ }
- if (!file_exists($url)) {
- throw new LoggerException("File not found at [$url].");
- }
+ $type = $this->getConfigType($url);
+ $adapterClass = "Apache\\Log4php\\Configuration\\Adapters\\" . $this->adapters[$type];
- $type = $this->getConfigType($url);
- $adapterClass = "Apache\\Log4php\\Configuration\\Adapters\\" . $this->adapters[$type];
+ $adapter = new $adapterClass();
- $adapter = new $adapterClass();
- return $adapter->convert($url);
- }
+ return $adapter->convert($url);
+ }
- /** Determines configuration file type based on the file extension. */
- private function getConfigType($url) {
- $info = pathinfo($url);
- $ext = strtolower($info['extension']);
+ /** Determines configuration file type based on the file extension. */
+ private function getConfigType($url)
+ {
+ $info = pathinfo($url);
+ $ext = strtolower($info['extension']);
- switch($ext) {
- case 'xml':
- return self::FORMAT_XML;
+ switch ($ext) {
+ case 'xml':
+ return self::FORMAT_XML;
- case 'ini':
- case 'properties':
- return self::FORMAT_INI;
+ case 'ini':
+ case 'properties':
+ return self::FORMAT_INI;
- case 'php':
- return self::FORMAT_PHP;
+ case 'php':
+ return self::FORMAT_PHP;
- default:
- throw new LoggerException("Unsupported configuration file extension: $ext");
- }
- }
+ default:
+ throw new LoggerException("Unsupported configuration file extension: $ext");
+ }
+ }
- /**
- * Constructs the logger hierarchy based on configuration.
- *
- * @param Hierarchy $hierarchy
- * @param array $config
- */
- private function doConfigure(Hierarchy $hierarchy, $config) {
- if (isset($config['threshold'])) {
- $threshold = Level::toLevel($config['threshold']);
- if (isset($threshold)) {
- $hierarchy->setThreshold($threshold);
- } else {
- $this->warn("Invalid threshold value [{$config['threshold']}] specified. Ignoring threshold definition.");
- }
- }
+ /**
+ * Constructs the logger hierarchy based on configuration.
+ *
+ * @param Hierarchy $hierarchy
+ * @param array $config
+ */
+ private function doConfigure(Hierarchy $hierarchy, $config)
+ {
+ if (isset($config['threshold'])) {
+ $threshold = Level::toLevel($config['threshold']);
+ if (isset($threshold)) {
+ $hierarchy->setThreshold($threshold);
+ } else {
+ $this->warn("Invalid threshold value [{$config['threshold']}] specified. Ignoring threshold definition.");
+ }
+ }
- // Configure appenders and add them to the appender pool
- if (isset($config['appenders']) && is_array($config['appenders'])) {
- foreach($config['appenders'] as $name => $appenderConfig) {
- $this->configureAppender($name, $appenderConfig);
- }
- }
+ // Configure appenders and add them to the appender pool
+ if (isset($config['appenders']) && is_array($config['appenders'])) {
+ foreach ($config['appenders'] as $name => $appenderConfig) {
+ $this->configureAppender($name, $appenderConfig);
+ }
+ }
- // Configure root logger
- if (isset($config['rootLogger'])) {
- $this->configureRootLogger($hierarchy, $config['rootLogger']);
- }
+ // Configure root logger
+ if (isset($config['rootLogger'])) {
+ $this->configureRootLogger($hierarchy, $config['rootLogger']);
+ }
- // Configure loggers
- if (isset($config['loggers']) && is_array($config['loggers'])) {
- foreach($config['loggers'] as $loggerName => $loggerConfig) {
- $this->configureOtherLogger($hierarchy, $loggerName, $loggerConfig);
- }
- }
+ // Configure loggers
+ if (isset($config['loggers']) && is_array($config['loggers'])) {
+ foreach ($config['loggers'] as $loggerName => $loggerConfig) {
+ $this->configureOtherLogger($hierarchy, $loggerName, $loggerConfig);
+ }
+ }
- // Configure renderers
- if (isset($config['renderers']) && is_array($config['renderers'])) {
- foreach($config['renderers'] as $rendererConfig) {
- $this->configureRenderer($hierarchy, $rendererConfig);
- }
- }
+ // Configure renderers
+ if (isset($config['renderers']) && is_array($config['renderers'])) {
+ foreach ($config['renderers'] as $rendererConfig) {
+ $this->configureRenderer($hierarchy, $rendererConfig);
+ }
+ }
- if (isset($config['defaultRenderer'])) {
- $this->configureDefaultRenderer($hierarchy, $config['defaultRenderer']);
- }
- }
+ if (isset($config['defaultRenderer'])) {
+ $this->configureDefaultRenderer($hierarchy, $config['defaultRenderer']);
+ }
+ }
- private function configureRenderer(Hierarchy $hierarchy, $config) {
- if (empty($config['renderingClass'])) {
- $this->warn("Rendering class not specified. Skipping renderer definition.");
- return;
- }
+ private function configureRenderer(Hierarchy $hierarchy, $config)
+ {
+ if (empty($config['renderingClass'])) {
+ $this->warn("Rendering class not specified. Skipping renderer definition.");
- if (empty($config['renderedClass'])) {
- $this->warn("Rendered class not specified. Skipping renderer definition.");
- return;
- }
+ return;
+ }
- // Error handling performed by RendererMap
- $hierarchy->getRendererMap()->addRenderer($config['renderedClass'], $config['renderingClass']);
- }
+ if (empty($config['renderedClass'])) {
+ $this->warn("Rendered class not specified. Skipping renderer definition.");
- private function configureDefaultRenderer(Hierarchy $hierarchy, $class) {
- if (empty($class)) {
- $this->warn("Rendering class not specified. Skipping default renderer definition.");
- return;
- }
+ return;
+ }
- // Error handling performed by RendererMap
- $hierarchy->getRendererMap()->setDefaultRenderer($class);
- }
+ // Error handling performed by RendererMap
+ $hierarchy->getRendererMap()->addRenderer($config['renderedClass'], $config['renderingClass']);
+ }
- /**
- * Configures an appender based on given config and saves it to
- * {@link $appenders} array so it can be later linked to loggers.
- * @param string $name Appender name.
- * @param array $config Appender configuration options.
- */
- private function configureAppender($name, $config) {
+ private function configureDefaultRenderer(Hierarchy $hierarchy, $class)
+ {
+ if (empty($class)) {
+ $this->warn("Rendering class not specified. Skipping default renderer definition.");
- // TODO: add this check to other places where it might be useful
- if (!is_array($config)) {
- $type = gettype($config);
- $this->warn("Invalid configuration provided for appender [$name]. Expected an array, found <$type>. Skipping appender definition.");
- return;
- }
+ return;
+ }
- // Parse appender class
- $class = $config['class'];
- if (empty($class)) {
- $this->warn("No class given for appender [$name]. Skipping appender definition.");
- return;
- }
+ // Error handling performed by RendererMap
+ $hierarchy->getRendererMap()->setDefaultRenderer($class);
+ }
- // Instantiate the appender
- if (class_exists($class)) {
- $appender = new $class($name);
- } else {
- // Try the default namespace
- $nsClass = "\\Apache\\Log4php\\Appenders\\$class";
- if (class_exists($nsClass)) {
- $appender = new $nsClass($name);
- }
- }
+ /**
+ * Configures an appender based on given config and saves it to
+ * {@link $appenders} array so it can be later linked to loggers.
+ * @param string $name Appender name.
+ * @param array $config Appender configuration options.
+ */
+ private function configureAppender($name, $config)
+ {
+ // TODO: add this check to other places where it might be useful
+ if (!is_array($config)) {
+ $type = gettype($config);
+ $this->warn("Invalid configuration provided for appender [$name]. Expected an array, found <$type>. Skipping appender definition.");
- if (!isset($appender)) {
- $this->warn("Invalid class [$class] given for appender [$name]. Class does not exist. Skipping appender definition.");
- return;
- }
+ return;
+ }
- if (!($appender instanceof AbstractAppender)) {
- $this->warn("Invalid class [$class] given for appender [$name]. Not a valid Appender class. Skipping appender definition.");
- return;
- }
+ // Parse appender class
+ $class = $config['class'];
+ if (empty($class)) {
+ $this->warn("No class given for appender [$name]. Skipping appender definition.");
- // Parse the appender threshold
- if (isset($config['threshold'])) {
- $threshold = Level::toLevel($config['threshold']);
- if ($threshold instanceof Level) {
- $appender->setThreshold($threshold);
- } else {
- $this->warn("Invalid threshold value [{$config['threshold']}] specified for appender [$name]. Ignoring threshold definition.");
- }
- }
+ return;
+ }
- // Parse the appender layout
- if ($appender->requiresLayout() && isset($config['layout'])) {
- $this->createAppenderLayout($appender, $config['layout']);
- }
+ // Instantiate the appender
+ if (class_exists($class)) {
+ $appender = new $class($name);
+ } else {
+ // Try the default namespace
+ $nsClass = "\\Apache\\Log4php\\Appenders\\$class";
+ if (class_exists($nsClass)) {
+ $appender = new $nsClass($name);
+ }
+ }
- // Parse filters
- if (isset($config['filters']) && is_array($config['filters'])) {
- foreach($config['filters'] as $filterConfig) {
- $this->createAppenderFilter($appender, $filterConfig);
- }
- }
+ if (!isset($appender)) {
+ $this->warn("Invalid class [$class] given for appender [$name]. Class does not exist. Skipping appender definition.");
- // Set options if any
- if (isset($config['params'])) {
- $this->setOptions($appender, $config['params']);
- }
+ return;
+ }
- // Activate and save for later linking to loggers
- $appender->activateOptions();
- $this->appenders[$name] = $appender;
- }
+ if (!($appender instanceof AbstractAppender)) {
+ $this->warn("Invalid class [$class] given for appender [$name]. Not a valid Appender class. Skipping appender definition.");
- /**
- * Parses layout config, creates the layout and links it to the appender.
- * @param AbstractAppender $appender
- * @param array $config Layout configuration.
- */
- private function createAppenderLayout(AbstractAppender $appender, $config) {
- $name = $appender->getName();
- $class = $config['class'];
- if (empty($class)) {
- $this->warn("Layout class not specified for appender [$name]. Reverting to default layout.");
- return;
- }
+ return;
+ }
- if (class_exists($class)) {
- $layout = new $class();
- } else {
- $nsClass = "Apache\\Log4php\\Layouts\\$class";
- if (class_exists($nsClass)) {
- $layout = new $nsClass();
- }
- }
+ // Parse the appender threshold
+ if (isset($config['threshold'])) {
+ $threshold = Level::toLevel($config['threshold']);
+ if ($threshold instanceof Level) {
+ $appender->setThreshold($threshold);
+ } else {
+ $this->warn("Invalid threshold value [{$config['threshold']}] specified for appender [$name]. Ignoring threshold definition.");
+ }
+ }
- if (!isset($layout)) {
- $this->warn("Nonexistant layout class [$class] specified for appender [$name]. Reverting to default layout.");
- return;
- }
+ // Parse the appender layout
+ if ($appender->requiresLayout() && isset($config['layout'])) {
+ $this->createAppenderLayout($appender, $config['layout']);
+ }
+ // Parse filters
+ if (isset($config['filters']) && is_array($config['filters'])) {
+ foreach ($config['filters'] as $filterConfig) {
+ $this->createAppenderFilter($appender, $filterConfig);
+ }
+ }
- if (!($layout instanceof AbstractLayout)) {
- $this->warn("Invalid layout class [$class] sepcified for appender [$name]. Reverting to default layout.");
- return;
- }
+ // Set options if any
+ if (isset($config['params'])) {
+ $this->setOptions($appender, $config['params']);
+ }
- if (isset($config['params'])) {
- $this->setOptions($layout, $config['params']);
- }
+ // Activate and save for later linking to loggers
+ $appender->activateOptions();
+ $this->appenders[$name] = $appender;
+ }
- $layout->activateOptions();
- $appender->setLayout($layout);
- }
+ /**
+ * Parses layout config, creates the layout and links it to the appender.
+ * @param AbstractAppender $appender
+ * @param array $config Layout configuration.
+ */
+ private function createAppenderLayout(AbstractAppender $appender, $config)
+ {
+ $name = $appender->getName();
+ $class = $config['class'];
+ if (empty($class)) {
+ $this->warn("Layout class not specified for appender [$name]. Reverting to default layout.");
- /**
- * Parses filter config, creates the filter and adds it to the appender's
- * filter chain.
- * @param Appender $appender
- * @param array $config Filter configuration.
- */
- private function createAppenderFilter(AbstractAppender $appender, $config) {
- $name = $appender->getName();
- $class = $config['class'];
+ return;
+ }
- if (class_exists($class)) {
- $filter = new $class();
- } else {
- $nsClass = "Apache\\Log4php\\Filters\\$class";
- if (class_exists($nsClass)) {
- $filter = new $nsClass();
- }
- }
+ if (class_exists($class)) {
+ $layout = new $class();
+ } else {
+ $nsClass = "Apache\\Log4php\\Layouts\\$class";
+ if (class_exists($nsClass)) {
+ $layout = new $nsClass();
+ }
+ }
- if (!isset($filter)) {
- $this->warn("Nonexistant filter class [$class] specified on appender [$name]. Skipping filter definition.");
- return;
- }
+ if (!isset($layout)) {
+ $this->warn("Nonexistant layout class [$class] specified for appender [$name]. Reverting to default layout.");
- if (!($filter instanceof AbstractFilter)) {
- $this->warn("Invalid filter class [$class] sepcified on appender [$name]. Skipping filter definition.");
- return;
- }
+ return;
+ }
- if (isset($config['params'])) {
- $this->setOptions($filter, $config['params']);
- }
+ if (!($layout instanceof AbstractLayout)) {
+ $this->warn("Invalid layout class [$class] sepcified for appender [$name]. Reverting to default layout.");
- $filter->activateOptions();
- $appender->addFilter($filter);
- }
+ return;
+ }
- /**
- * Configures the root logger
- * @see configureLogger()
- */
- private function configureRootLogger(Hierarchy $hierarchy, $config) {
- $logger = $hierarchy->getRootLogger();
- $this->configureLogger($logger, $config);
- }
+ if (isset($config['params'])) {
+ $this->setOptions($layout, $config['params']);
+ }
- /**
- * Configures a logger which is not root.
- * @see configureLogger()
- */
- private function configureOtherLogger(Hierarchy $hierarchy, $name, $config) {
- // Get logger from hierarchy (this creates it if it doesn't already exist)
- $logger = $hierarchy->getLogger($name);
- $this->configureLogger($logger, $config);
- }
+ $layout->activateOptions();
+ $appender->setLayout($layout);
+ }
- /**
- * Configures a logger.
- *
- * @param Logger $logger The logger to configure
- * @param array $config Logger configuration options.
- */
- private function configureLogger(Logger $logger, $config) {
- $loggerName = $logger->getName();
+ /**
+ * Parses filter config, creates the filter and adds it to the appender's
+ * filter chain.
+ * @param Appender $appender
+ * @param array $config Filter configuration.
+ */
+ private function createAppenderFilter(AbstractAppender $appender, $config)
+ {
+ $name = $appender->getName();
+ $class = $config['class'];
- // Set logger level
- if (isset($config['level'])) {
- $level = Level::toLevel($config['level']);
- if (isset($level)) {
- $logger->setLevel($level);
- } else {
- $this->warn("Invalid level value [{$config['level']}] specified for logger [$loggerName]. Ignoring level definition.");
- }
- }
+ if (class_exists($class)) {
+ $filter = new $class();
+ } else {
+ $nsClass = "Apache\\Log4php\\Filters\\$class";
+ if (class_exists($nsClass)) {
+ $filter = new $nsClass();
+ }
+ }
- // Link appenders to logger
- if (isset($config['appenders'])) {
- foreach($config['appenders'] as $appenderName) {
- if (isset($this->appenders[$appenderName])) {
- $logger->addAppender($this->appenders[$appenderName]);
- } else {
- $this->warn("Nonexistnant appender [$appenderName] linked to logger [$loggerName].");
- }
- }
- }
+ if (!isset($filter)) {
+ $this->warn("Nonexistant filter class [$class] specified on appender [$name]. Skipping filter definition.");
- // Set logger additivity
- if (isset($config['additivity'])) {
- try {
- $additivity = OptionConverter::toBooleanEx($config['additivity'], null);
- $logger->setAdditivity($additivity);
- } catch (LoggerException $ex) {
- $this->warn("Invalid additivity value [{$config['additivity']}] specified for logger [$loggerName]. Ignoring additivity setting.");
- }
- }
- }
+ return;
+ }
- /**
- * Helper method which applies given options to an object which has setters
- * for these options (such as appenders, layouts, etc.).
- *
- * For example, if options are:
- * <code>
- * array(
- * 'file' => '/tmp/myfile.log',
- * 'append' => true
- * )
- * </code>
- *
- * This method will call:
- * <code>
- * $object->setFile('/tmp/myfile.log')
- * $object->setAppend(true)
- * </code>
- *
- * If required setters do not exist, it will produce a warning.
- *
- * @param mixed $object The object to configure.
- * @param unknown_type $options
- */
- private function setOptions($object, $options) {
- foreach($options as $name => $value) {
- $setter = "set$name";
- if (method_exists($object, $setter)) {
- $object->$setter($value);
- } else {
- $class = get_class($object);
- $this->warn("Nonexistant option [$name] specified on [$class]. Skipping.");
- }
- }
- }
+ if (!($filter instanceof AbstractFilter)) {
+ $this->warn("Invalid filter class [$class] sepcified on appender [$name]. Skipping filter definition.");
- /** Helper method to simplify error reporting. */
- private function warn($message) {
- trigger_error("log4php: $message", E_USER_WARNING);
- }
+ return;
+ }
+
+ if (isset($config['params'])) {
+ $this->setOptions($filter, $config['params']);
+ }
+
+ $filter->activateOptions();
+ $appender->addFilter($filter);
+ }
+
+ /**
+ * Configures the root logger
+ * @see configureLogger()
+ */
+ private function configureRootLogger(Hierarchy $hierarchy, $config)
+ {
+ $logger = $hierarchy->getRootLogger();
+ $this->configureLogger($logger, $config);
+ }
+
+ /**
+ * Configures a logger which is not root.
+ * @see configureLogger()
+ */
+ private function configureOtherLogger(Hierarchy $hierarchy, $name, $config)
+ {
+ // Get logger from hierarchy (this creates it if it doesn't already exist)
+ $logger = $hierarchy->getLogger($name);
+ $this->configureLogger($logger, $config);
+ }
+
+ /**
+ * Configures a logger.
+ *
+ * @param Logger $logger The logger to configure
+ * @param array $config Logger configuration options.
+ */
+ private function configureLogger(Logger $logger, $config)
+ {
+ $loggerName = $logger->getName();
+
+ // Set logger level
+ if (isset($config['level'])) {
+ $level = Level::toLevel($config['level']);
+ if (isset($level)) {
+ $logger->setLevel($level);
+ } else {
+ $this->warn("Invalid level value [{$config['level']}] specified for logger [$loggerName]. Ignoring level definition.");
+ }
+ }
+
+ // Link appenders to logger
+ if (isset($config['appenders'])) {
+ foreach ($config['appenders'] as $appenderName) {
+ if (isset($this->appenders[$appenderName])) {
+ $logger->addAppender($this->appenders[$appenderName]);
+ } else {
+ $this->warn("Nonexistnant appender [$appenderName] linked to logger [$loggerName].");
+ }
+ }
+ }
+
+ // Set logger additivity
+ if (isset($config['additivity'])) {
+ try {
+ $additivity = OptionConverter::toBooleanEx($config['additivity'], null);
+ $logger->setAdditivity($additivity);
+ } catch (LoggerException $ex) {
+ $this->warn("Invalid additivity value [{$config['additivity']}] specified for logger [$loggerName]. Ignoring additivity setting.");
+ }
+ }
+ }
+
+ /**
+ * Helper method which applies given options to an object which has setters
+ * for these options (such as appenders, layouts, etc.).
+ *
+ * For example, if options are:
+ * <code>
+ * array(
+ * 'file' => '/tmp/myfile.log',
+ * 'append' => true
+ * )
+ * </code>
+ *
+ * This method will call:
+ * <code>
+ * $object->setFile('/tmp/myfile.log')
+ * $object->setAppend(true)
+ * </code>
+ *
+ * If required setters do not exist, it will produce a warning.
+ *
+ * @param mixed $object The object to configure.
+ * @param unknown_type $options
+ */
+ private function setOptions($object, $options)
+ {
+ foreach ($options as $name => $value) {
+ $setter = "set$name";
+ if (method_exists($object, $setter)) {
+ $object->$setter($value);
+ } else {
+ $class = get_class($object);
+ $this->warn("Nonexistant option [$name] specified on [$class]. Skipping.");
+ }
+ }
+ }
+
+ /** Helper method to simplify error reporting. */
+ private function warn($message)
+ {
+ trigger_error("log4php: $message", E_USER_WARNING);
+ }
}
diff --git a/src/Configuration/adapters/AdapterInterface.php b/src/Configuration/adapters/AdapterInterface.php
index f0fea69..15b565a 100644
--- a/src/Configuration/adapters/AdapterInterface.php
+++ b/src/Configuration/adapters/AdapterInterface.php
@@ -29,7 +29,7 @@
*/
interface AdapterInterface
{
- /** Converts the configuration file to PHP format usable by the configurator. */
- public function convert($input);
+ /** Converts the configuration file to PHP format usable by the configurator. */
+ public function convert($input);
}
diff --git a/src/Configuration/adapters/IniAdapter.php b/src/Configuration/adapters/IniAdapter.php
index 61c003b..fcc50e2 100644
--- a/src/Configuration/adapters/IniAdapter.php
+++ b/src/Configuration/adapters/IniAdapter.php
@@ -28,267 +28,276 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @since 2.2
*/
-class IniAdapter implements AdapterInterface {
+class IniAdapter implements AdapterInterface
+{
+ /** Name to assign to the root logger. */
+ const ROOT_LOGGER_NAME = "root";
- /** Name to assign to the root logger. */
- const ROOT_LOGGER_NAME = "root";
+ /** Prefix used for defining logger additivity. */
+ const ADDITIVITY_PREFIX = "log4php.additivity.";
- /** Prefix used for defining logger additivity. */
- const ADDITIVITY_PREFIX = "log4php.additivity.";
+ /** Prefix used for defining logger threshold. */
+ const THRESHOLD_PREFIX = "log4php.threshold";
- /** Prefix used for defining logger threshold. */
- const THRESHOLD_PREFIX = "log4php.threshold";
+ /** Prefix used for defining the root logger. */
+ const ROOT_LOGGER_PREFIX = "log4php.rootLogger";
- /** Prefix used for defining the root logger. */
- const ROOT_LOGGER_PREFIX = "log4php.rootLogger";
+ /** Prefix used for defining a logger. */
+ const LOGGER_PREFIX = "log4php.logger.";
- /** Prefix used for defining a logger. */
- const LOGGER_PREFIX = "log4php.logger.";
+ /** Prefix used for defining an appender. */
+ const APPENDER_PREFIX = "log4php.appender.";
- /** Prefix used for defining an appender. */
- const APPENDER_PREFIX = "log4php.appender.";
+ /** Prefix used for defining a renderer. */
+ const RENDERER_PREFIX = "log4php.renderer.";
- /** Prefix used for defining a renderer. */
- const RENDERER_PREFIX = "log4php.renderer.";
+ /** Holds the configuration. */
+ private $config = array();
- /** Holds the configuration. */
- private $config = array();
+ /**
+ * Loads and parses the INI configuration file.
+ *
+ * @param string $url Path to the config file.
+ * @throws LoggerException
+ */
+ private function load($url)
+ {
+ if (!file_exists($url)) {
+ throw new LoggerException("File [$url] does not exist.");
+ }
- /**
- * Loads and parses the INI configuration file.
- *
- * @param string $url Path to the config file.
- * @throws LoggerException
- */
- private function load($url) {
- if (!file_exists($url)) {
- throw new LoggerException("File [$url] does not exist.");
- }
+ $properties = @parse_ini_file($url, true);
+ if ($properties === false) {
+ $error = error_get_last();
+ throw new LoggerException("Error parsing configuration file: {$error['message']}");
+ }
- $properties = @parse_ini_file($url, true);
- if ($properties === false) {
- $error = error_get_last();
- throw new LoggerException("Error parsing configuration file: {$error['message']}");
- }
+ return $properties;
+ }
- return $properties;
- }
+ /**
+ * Converts the provided INI configuration file to a PHP array config.
+ *
+ * @param string $path Path to the config file.
+ * @throws LoggerException If the file cannot be loaded or parsed.
+ */
+ public function convert($path)
+ {
+ // Load the configuration
+ $properties = $this->load($path);
- /**
- * Converts the provided INI configuration file to a PHP array config.
- *
- * @param string $path Path to the config file.
- * @throws LoggerException If the file cannot be loaded or parsed.
- */
- public function convert($path) {
- // Load the configuration
- $properties = $this->load($path);
+ // Parse threshold
+ if (isset($properties[self::THRESHOLD_PREFIX])) {
+ $this->config['threshold'] = $properties[self::THRESHOLD_PREFIX];
+ }
- // Parse threshold
- if (isset($properties[self::THRESHOLD_PREFIX])) {
- $this->config['threshold'] = $properties[self::THRESHOLD_PREFIX];
- }
+ // Parse root logger
+ if (isset($properties[self::ROOT_LOGGER_PREFIX])) {
+ $this->parseLogger($properties[self::ROOT_LOGGER_PREFIX], self::ROOT_LOGGER_NAME);
+ }
- // Parse root logger
- if (isset($properties[self::ROOT_LOGGER_PREFIX])) {
- $this->parseLogger($properties[self::ROOT_LOGGER_PREFIX], self::ROOT_LOGGER_NAME);
- }
+ $appenders = array();
- $appenders = array();
+ foreach ($properties as $key => $value) {
+ // Parse loggers
+ if ($this->beginsWith($key, self::LOGGER_PREFIX)) {
+ $name = substr($key, strlen(self::LOGGER_PREFIX));
+ $this->parseLogger($value, $name);
+ }
- foreach($properties as $key => $value) {
- // Parse loggers
- if ($this->beginsWith($key, self::LOGGER_PREFIX)) {
- $name = substr($key, strlen(self::LOGGER_PREFIX));
- $this->parseLogger($value, $name);
- }
+ // Parse additivity
+ if ($this->beginsWith($key, self::ADDITIVITY_PREFIX)) {
+ $name = substr($key, strlen(self::ADDITIVITY_PREFIX));
+ $this->config['loggers'][$name]['additivity'] = $value;
+ }
- // Parse additivity
- if ($this->beginsWith($key, self::ADDITIVITY_PREFIX)) {
- $name = substr($key, strlen(self::ADDITIVITY_PREFIX));
- $this->config['loggers'][$name]['additivity'] = $value;
- }
+ // Parse appenders
+ else if ($this->beginsWith($key, self::APPENDER_PREFIX)) {
+ $this->parseAppender($key, $value);
+ }
- // Parse appenders
- else if ($this->beginsWith($key, self::APPENDER_PREFIX)) {
- $this->parseAppender($key, $value);
- }
+ // Parse renderers
+ else if ($this->beginsWith($key, self::RENDERER_PREFIX)) {
+ $this->parseRenderer($key, $value);
+ }
+ }
- // Parse renderers
- else if ($this->beginsWith($key, self::RENDERER_PREFIX)) {
- $this->parseRenderer($key, $value);
- }
- }
+ return $this->config;
+ }
- return $this->config;
- }
+ /**
+ * Parses a logger definition.
+ *
+ * Loggers are defined in the following manner:
+ * <pre>
+ * log4php.logger.<name> = [<level>], [<appender-ref>, <appender-ref>, ...]
+ * </pre>
+ *
+ * @param string $value The configuration value (level and appender-refs).
+ * @param string $name Logger name.
+ */
+ private function parseLogger($value, $name)
+ {
+ // Value is divided by commas
+ $parts = explode(',', $value);
+ if (empty($value) || empty($parts)) {
+ return;
+ }
+ // The first value is the logger level
+ $level = array_shift($parts);
- /**
- * Parses a logger definition.
- *
- * Loggers are defined in the following manner:
- * <pre>
- * log4php.logger.<name> = [<level>], [<appender-ref>, <appender-ref>, ...]
- * </pre>
- *
- * @param string $value The configuration value (level and appender-refs).
- * @param string $name Logger name.
- */
- private function parseLogger($value, $name) {
- // Value is divided by commas
- $parts = explode(',', $value);
- if (empty($value) || empty($parts)) {
- return;
- }
+ // The remaining values are appender references
+ $appenders = array();
+ while ($appender = array_shift($parts)) {
+ $appender = trim($appender);
+ if (!empty($appender)) {
+ $appenders[] = trim($appender);
+ }
+ }
- // The first value is the logger level
- $level = array_shift($parts);
+ // Find the target configuration
+ if ($name == self::ROOT_LOGGER_NAME) {
+ $this->config['rootLogger']['level'] = trim($level);
+ $this->config['rootLogger']['appenders'] = $appenders;
+ } else {
+ $this->config['loggers'][$name]['level'] = trim($level);
+ $this->config['loggers'][$name]['appenders'] = $appenders;
+ }
+ }
- // The remaining values are appender references
- $appenders = array();
- while($appender = array_shift($parts)) {
- $appender = trim($appender);
- if (!empty($appender)) {
- $appenders[] = trim($appender);
- }
- }
+ /**
+ * Parses an configuration line pertaining to an appender.
+ *
+ * Parses the following patterns:
+ *
+ * Appender class:
+ * <pre>
+ * log4php.appender.<name> = <class>
+ * </pre>
+ *
+ * Appender parameter:
+ * <pre>
+ * log4php.appender.<name>.<param> = <value>
+ * </pre>
+ *
+ * Appender threshold:
+ * <pre>
+ * log4php.appender.<name>.threshold = <level>
+ * </pre>
+ *
+ * Appender layout:
+ * <pre>
+ * log4php.appender.<name>.layout = <layoutClass>
+ * </pre>
+ *
+ * Layout parameter:
+ * <pre>
+ * log4php.appender.<name>.layout.<param> = <value>
+ * </pre>
+ *
+ * For example, a full appender config might look like:
+ * <pre>
+ * log4php.appender.myAppender = ConsoleAppender
+ * log4php.appender.myAppender.threshold = info
+ * log4php.appender.myAppender.target = stdout
+ * log4php.appender.myAppender.layout = PatternLayout
+ * log4php.appender.myAppender.layout.conversionPattern = "%d %c: %m%n"
+ * </pre>
+ *
+ * After parsing all these options, the following configuration can be
+ * found under $this->config['appenders']['myAppender']:
+ * <pre>
+ * array(
+ * 'class' => ConsoleAppender,
+ * 'threshold' => info,
+ * 'params' => array(
+ * 'target' => 'stdout'
+ * ),
+ * 'layout' => array(
+ * 'class' => 'ConsoleAppender',
+ * 'params' => array(
+ * 'conversionPattern' => '%d %c: %m%n'
+ * )
+ * )
+ * )
+ * </pre>
+ *
+ * @param string $key
+ * @param string $value
+ */
+ private function parseAppender($key, $value)
+ {
+ // Remove the appender prefix from key
+ $subKey = substr($key, strlen(self::APPENDER_PREFIX));
- // Find the target configuration
- if ($name == self::ROOT_LOGGER_NAME) {
- $this->config['rootLogger']['level'] = trim($level);
- $this->config['rootLogger']['appenders'] = $appenders;
- } else {
- $this->config['loggers'][$name]['level'] = trim($level);
- $this->config['loggers'][$name]['appenders'] = $appenders;
- }
- }
+ // Divide the string by dots
+ $parts = explode('.', $subKey);
+ $count = count($parts);
- /**
- * Parses an configuration line pertaining to an appender.
- *
- * Parses the following patterns:
- *
- * Appender class:
- * <pre>
- * log4php.appender.<name> = <class>
- * </pre>
- *
- * Appender parameter:
- * <pre>
- * log4php.appender.<name>.<param> = <value>
- * </pre>
- *
- * Appender threshold:
- * <pre>
- * log4php.appender.<name>.threshold = <level>
- * </pre>
- *
- * Appender layout:
- * <pre>
- * log4php.appender.<name>.layout = <layoutClass>
- * </pre>
- *
- * Layout parameter:
- * <pre>
- * log4php.appender.<name>.layout.<param> = <value>
- * </pre>
- *
- * For example, a full appender config might look like:
- * <pre>
- * log4php.appender.myAppender = ConsoleAppender
- * log4php.appender.myAppender.threshold = info
- * log4php.appender.myAppender.target = stdout
- * log4php.appender.myAppender.layout = PatternLayout
- * log4php.appender.myAppender.layout.conversionPattern = "%d %c: %m%n"
- * </pre>
- *
- * After parsing all these options, the following configuration can be
- * found under $this->config['appenders']['myAppender']:
- * <pre>
- * array(
- * 'class' => ConsoleAppender,
- * 'threshold' => info,
- * 'params' => array(
- * 'target' => 'stdout'
- * ),
- * 'layout' => array(
- * 'class' => 'ConsoleAppender',
- * 'params' => array(
- * 'conversionPattern' => '%d %c: %m%n'
- * )
- * )
- * )
- * </pre>
- *
- * @param string $key
- * @param string $value
- */
- private function parseAppender($key, $value) {
+ // The first part is always the appender name
+ $name = trim($parts[0]);
- // Remove the appender prefix from key
- $subKey = substr($key, strlen(self::APPENDER_PREFIX));
+ // Only one part - this line defines the appender class
+ if ($count == 1) {
+ $this->config['appenders'][$name]['class'] = $value;
- // Divide the string by dots
- $parts = explode('.', $subKey);
- $count = count($parts);
+ return;
+ }
- // The first part is always the appender name
- $name = trim($parts[0]);
+ // Two parts - either a parameter, a threshold or layout class
+ else if ($count == 2) {
- // Only one part - this line defines the appender class
- if ($count == 1) {
- $this->config['appenders'][$name]['class'] = $value;
- return;
- }
+ if ($parts[1] == 'layout') {
+ $this->config['appenders'][$name]['layout']['class'] = $value;
- // Two parts - either a parameter, a threshold or layout class
- else if ($count == 2) {
+ return;
+ } elseif ($parts[1] == 'threshold') {
+ $this->config['appenders'][$name]['threshold'] = $value;
- if ($parts[1] == 'layout') {
- $this->config['appenders'][$name]['layout']['class'] = $value;
- return;
- } else if ($parts[1] == 'threshold') {
- $this->config['appenders'][$name]['threshold'] = $value;
- return;
- } else {
- $this->config['appenders'][$name]['params'][$parts[1]] = $value;
- return;
- }
- }
+ return;
+ } else {
+ $this->config['appenders'][$name]['params'][$parts[1]] = $value;
- // Three parts - this can only be a layout parameter
- else if ($count == 3) {
- if ($parts[1] == 'layout') {
- $this->config['appenders'][$name]['layout']['params'][$parts[2]] = $value;
- return;
- }
- }
+ return;
+ }
+ }
- trigger_error("log4php: Don't know how to parse the following line: \"$key = $value\". Skipping.");
- }
+ // Three parts - this can only be a layout parameter
+ else if ($count == 3) {
+ if ($parts[1] == 'layout') {
+ $this->config['appenders'][$name]['layout']['params'][$parts[2]] = $value;
- /**
- * Parses a renderer definition.
- *
- * Renderers are defined as:
- * <pre>
- * log4php.renderer.<renderedClass> = <renderingClass>
- * </pre>
- *
- * @param string $key log4php.renderer.<renderedClass>
- * @param string $value <renderingClass>
- */
- private function parseRenderer($key, $value) {
- // Remove the appender prefix from key
- $renderedClass = substr($key, strlen(self::APPENDER_PREFIX));
- $renderingClass = $value;
+ return;
+ }
+ }
- $this->config['renderers'][] = compact('renderedClass', 'renderingClass');
- }
+ trigger_error("log4php: Don't know how to parse the following line: \"$key = $value\". Skipping.");
+ }
- /** Helper method. Returns true if $str begins with $sub. */
- private function beginsWith($str, $sub) {
- return (strncmp($str, $sub, strlen($sub)) == 0);
- }
+ /**
+ * Parses a renderer definition.
+ *
+ * Renderers are defined as:
+ * <pre>
+ * log4php.renderer.<renderedClass> = <renderingClass>
+ * </pre>
+ *
+ * @param string $key log4php.renderer.<renderedClass>
+ * @param string $value <renderingClass>
+ */
+ private function parseRenderer($key, $value)
+ {
+ // Remove the appender prefix from key
+ $renderedClass = substr($key, strlen(self::APPENDER_PREFIX));
+ $renderingClass = $value;
+
+ $this->config['renderers'][] = compact('renderedClass', 'renderingClass');
+ }
+
+ /** Helper method. Returns true if $str begins with $sub. */
+ private function beginsWith($str, $sub)
+ {
+ return (strncmp($str, $sub, strlen($sub)) == 0);
+ }
}
diff --git a/src/Configuration/adapters/PhpAdapter.php b/src/Configuration/adapters/PhpAdapter.php
index 71d245b..6e22c1d 100644
--- a/src/Configuration/adapters/PhpAdapter.php
+++ b/src/Configuration/adapters/PhpAdapter.php
@@ -49,34 +49,34 @@
*/
class PhpAdapter implements AdapterInterface
{
- public function convert($url) {
- if (!file_exists($url)) {
- throw new LoggerException("File [$url] does not exist.");
- }
+ public function convert($url)
+ {
+ if (!file_exists($url)) {
+ throw new LoggerException("File [$url] does not exist.");
+ }
- // Load the config file
- $data = @file_get_contents($url);
- if ($data === false) {
- $error = error_get_last();
- throw new LoggerException("Error loading config file: {$error['message']}");
- }
+ // Load the config file
+ $data = @file_get_contents($url);
+ if ($data === false) {
+ $error = error_get_last();
+ throw new LoggerException("Error loading config file: {$error['message']}");
+ }
- $config = @eval('?>' . $data);
+ $config = @eval('?>' . $data);
- if ($config === false) {
- $error = error_get_last();
- throw new LoggerException("Error parsing configuration: " . $error['message']);
- }
+ if ($config === false) {
+ $error = error_get_last();
+ throw new LoggerException("Error parsing configuration: " . $error['message']);
+ }
- if (empty($config)) {
- throw new LoggerException("Invalid configuration: empty configuration array.");
- }
+ if (empty($config)) {
+ throw new LoggerException("Invalid configuration: empty configuration array.");
+ }
- if (!is_array($config)) {
- throw new LoggerException("Invalid configuration: not an array.");
- }
+ if (!is_array($config)) {
+ throw new LoggerException("Invalid configuration: not an array.");
+ }
- return $config;
- }
+ return $config;
+ }
}
-
diff --git a/src/Configuration/adapters/XmlAdapter.php b/src/Configuration/adapters/XmlAdapter.php
index d7495b8..829b6d9 100644
--- a/src/Configuration/adapters/XmlAdapter.php
+++ b/src/Configuration/adapters/XmlAdapter.php
@@ -27,251 +27,266 @@
*/
class XmlAdapter implements AdapterInterface
{
- /** Path to the XML schema used for validation. */
- const SCHEMA_PATH = '/../xml/log4php.xsd';
+ /** Path to the XML schema used for validation. */
+ const SCHEMA_PATH = '/../xml/log4php.xsd';
- private $config = array(
- 'appenders' => array(),
- 'loggers' => array(),
- 'renderers' => array(),
- );
+ private $config = array(
+ 'appenders' => array(),
+ 'loggers' => array(),
+ 'renderers' => array(),
+ );
- public function convert($url) {
- $xml = $this->loadXML($url);
+ public function convert($url)
+ {
+ $xml = $this->loadXML($url);
- $this->parseConfiguration($xml);
+ $this->parseConfiguration($xml);
- // Parse the <root> node
- if (isset($xml->root)) {
- $this->parseRootLogger($xml->root);
- }
+ // Parse the <root> node
+ if (isset($xml->root)) {
+ $this->parseRootLogger($xml->root);
+ }
- // Process <logger> nodes
- foreach($xml->logger as $logger) {
- $this->parseLogger($logger);
- }
+ // Process <logger> nodes
+ foreach ($xml->logger as $logger) {
+ $this->parseLogger($logger);
+ }
- // Process <appender> nodes
- foreach($xml->appender as $appender) {
- $this->parseAppender($appender);
- }
+ // Process <appender> nodes
+ foreach ($xml->appender as $appender) {
+ $this->parseAppender($appender);
+ }
- // Process <renderer> nodes
- foreach($xml->renderer as $rendererNode) {
- $this->parseRenderer($rendererNode);
- }
+ // Process <renderer> nodes
+ foreach ($xml->renderer as $rendererNode) {
+ $this->parseRenderer($rendererNode);
+ }
- // Process <defaultRenderer> node
- foreach($xml->defaultRenderer as $rendererNode) {
- $this->parseDefaultRenderer($rendererNode);
- }
+ // Process <defaultRenderer> node
+ foreach ($xml->defaultRenderer as $rendererNode) {
+ $this->parseDefaultRenderer($rendererNode);
+ }
- return $this->config;
- }
+ return $this->config;
+ }
- /**
- * Loads and validates the XML.
- * @param string $url Input XML.
- */
- private function loadXML($url) {
- if (!file_exists($url)) {
- throw new LoggerException("File [$url] does not exist.");
- }
+ /**
+ * Loads and validates the XML.
+ * @param string $url Input XML.
+ */
+ private function loadXML($url)
+ {
+ if (!file_exists($url)) {
+ throw new LoggerException("File [$url] does not exist.");
+ }
- libxml_clear_errors();
- $oldValue = libxml_use_internal_errors(true);
+ libxml_clear_errors();
+ $oldValue = libxml_use_internal_errors(true);
- // Load XML
- $xml = @simplexml_load_file($url);
- if ($xml === false) {
+ // Load XML
+ $xml = @simplexml_load_file($url);
+ if ($xml === false) {
- $errorStr = "";
- foreach(libxml_get_errors() as $error) {
- $errorStr .= $error->message;
- }
+ $errorStr = "";
+ foreach (libxml_get_errors() as $error) {
+ $errorStr .= $error->message;
+ }
- throw new LoggerException("Error loading configuration file: " . trim($errorStr));
- }
+ throw new LoggerException("Error loading configuration file: " . trim($errorStr));
+ }
- libxml_clear_errors();
- libxml_use_internal_errors($oldValue);
+ libxml_clear_errors();
+ libxml_use_internal_errors($oldValue);
- return $xml;
- }
+ return $xml;
+ }
- /**
- * Parses the <configuration> node.
- */
- private function parseConfiguration(\SimpleXMLElement $xml) {
- $attributes = $xml->attributes();
- if (isset($attributes['threshold'])) {
- $this->config['threshold'] = (string) $attributes['threshold'];
- }
- }
+ /**
+ * Parses the <configuration> node.
+ */
+ private function parseConfiguration(\SimpleXMLElement $xml)
+ {
+ $attributes = $xml->attributes();
+ if (isset($attributes['threshold'])) {
+ $this->config['threshold'] = (string) $attributes['threshold'];
+ }
+ }
- /** Parses an <appender> node. */
- private function parseAppender(\SimpleXMLElement $node) {
- $name = $this->getAttributeValue($node, 'name');
- if (empty($name)) {
- $this->warn("An <appender> node is missing the required 'name' attribute. Skipping appender definition.");
- return;
- }
+ /** Parses an <appender> node. */
+ private function parseAppender(\SimpleXMLElement $node)
+ {
+ $name = $this->getAttributeValue($node, 'name');
+ if (empty($name)) {
+ $this->warn("An <appender> node is missing the required 'name' attribute. Skipping appender definition.");
- $appender = array();
- $appender['class'] = $this->getAttributeValue($node, 'class');
+ return;
+ }
- if (isset($node['threshold'])) {
- $appender['threshold'] = $this->getAttributeValue($node, 'threshold');
- }
+ $appender = array();
+ $appender['class'] = $this->getAttributeValue($node, 'class');
- if (isset($node->layout)) {
- $appender['layout']= $this->parseLayout($node->layout, $name);
- }
+ if (isset($node['threshold'])) {
+ $appender['threshold'] = $this->getAttributeValue($node, 'threshold');
+ }
- if (count($node->param) > 0) {
- $appender['params'] = $this->parseParameters($node);
- }
+ if (isset($node->layout)) {
+ $appender['layout']= $this->parseLayout($node->layout, $name);
+ }
- foreach($node->filter as $filterNode) {
- $appender['filters'][] = $this->parseFilter($filterNode);
- }
+ if (count($node->param) > 0) {
+ $appender['params'] = $this->parseParameters($node);
+ }
- $this->config['appenders'][$name] = $appender;
- }
+ foreach ($node->filter as $filterNode) {
+ $appender['filters'][] = $this->parseFilter($filterNode);
+ }
- /** Parses a <layout> node. */
- private function parseLayout(\SimpleXMLElement $node, $appenderName) {
- $layout = array();
- $layout['class'] = $this->getAttributeValue($node, 'class');
+ $this->config['appenders'][$name] = $appender;
+ }
- if (count($node->param) > 0) {
- $layout['params'] = $this->parseParameters($node);
- }
+ /** Parses a <layout> node. */
+ private function parseLayout(\SimpleXMLElement $node, $appenderName)
+ {
+ $layout = array();
+ $layout['class'] = $this->getAttributeValue($node, 'class');
- return $layout;
- }
+ if (count($node->param) > 0) {
+ $layout['params'] = $this->parseParameters($node);
+ }
- /** Parses any <param> child nodes returning them in an array. */
- private function parseParameters($paramsNode) {
- $params = array();
+ return $layout;
+ }
- foreach($paramsNode->param as $paramNode) {
- if (empty($paramNode['name'])) {
- $this->warn("A <param> node is missing the required 'name' attribute. Skipping parameter.");
- continue;
- }
+ /** Parses any <param> child nodes returning them in an array. */
+ private function parseParameters($paramsNode)
+ {
+ $params = array();
- $name = $this->getAttributeValue($paramNode, 'name');
- $value = $this->getAttributeValue($paramNode, 'value');
+ foreach ($paramsNode->param as $paramNode) {
+ if (empty($paramNode['name'])) {
+ $this->warn("A <param> node is missing the required 'name' attribute. Skipping parameter.");
+ continue;
+ }
- $params[$name] = $value;
- }
+ $name = $this->getAttributeValue($paramNode, 'name');
+ $value = $this->getAttributeValue($paramNode, 'value');
- return $params;
- }
+ $params[$name] = $value;
+ }
- /** Parses a <root> node. */
- private function parseRootLogger(\SimpleXMLElement $node) {
- $logger = array();
+ return $params;
+ }
- if (isset($node->level)) {
- $logger['level'] = $this->getAttributeValue($node->level, 'value');
- }
+ /** Parses a <root> node. */
+ private function parseRootLogger(\SimpleXMLElement $node)
+ {
+ $logger = array();
- $logger['appenders'] = $this->parseAppenderReferences($node);
+ if (isset($node->level)) {
+ $logger['level'] = $this->getAttributeValue($node->level, 'value');
+ }
- $this->config['rootLogger'] = $logger;
- }
+ $logger['appenders'] = $this->parseAppenderReferences($node);
- /** Parses a <logger> node. */
- private function parseLogger(\SimpleXMLElement $node) {
- $logger = array();
+ $this->config['rootLogger'] = $logger;
+ }
- $name = $this->getAttributeValue($node, 'name');
- if (empty($name)) {
- $this->warn("A <logger> node is missing the required 'name' attribute. Skipping logger definition.");
- return;
- }
+ /** Parses a <logger> node. */
+ private function parseLogger(\SimpleXMLElement $node)
+ {
+ $logger = array();
- if (isset($node->level)) {
- $logger['level'] = $this->getAttributeValue($node->level, 'value');
- }
+ $name = $this->getAttributeValue($node, 'name');
+ if (empty($name)) {
+ $this->warn("A <logger> node is missing the required 'name' attribute. Skipping logger definition.");
- if (isset($node['additivity'])) {
- $logger['additivity'] = $this->getAttributeValue($node, 'additivity');
- }
+ return;
+ }
- $logger['appenders'] = $this->parseAppenderReferences($node);
+ if (isset($node->level)) {
+ $logger['level'] = $this->getAttributeValue($node->level, 'value');
+ }
- // Check for duplicate loggers
- if (isset($this->config['loggers'][$name])) {
- $this->warn("Duplicate logger definition [$name]. Overwriting.");
- }
+ if (isset($node['additivity'])) {
+ $logger['additivity'] = $this->getAttributeValue($node, 'additivity');
+ }
- $this->config['loggers'][$name] = $logger;
- }
+ $logger['appenders'] = $this->parseAppenderReferences($node);
- /**
- * Parses a <logger> node for appender references and returns them in an array.
- *
- * Previous versions supported appender-ref, as well as appender_ref so both
- * are parsed for backward compatibility.
- */
- private function parseAppenderReferences(\SimpleXMLElement $node) {
- $refs = array();
- foreach($node->appender_ref as $ref) {
- $refs[] = $this->getAttributeValue($ref, 'ref');
- }
+ // Check for duplicate loggers
+ if (isset($this->config['loggers'][$name])) {
+ $this->warn("Duplicate logger definition [$name]. Overwriting.");
+ }
- foreach($node->{'appender-ref'} as $ref) {
- $refs[] = $this->getAttributeValue($ref, 'ref');
- }
+ $this->config['loggers'][$name] = $logger;
+ }
- return $refs;
- }
+ /**
+ * Parses a <logger> node for appender references and returns them in an array.
+ *
+ * Previous versions supported appender-ref, as well as appender_ref so both
+ * are parsed for backward compatibility.
+ */
+ private function parseAppenderReferences(\SimpleXMLElement $node)
+ {
+ $refs = array();
+ foreach ($node->appender_ref as $ref) {
+ $refs[] = $this->getAttributeValue($ref, 'ref');
+ }
- /** Parses a <filter> node. */
- private function parseFilter($filterNode) {
- $filter = array();
- $filter['class'] = $this->getAttributeValue($filterNode, 'class');
+ foreach ($node->{'appender-ref'} as $ref) {
+ $refs[] = $this->getAttributeValue($ref, 'ref');
+ }
- if (count($filterNode->param) > 0) {
- $filter['params'] = $this->parseParameters($filterNode);
- }
+ return $refs;
+ }
- return $filter;
- }
+ /** Parses a <filter> node. */
+ private function parseFilter($filterNode)
+ {
+ $filter = array();
+ $filter['class'] = $this->getAttributeValue($filterNode, 'class');
- /** Parses a <renderer> node. */
- private function parseRenderer(\SimpleXMLElement $node) {
- $renderedClass = $this->getAttributeValue($node, 'renderedClass');
- $renderingClass = $this->getAttributeValue($node, 'renderingClass');
+ if (count($filterNode->param) > 0) {
+ $filter['params'] = $this->parseParameters($filterNode);
+ }
- $this->config['renderers'][] = compact('renderedClass', 'renderingClass');
- }
+ return $filter;
+ }
- /** Parses a <defaultRenderer> node. */
- private function parseDefaultRenderer(\SimpleXMLElement $node) {
- $renderingClass = $this->getAttributeValue($node, 'renderingClass');
+ /** Parses a <renderer> node. */
+ private function parseRenderer(\SimpleXMLElement $node)
+ {
+ $renderedClass = $this->getAttributeValue($node, 'renderedClass');
+ $renderingClass = $this->getAttributeValue($node, 'renderingClass');
- // Warn on duplicates
- if(isset($this->config['defaultRenderer'])) {
- $this->warn("Duplicate <defaultRenderer> node. Overwriting.");
- }
+ $this->config['renderers'][] = compact('renderedClass', 'renderingClass');
+ }
- $this->config['defaultRenderer'] = $renderingClass;
- }
+ /** Parses a <defaultRenderer> node. */
+ private function parseDefaultRenderer(\SimpleXMLElement $node)
+ {
+ $renderingClass = $this->getAttributeValue($node, 'renderingClass');
- // ******************************************
- // ** Helper methods **
- // ******************************************
+ // Warn on duplicates
+ if (isset($this->config['defaultRenderer'])) {
+ $this->warn("Duplicate <defaultRenderer> node. Overwriting.");
+ }
- private function getAttributeValue(\SimpleXMLElement $node, $name) {
- return isset($node[$name]) ? (string) $node[$name] : null;
- }
+ $this->config['defaultRenderer'] = $renderingClass;
+ }
- private function warn($message) {
- trigger_error("log4php: " . $message, E_USER_WARNING);
- }
+ // ******************************************
+ // ** Helper methods **
+ // ******************************************
+
+ private function getAttributeValue(\SimpleXMLElement $node, $name)
+ {
+ return isset($node[$name]) ? (string) $node[$name] : null;
+ }
+
+ private function warn($message)
+ {
+ trigger_error("log4php: " . $message, E_USER_WARNING);
+ }
}
-
diff --git a/src/Filters/AbstractFilter.php b/src/Filters/AbstractFilter.php
index 81663e3..9b884a7 100644
--- a/src/Filters/AbstractFilter.php
+++ b/src/Filters/AbstractFilter.php
@@ -53,74 +53,78 @@
* <p>The philosophy of log4php filters is largely inspired from the
* Linux ipchains.
*/
-abstract class AbstractFilter extends Configurable {
+abstract class AbstractFilter extends Configurable
+{
+ /**
+ * The log event must be logged immediately without consulting with
+ * the remaining filters, if any, in the chain.
+ */
+ const ACCEPT = 1;
- /**
- * The log event must be logged immediately without consulting with
- * the remaining filters, if any, in the chain.
- */
- const ACCEPT = 1;
+ /**
+ * This filter is neutral with respect to the log event. The
+ * remaining filters, if any, should be consulted for a final decision.
+ */
+ const NEUTRAL = 0;
- /**
- * This filter is neutral with respect to the log event. The
- * remaining filters, if any, should be consulted for a final decision.
- */
- const NEUTRAL = 0;
+ /**
+ * The log event must be dropped immediately without consulting
+ * with the remaining filters, if any, in the chain.
+ */
+ const DENY = -1;
- /**
- * The log event must be dropped immediately without consulting
- * with the remaining filters, if any, in the chain.
- */
- const DENY = -1;
+ /**
+ * @var AbstractFilter Points to the next {@link AbstractFilter} in the filter chain.
+ */
+ protected $next;
- /**
- * @var AbstractFilter Points to the next {@link AbstractFilter} in the filter chain.
- */
- protected $next;
+ /**
+ * Usually filters options become active when set. We provide a
+ * default do-nothing implementation for convenience.
+ */
+ public function activateOptions()
+ {
+ }
- /**
- * Usually filters options become active when set. We provide a
- * default do-nothing implementation for convenience.
- */
- public function activateOptions() {
- }
+ /**
+ * Decide what to do.
+ * <p>If the decision is {@link AbstractFilter::DENY}, then the event will be
+ * dropped. If the decision is {@link AbstractFilter::NEUTRAL}, then the next
+ * filter, if any, will be invoked. If the decision is {@link AbstractFilter::ACCEPT} then
+ * the event will be logged without consulting with other filters in
+ * the chain.
+ *
+ * @param LoggingEvent $event The {@link LoggingEvent} to decide upon.
+ * @return integer {@link AbstractFilter::NEUTRAL} or {@link AbstractFilter::DENY}|{@link AbstractFilter::ACCEPT}
+ */
+ public function decide(LoggingEvent $event)
+ {
+ return self::NEUTRAL;
+ }
- /**
- * Decide what to do.
- * <p>If the decision is {@link AbstractFilter::DENY}, then the event will be
- * dropped. If the decision is {@link AbstractFilter::NEUTRAL}, then the next
- * filter, if any, will be invoked. If the decision is {@link AbstractFilter::ACCEPT} then
- * the event will be logged without consulting with other filters in
- * the chain.
- *
- * @param LoggingEvent $event The {@link LoggingEvent} to decide upon.
- * @return integer {@link AbstractFilter::NEUTRAL} or {@link AbstractFilter::DENY}|{@link AbstractFilter::ACCEPT}
- */
- public function decide(LoggingEvent $event) {
- return self::NEUTRAL;
- }
+ /**
+ * Adds a new filter to the filter chain this filter is a part of.
+ * If this filter has already and follow up filter, the param filter
+ * is passed on until it is the last filter in chain.
+ *
+ * @param $filter - the filter to add to this chain
+ */
+ public function addNext($filter)
+ {
+ if ($this->next !== null) {
+ $this->next->addNext($filter);
+ } else {
+ $this->next = $filter;
+ }
+ }
- /**
- * Adds a new filter to the filter chain this filter is a part of.
- * If this filter has already and follow up filter, the param filter
- * is passed on until it is the last filter in chain.
- *
- * @param $filter - the filter to add to this chain
- */
- public function addNext($filter) {
- if($this->next !== null) {
- $this->next->addNext($filter);
- } else {
- $this->next = $filter;
- }
- }
-
- /**
- * Returns the next filter in this chain
- * @return the next filter
- */
- public function getNext() {
- return $this->next;
- }
+ /**
+ * Returns the next filter in this chain
+ * @return the next filter
+ */
+ public function getNext()
+ {
+ return $this->next;
+ }
}
diff --git a/src/Filters/DenyAllFilter.php b/src/Filters/DenyAllFilter.php
index 1d34357..6781b55 100644
--- a/src/Filters/DenyAllFilter.php
+++ b/src/Filters/DenyAllFilter.php
@@ -30,16 +30,17 @@
*
* @since 0.3
*/
-class DenyAllFilter extends AbstractFilter {
-
- /**
- * Always returns the integer constant {@link AbstractFilter::DENY}
- * regardless of the {@link LoggingEvent} parameter.
- *
- * @param LoggingEvent $event The {@link LoggingEvent} to filter.
- * @return AbstractFilter::DENY Always returns {@link AbstractFilter::DENY}
- */
- public function decide(LoggingEvent $event) {
- return AbstractFilter::DENY;
- }
+class DenyAllFilter extends AbstractFilter
+{
+ /**
+ * Always returns the integer constant {@link AbstractFilter::DENY}
+ * regardless of the {@link LoggingEvent} parameter.
+ *
+ * @param LoggingEvent $event The {@link LoggingEvent} to filter.
+ * @return AbstractFilter::DENY Always returns {@link AbstractFilter::DENY}
+ */
+ public function decide(LoggingEvent $event)
+ {
+ return AbstractFilter::DENY;
+ }
}
diff --git a/src/Filters/LevelMatchFilter.php b/src/Filters/LevelMatchFilter.php
index 4573c4c..2ace612 100644
--- a/src/Filters/LevelMatchFilter.php
+++ b/src/Filters/LevelMatchFilter.php
@@ -43,56 +43,59 @@
* {@example ../../examples/resources/filter_levelmatch.xml 18}
* @since 0.6
*/
-class LevelMatchFilter extends AbstractFilter {
+class LevelMatchFilter extends AbstractFilter
+{
+ /**
+ * Indicates if this event should be accepted or denied on match
+ * @var boolean
+ */
+ protected $acceptOnMatch = true;
- /**
- * Indicates if this event should be accepted or denied on match
- * @var boolean
- */
- protected $acceptOnMatch = true;
+ /**
+ * The level, when to match
+ * @var Level
+ */
+ protected $levelToMatch;
- /**
- * The level, when to match
- * @var Level
- */
- protected $levelToMatch;
+ /**
+ * @param boolean $acceptOnMatch
+ */
+ public function setAcceptOnMatch($acceptOnMatch)
+ {
+ $this->setBoolean('acceptOnMatch', $acceptOnMatch);
+ }
- /**
- * @param boolean $acceptOnMatch
- */
- public function setAcceptOnMatch($acceptOnMatch) {
- $this->setBoolean('acceptOnMatch', $acceptOnMatch);
- }
+ /**
+ * @param string $l the level to match
+ */
+ public function setLevelToMatch($level)
+ {
+ $this->setLevel('levelToMatch', $level);
+ }
- /**
- * @param string $l the level to match
- */
- public function setLevelToMatch($level) {
- $this->setLevel('levelToMatch', $level);
- }
+ /**
+ * Return the decision of this filter.
+ *
+ * Returns {@link AbstractFilter::NEUTRAL} if the <b><var>LevelToMatch</var></b>
+ * option is not set or if there is not match. Otherwise, if there is a
+ * match, then the returned decision is {@link AbstractFilter::ACCEPT} if the
+ * <b><var>AcceptOnMatch</var></b> property is set to <i>true</i>. The
+ * returned decision is {@link AbstractFilter::DENY} if the
+ * <b><var>AcceptOnMatch</var></b> property is set to <i>false</i>.
+ *
+ * @param LoggingEvent $event
+ * @return integer
+ */
+ public function decide(LoggingEvent $event)
+ {
+ if ($this->levelToMatch === null) {
+ return AbstractFilter::NEUTRAL;
+ }
- /**
- * Return the decision of this filter.
- *
- * Returns {@link AbstractFilter::NEUTRAL} if the <b><var>LevelToMatch</var></b>
- * option is not set or if there is not match. Otherwise, if there is a
- * match, then the returned decision is {@link AbstractFilter::ACCEPT} if the
- * <b><var>AcceptOnMatch</var></b> property is set to <i>true</i>. The
- * returned decision is {@link AbstractFilter::DENY} if the
- * <b><var>AcceptOnMatch</var></b> property is set to <i>false</i>.
- *
- * @param LoggingEvent $event
- * @return integer
- */
- public function decide(LoggingEvent $event) {
- if($this->levelToMatch === null) {
- return AbstractFilter::NEUTRAL;
- }
-
- if($this->levelToMatch->equals($event->getLevel())) {
- return $this->acceptOnMatch ? AbstractFilter::ACCEPT : AbstractFilter::DENY;
- } else {
- return AbstractFilter::NEUTRAL;
- }
- }
+ if ($this->levelToMatch->equals($event->getLevel())) {
+ return $this->acceptOnMatch ? AbstractFilter::ACCEPT : AbstractFilter::DENY;
+ } else {
+ return AbstractFilter::NEUTRAL;
+ }
+ }
}
diff --git a/src/Filters/LevelRangeFilter.php b/src/Filters/LevelRangeFilter.php
index d30f5ae..6eb62f5 100644
--- a/src/Filters/LevelRangeFilter.php
+++ b/src/Filters/LevelRangeFilter.php
@@ -60,77 +60,81 @@
* @author based on the org.apache.log4j.varia.LevelRangeFilte Java code by Ceki Gülcü
* @since 0.6
*/
-class LevelRangeFilter extends AbstractFilter {
+class LevelRangeFilter extends AbstractFilter
+{
+ /**
+ * @var boolean
+ */
+ protected $acceptOnMatch = true;
- /**
- * @var boolean
- */
- protected $acceptOnMatch = true;
+ /**
+ * @var Level
+ */
+ protected $levelMin;
- /**
- * @var Level
- */
- protected $levelMin;
+ /**
+ * @var Level
+ */
+ protected $levelMax;
- /**
- * @var Level
- */
- protected $levelMax;
+ /**
+ * @param boolean $acceptOnMatch
+ */
+ public function setAcceptOnMatch($acceptOnMatch)
+ {
+ $this->setBoolean('acceptOnMatch', $acceptOnMatch);
+ }
- /**
- * @param boolean $acceptOnMatch
- */
- public function setAcceptOnMatch($acceptOnMatch) {
- $this->setBoolean('acceptOnMatch', $acceptOnMatch);
- }
+ /**
+ * @param string $l the level min to match
+ */
+ public function setLevelMin($level)
+ {
+ $this->setLevel('levelMin', $level);
+ }
- /**
- * @param string $l the level min to match
- */
- public function setLevelMin($level) {
- $this->setLevel('levelMin', $level);
- }
+ /**
+ * @param string $l the level max to match
+ */
+ public function setLevelMax($level)
+ {
+ $this->setLevel('levelMax', $level);
+ }
- /**
- * @param string $l the level max to match
- */
- public function setLevelMax($level) {
- $this->setLevel('levelMax', $level);
- }
+ /**
+ * Return the decision of this filter.
+ *
+ * @param LoggingEvent $event
+ * @return integer
+ */
+ public function decide(LoggingEvent $event)
+ {
+ $level = $event->getLevel();
- /**
- * Return the decision of this filter.
- *
- * @param LoggingEvent $event
- * @return integer
- */
- public function decide(LoggingEvent $event) {
- $level = $event->getLevel();
+ if ($this->levelMin !== null) {
+ if ($level->isGreaterOrEqual($this->levelMin) == false) {
+ // level of event is less than minimum
+ return AbstractFilter::DENY;
+ }
+ }
- if($this->levelMin !== null) {
- if($level->isGreaterOrEqual($this->levelMin) == false) {
- // level of event is less than minimum
- return AbstractFilter::DENY;
- }
- }
+ if ($this->levelMax !== null) {
+ if ($level->toInt() > $this->levelMax->toInt()) {
+ // level of event is greater than maximum
+ // Alas, there is no Level.isGreater method. and using
+ // a combo of isGreaterOrEqual && !Equal seems worse than
+ // checking the int values of the level objects..
+ return AbstractFilter::DENY;
+ }
+ }
- if($this->levelMax !== null) {
- if($level->toInt() > $this->levelMax->toInt()) {
- // level of event is greater than maximum
- // Alas, there is no Level.isGreater method. and using
- // a combo of isGreaterOrEqual && !Equal seems worse than
- // checking the int values of the level objects..
- return AbstractFilter::DENY;
- }
- }
-
- if($this->acceptOnMatch) {
- // this filter set up to bypass later filters and always return
- // accept if level in range
- return AbstractFilter::ACCEPT;
- } else {
- // event is ok for this filter; allow later filters to have a look..
- return AbstractFilter::NEUTRAL;
- }
- }
+ if ($this->acceptOnMatch) {
+ // this filter set up to bypass later filters and always return
+ // accept if level in range
+ return AbstractFilter::ACCEPT;
+ } else {
+ // event is ok for this filter; allow later filters to have a look..
+ return AbstractFilter::NEUTRAL;
+ }
+ }
}
diff --git a/src/Filters/StringMatchFilter.php b/src/Filters/StringMatchFilter.php
index 152c9c9..c6e6359 100644
--- a/src/Filters/StringMatchFilter.php
+++ b/src/Filters/StringMatchFilter.php
@@ -43,45 +43,49 @@
* {@example ../../examples/resources/filter_stringmatch.xml 18}
* @since 0.3
*/
-class StringMatchFilter extends AbstractFilter {
+class StringMatchFilter extends AbstractFilter
+{
+ /**
+ * @var boolean
+ */
+ protected $acceptOnMatch = true;
- /**
- * @var boolean
- */
- protected $acceptOnMatch = true;
+ /**
+ * @var string
+ */
+ protected $stringToMatch;
- /**
- * @var string
- */
- protected $stringToMatch;
+ /**
+ * @param mixed $acceptOnMatch a boolean or a string ('true' or 'false')
+ */
+ public function setAcceptOnMatch($acceptOnMatch)
+ {
+ $this->setBoolean('acceptOnMatch', $acceptOnMatch);
+ }
- /**
- * @param mixed $acceptOnMatch a boolean or a string ('true' or 'false')
- */
- public function setAcceptOnMatch($acceptOnMatch) {
- $this->setBoolean('acceptOnMatch', $acceptOnMatch);
- }
+ /**
+ * @param string $s the string to match
+ */
+ public function setStringToMatch($string)
+ {
+ $this->setString('stringToMatch', $string);
+ }
- /**
- * @param string $s the string to match
- */
- public function setStringToMatch($string) {
- $this->setString('stringToMatch', $string);
- }
+ /**
+ * @return integer a {@link LOGGER_FILTER_NEUTRAL} is there is no string match.
+ */
+ public function decide(LoggingEvent $event)
+ {
+ $msg = $event->getRenderedMessage();
- /**
- * @return integer a {@link LOGGER_FILTER_NEUTRAL} is there is no string match.
- */
- public function decide(LoggingEvent $event) {
- $msg = $event->getRenderedMessage();
+ if ($msg === null or $this->stringToMatch === null) {
+ return AbstractFilter::NEUTRAL;
+ }
- if($msg === null or $this->stringToMatch === null) {
- return AbstractFilter::NEUTRAL;
- }
+ if (strpos($msg, $this->stringToMatch) !== false ) {
+ return ($this->acceptOnMatch) ? AbstractFilter::ACCEPT : AbstractFilter::DENY;
+ }
- if(strpos($msg, $this->stringToMatch) !== false ) {
- return ($this->acceptOnMatch) ? AbstractFilter::ACCEPT : AbstractFilter::DENY;
- }
- return AbstractFilter::NEUTRAL;
- }
+ return AbstractFilter::NEUTRAL;
+ }
}
diff --git a/src/Helpers/FormattingInfo.php b/src/Helpers/FormattingInfo.php
index 9f2bb3b..fb824b4 100644
--- a/src/Helpers/FormattingInfo.php
+++ b/src/Helpers/FormattingInfo.php
@@ -23,29 +23,29 @@
* formatting modifiers in conversion modifiers.
* @since 0.3
*/
-class FormattingInfo {
+class FormattingInfo
+{
+ /**
+ * Minimal output length. If output is shorter than this value, it will be
+ * padded with spaces.
+ */
+ public $min = 0;
- /**
- * Minimal output length. If output is shorter than this value, it will be
- * padded with spaces.
- */
- public $min = 0;
+ /**
+ * Maximum output length. If output is longer than this value, it will be
+ * trimmed.
+ */
+ public $max = PHP_INT_MAX;
- /**
- * Maximum output length. If output is longer than this value, it will be
- * trimmed.
- */
- public $max = PHP_INT_MAX;
+ /**
+ * Whether to pad the string from the left. If set to false, the string
+ * will be padded from the right.
+ */
+ public $padLeft = true;
- /**
- * Whether to pad the string from the left. If set to false, the string
- * will be padded from the right.
- */
- public $padLeft = true;
-
- /**
- * Whether to trim the string from the left. If set to false, the string
- * will be trimmed from the right.
- */
- public $trimLeft = false;
+ /**
+ * Whether to trim the string from the left. If set to false, the string
+ * will be trimmed from the right.
+ */
+ public $trimLeft = false;
}
diff --git a/src/Helpers/OptionConverter.php b/src/Helpers/OptionConverter.php
index c496f02..d67b4a8 100644
--- a/src/Helpers/OptionConverter.php
+++ b/src/Helpers/OptionConverter.php
@@ -25,201 +25,210 @@
* A convenience class to convert property values to specific types.
* @since 0.5
*/
-class OptionConverter {
+class OptionConverter
+{
+ /** String values which are converted to boolean TRUE. */
+ private static $trueValues = array('1', 'true', 'yes', 'on');
- /** String values which are converted to boolean TRUE. */
- private static $trueValues = array('1', 'true', 'yes', 'on');
+ /**
+ * String values which are converted to boolean FALSE.
+ *
+ * Note that an empty string must convert to false, because
+ * parse_ini_file() which is used for parsing configuration
+ * converts the value _false_ to an empty string.
+ */
+ private static $falseValues = array('0', 'false', 'no', 'off', '');
- /**
- * String values which are converted to boolean FALSE.
- *
- * Note that an empty string must convert to false, because
- * parse_ini_file() which is used for parsing configuration
- * converts the value _false_ to an empty string.
- */
- private static $falseValues = array('0', 'false', 'no', 'off', '');
+ /**
+ * Read a predefined var.
+ *
+ * It returns a value referenced by <var>$key</var> using this search criteria:
+ * - if <var>$key</var> is a constant then return it. Else
+ * - if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
+ * - return <var>$def</var>.
+ *
+ * @param string $key The key to search for.
+ * @param string $def The default value to return.
+ * @return string the string value of the system property, or the default
+ * value if there is no property with that key.
+ */
+ public static function getSystemProperty($key, $def)
+ {
+ if (defined($key)) {
+ return (string) constant($key);
+ } elseif (isset($_SERVER[$key])) {
+ return (string) $_SERVER[$key];
+ } elseif (isset($_ENV[$key])) {
+ return (string) $_ENV[$key];
+ } else {
+ return $def;
+ }
+ }
- /**
- * Read a predefined var.
- *
- * It returns a value referenced by <var>$key</var> using this search criteria:
- * - if <var>$key</var> is a constant then return it. Else
- * - if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
- * - return <var>$def</var>.
- *
- * @param string $key The key to search for.
- * @param string $def The default value to return.
- * @return string the string value of the system property, or the default
- * value if there is no property with that key.
- */
- public static function getSystemProperty($key, $def) {
- if(defined($key)) {
- return (string)constant($key);
- } else if(isset($_SERVER[$key])) {
- return (string)$_SERVER[$key];
- } else if(isset($_ENV[$key])) {
- return (string)$_ENV[$key];
- } else {
- return $def;
- }
- }
+ /** Converts $value to boolean, or throws an exception if not possible. */
+ public static function toBooleanEx($value)
+ {
+ if (isset($value)) {
+ if (is_bool($value)) {
+ return $value;
+ }
+ $value = strtolower(trim($value));
+ if (in_array($value, self::$trueValues)) {
+ return true;
+ }
+ if (in_array($value, self::$falseValues)) {
+ return false;
+ }
+ }
- /** Converts $value to boolean, or throws an exception if not possible. */
- public static function toBooleanEx($value) {
- if (isset($value)) {
- if (is_bool($value)) {
- return $value;
- }
- $value = strtolower(trim($value));
- if (in_array($value, self::$trueValues)) {
- return true;
- }
- if (in_array($value, self::$falseValues)) {
- return false;
- }
- }
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to boolean.");
+ }
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to boolean.");
- }
+ /**
+ * Converts $value to integer, or throws an exception if not possible.
+ * Floats cannot be converted to integer.
+ */
+ public static function toIntegerEx($value)
+ {
+ if (is_integer($value)) {
+ return $value;
+ }
+ if (is_numeric($value) && ($value == (integer) $value)) {
+ return (integer) $value;
+ }
- /**
- * Converts $value to integer, or throws an exception if not possible.
- * Floats cannot be converted to integer.
- */
- public static function toIntegerEx($value) {
- if (is_integer($value)) {
- return $value;
- }
- if (is_numeric($value) && ($value == (integer) $value)) {
- return (integer) $value;
- }
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to integer.");
+ }
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to integer.");
- }
+ /**
+ * Converts $value to integer, or throws an exception if not possible.
+ * Floats cannot be converted to integer.
+ */
+ public static function toPositiveIntegerEx($value)
+ {
+ if (is_integer($value) && $value > 0) {
+ return $value;
+ }
+ if (is_numeric($value) && ($value == (integer) $value) && $value > 0) {
+ return (integer) $value;
+ }
- /**
- * Converts $value to integer, or throws an exception if not possible.
- * Floats cannot be converted to integer.
- */
- public static function toPositiveIntegerEx($value) {
- if (is_integer($value) && $value > 0) {
- return $value;
- }
- if (is_numeric($value) && ($value == (integer) $value) && $value > 0) {
- return (integer) $value;
- }
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a positive integer.");
+ }
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a positive integer.");
- }
+ /** Converts the value to a level. Throws an exception if not possible. */
+ public static function toLevelEx($value)
+ {
+ if ($value instanceof Level) {
+ return $value;
+ }
+ $level = Level::toLevel($value);
+ if ($level === null) {
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a logger level.");
+ }
- /** Converts the value to a level. Throws an exception if not possible. */
- public static function toLevelEx($value) {
- if ($value instanceof Level) {
- return $value;
- }
- $level = Level::toLevel($value);
- if ($level === null) {
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a logger level.");
- }
- return $level;
- }
+ return $level;
+ }
- /**
- * Converts a value to a valid file size (integer).
- *
- * Supports 'KB', 'MB' and 'GB' suffixes, where KB = 1024 B etc.
- *
- * The final value will be rounded to the nearest integer.
- *
- * Examples:
- * - '100' => 100
- * - '100.12' => 100
- * - '100KB' => 102400
- * - '1.5MB' => 1572864
- *
- * @param mixed $value File size (optionally with suffix).
- * @return integer Parsed file size.
- */
- public static function toFileSizeEx($value) {
+ /**
+ * Converts a value to a valid file size (integer) .
+ *
+ * Supports 'KB', 'MB' and 'GB' suffixes, where KB = 1024 B etc.
+ *
+ * The final value will be rounded to the nearest integer.
+ *
+ * Examples:
+ * - '100' => 100
+ * - '100.12' => 100
+ * - '100KB' => 102400
+ * - '1.5MB' => 1572864
+ *
+ * @param mixed $value File size (optionally with suffix).
+ * @return integer Parsed file size.
+ */
+ public static function toFileSizeEx($value)
+ {
+ if (empty($value)) {
+ throw new LoggerException("Empty value cannot be converted to a file size.");
+ }
- if (empty($value)) {
- throw new LoggerException("Empty value cannot be converted to a file size.");
- }
+ if (is_numeric($value)) {
+ return (integer) $value;
+ }
- if (is_numeric($value)) {
- return (integer) $value;
- }
+ if (!is_string($value)) {
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a file size.");
+ }
- if (!is_string($value)) {
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a file size.");
- }
+ $str = strtoupper(trim($value));
+ $count = preg_match('/^([0-9.]+)(KB|MB|GB)?$/', $str, $matches);
- $str = strtoupper(trim($value));
- $count = preg_match('/^([0-9.]+)(KB|MB|GB)?$/', $str, $matches);
+ if ($count > 0) {
+ $size = $matches[1];
+ $unit = $matches[2];
- if ($count > 0) {
- $size = $matches[1];
- $unit = $matches[2];
+ switch ($unit) {
+ case 'KB': $size *= pow(1024, 1); break;
+ case 'MB': $size *= pow(1024, 2); break;
+ case 'GB': $size *= pow(1024, 3); break;
+ }
- switch($unit) {
- case 'KB': $size *= pow(1024, 1); break;
- case 'MB': $size *= pow(1024, 2); break;
- case 'GB': $size *= pow(1024, 3); break;
- }
+ return (integer) $size;
+ }
- return (integer) $size;
- }
+ throw new LoggerException("Given value [$value] cannot be converted to a file size.");
+ }
- throw new LoggerException("Given value [$value] cannot be converted to a file size.");
- }
+ /**
+ * Converts a value to string, or throws an exception if not possible.
+ *
+ * Objects can be converted to string if they implement the magic
+ * __toString() method.
+ *
+ */
+ public static function toStringEx($value)
+ {
+ if (is_string($value)) {
+ return $value;
+ }
+ if (is_numeric($value)) {
+ return (string) $value;
+ }
+ if (is_object($value) && method_exists($value, '__toString')) {
+ return (string) $value;
+ }
- /**
- * Converts a value to string, or throws an exception if not possible.
- *
- * Objects can be converted to string if they implement the magic
- * __toString() method.
- *
- */
- public static function toStringEx($value) {
- if (is_string($value)) {
- return $value;
- }
- if (is_numeric($value)) {
- return (string) $value;
- }
- if (is_object($value) && method_exists($value, '__toString')) {
- return (string) $value;
- }
+ throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to string.");
+ }
- throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to string.");
- }
+ /**
+ * Performs value substitution for string options.
+ *
+ * An option can contain PHP constants delimited by '${' and '}'.
+ *
+ * E.g. for input string "some ${FOO} value", the method will attempt
+ * to substitute ${FOO} with the value of constant FOO if it exists.
+ *
+ * Therefore, if FOO is a constant, and it has value "bar", the resulting
+ * string will be "some bar value".
+ *
+ * If the constant is not defined, it will be replaced by an empty string,
+ * and the resulting string will be "some value".
+ *
+ * @param string $string String on which to perform substitution.
+ * @return string
+ */
+ public static function substConstants($string)
+ {
+ preg_match_all('/\${([^}]+)}/', $string, $matches);
- /**
- * Performs value substitution for string options.
- *
- * An option can contain PHP constants delimited by '${' and '}'.
- *
- * E.g. for input string "some ${FOO} value", the method will attempt
- * to substitute ${FOO} with the value of constant FOO if it exists.
- *
- * Therefore, if FOO is a constant, and it has value "bar", the resulting
- * string will be "some bar value".
- *
- * If the constant is not defined, it will be replaced by an empty string,
- * and the resulting string will be "some value".
- *
- * @param string $string String on which to perform substitution.
- * @return string
- */
- public static function substConstants($string) {
- preg_match_all('/\${([^}]+)}/', $string, $matches);
+ foreach ($matches[1] as $key => $match) {
+ $match = trim($match);
+ $search = $matches[0][$key];
+ $replacement = defined($match) ? constant($match) : '';
+ $string = str_replace($search, $replacement, $string);
+ }
- foreach($matches[1] as $key => $match) {
- $match = trim($match);
- $search = $matches[0][$key];
- $replacement = defined($match) ? constant($match) : '';
- $string = str_replace($search, $replacement, $string);
- }
- return $string;
- }
+ return $string;
+ }
}
diff --git a/src/Helpers/PatternParser.php b/src/Helpers/PatternParser.php
index 7e98a55..5d22b39 100644
--- a/src/Helpers/PatternParser.php
+++ b/src/Helpers/PatternParser.php
@@ -31,215 +31,223 @@
*
* @since 0.3
*/
-class PatternParser {
+class PatternParser
+{
+ /** Escape character for conversion words in the conversion pattern. */
+ const ESCAPE_CHAR = '%';
- /** Escape character for conversion words in the conversion pattern. */
- const ESCAPE_CHAR = '%';
+ /** Maps conversion words to relevant converters. */
+ private $converterMap;
- /** Maps conversion words to relevant converters. */
- private $converterMap;
+ /** Conversion pattern used in layout. */
+ private $pattern;
- /** Conversion pattern used in layout. */
- private $pattern;
+ /** Regex pattern used for parsing the conversion pattern. */
+ private $regex;
- /** Regex pattern used for parsing the conversion pattern. */
- private $regex;
+ /**
+ * First converter in the chain.
+ * @var AbstractConverter
+ */
+ private $head;
- /**
- * First converter in the chain.
- * @var AbstractConverter
- */
- private $head;
+ /** Last converter in the chain. */
+ private $tail;
- /** Last converter in the chain. */
- private $tail;
+ public function __construct($pattern, $converterMap)
+ {
+ $this->pattern = $pattern;
+ $this->converterMap = $converterMap;
- public function __construct($pattern, $converterMap) {
- $this->pattern = $pattern;
- $this->converterMap = $converterMap;
+ // Construct the regex pattern
+ $this->regex =
+ '/' . // Starting regex pattern delimiter
+ self::ESCAPE_CHAR . // Character which marks the start of the conversion pattern
+ '(?P<modifiers>[0-9.-]*)' . // Format modifiers (optional)
+ '(?P<word>[a-zA-Z]+)' . // The conversion word
+ '(?P<option>{[^}]*})?' . // Conversion option in braces (optional)
+ '/'; // Ending regex pattern delimiter
+ }
- // Construct the regex pattern
- $this->regex =
- '/' . // Starting regex pattern delimiter
- self::ESCAPE_CHAR . // Character which marks the start of the conversion pattern
- '(?P<modifiers>[0-9.-]*)' . // Format modifiers (optional)
- '(?P<word>[a-zA-Z]+)' . // The conversion word
- '(?P<option>{[^}]*})?' . // Conversion option in braces (optional)
- '/'; // Ending regex pattern delimiter
- }
+ /**
+ * Parses the conversion pattern string, converts it to a chain of pattern
+ * converters and returns the first converter in the chain.
+ *
+ * @return AbstractConverter
+ */
+ public function parse()
+ {
+ // Skip parsing if the pattern is empty
+ if (empty($this->pattern)) {
+ $this->addLiteral('');
- /**
- * Parses the conversion pattern string, converts it to a chain of pattern
- * converters and returns the first converter in the chain.
- *
- * @return AbstractConverter
- */
- public function parse() {
+ return $this->head;
+ }
- // Skip parsing if the pattern is empty
- if (empty($this->pattern)) {
- $this->addLiteral('');
- return $this->head;
- }
+ // Find all conversion words in the conversion pattern
+ $count = preg_match_all($this->regex, $this->pattern, $matches, PREG_OFFSET_CAPTURE);
+ if ($count === false) {
+ $error = error_get_last();
+ throw new LoggerException("Failed parsing layotut pattern: {$error['message']}");
+ }
- // Find all conversion words in the conversion pattern
- $count = preg_match_all($this->regex, $this->pattern, $matches, PREG_OFFSET_CAPTURE);
- if ($count === false) {
- $error = error_get_last();
- throw new LoggerException("Failed parsing layotut pattern: {$error['message']}");
- }
+ $prevEnd = 0;
- $prevEnd = 0;
+ foreach ($matches[0] as $key => $item) {
- foreach($matches[0] as $key => $item) {
+ // Locate where the conversion command starts and ends
+ $length = strlen($item[0]);
+ $start = $item[1];
+ $end = $item[1] + $length;
- // Locate where the conversion command starts and ends
- $length = strlen($item[0]);
- $start = $item[1];
- $end = $item[1] + $length;
+ // Find any literal expressions between matched commands
+ if ($start > $prevEnd) {
+ $literal = substr($this->pattern, $prevEnd, $start - $prevEnd);
+ $this->addLiteral($literal);
+ }
- // Find any literal expressions between matched commands
- if ($start > $prevEnd) {
- $literal = substr($this->pattern, $prevEnd, $start - $prevEnd);
- $this->addLiteral($literal);
- }
+ // Extract the data from the matched command
+ $word = !empty($matches['word'][$key]) ? $matches['word'][$key][0] : null;
+ $modifiers = !empty($matches['modifiers'][$key]) ? $matches['modifiers'][$key][0] : null;
+ $option = !empty($matches['option'][$key]) ? $matches['option'][$key][0] : null;
- // Extract the data from the matched command
- $word = !empty($matches['word'][$key]) ? $matches['word'][$key][0] : null;
- $modifiers = !empty($matches['modifiers'][$key]) ? $matches['modifiers'][$key][0] : null;
- $option = !empty($matches['option'][$key]) ? $matches['option'][$key][0] : null;
+ // Create a converter and add it to the chain
+ $this->addConverter($word, $modifiers, $option);
- // Create a converter and add it to the chain
- $this->addConverter($word, $modifiers, $option);
+ $prevEnd = $end;
+ }
- $prevEnd = $end;
- }
+ // Add any trailing literals
+ if ($end < strlen($this->pattern)) {
+ $literal = substr($this->pattern, $end);
+ $this->addLiteral($literal);
+ }
- // Add any trailing literals
- if ($end < strlen($this->pattern)) {
- $literal = substr($this->pattern, $end);
- $this->addLiteral($literal);
- }
+ return $this->head;
+ }
- return $this->head;
- }
+ /**
+ * Adds a literal converter to the converter chain.
+ * @param string $string The string for the literal converter.
+ */
+ private function addLiteral($string)
+ {
+ $converter = new LiteralConverter($string);
+ $this->addToChain($converter);
+ }
- /**
- * Adds a literal converter to the converter chain.
- * @param string $string The string for the literal converter.
- */
- private function addLiteral($string) {
- $converter = new LiteralConverter($string);
- $this->addToChain($converter);
- }
+ /**
+ * Adds a non-literal converter to the converter chain.
+ *
+ * @param string $word The conversion word, used to determine which
+ * converter will be used.
+ * @param string $modifiers Formatting modifiers.
+ * @param string $option Option to pass to the converter.
+ */
+ private function addConverter($word, $modifiers, $option)
+ {
+ $formattingInfo = $this->parseModifiers($modifiers);
+ $option = trim($option, "{} ");
- /**
- * Adds a non-literal converter to the converter chain.
- *
- * @param string $word The conversion word, used to determine which
- * converter will be used.
- * @param string $modifiers Formatting modifiers.
- * @param string $option Option to pass to the converter.
- */
- private function addConverter($word, $modifiers, $option) {
- $formattingInfo = $this->parseModifiers($modifiers);
- $option = trim($option, "{} ");
+ if (isset($this->converterMap[$word])) {
+ $converter = $this->getConverter($word, $formattingInfo, $option);
+ $this->addToChain($converter);
+ } else {
+ trigger_error("log4php: Invalid keyword '%$word' in converison pattern. Ignoring keyword.", E_USER_WARNING);
+ }
+ }
- if (isset($this->converterMap[$word])) {
- $converter = $this->getConverter($word, $formattingInfo, $option);
- $this->addToChain($converter);
- } else {
- trigger_error("log4php: Invalid keyword '%$word' in converison pattern. Ignoring keyword.", E_USER_WARNING);
- }
- }
+ /**
+ * Determines which converter to use based on the conversion word. Creates
+ * an instance of the converter using the provided formatting info and
+ * option and returns it.
+ *
+ * @param string $word The conversion word.
+ * @param FormattingInfo $info Formatting info.
+ * @param string $option Converter option.
+ *
+ * @throws LoggerException
+ *
+ * @return AbstractConverter
+ */
+ private function getConverter($word, $info, $option)
+ {
+ if (!isset($this->converterMap[$word])) {
+ throw new LoggerException("Invalid keyword '%$word' in converison pattern. Ignoring keyword.");
+ }
- /**
- * Determines which converter to use based on the conversion word. Creates
- * an instance of the converter using the provided formatting info and
- * option and returns it.
- *
- * @param string $word The conversion word.
- * @param FormattingInfo $info Formatting info.
- * @param string $option Converter option.
- *
- * @throws LoggerException
- *
- * @return AbstractConverter
- */
- private function getConverter($word, $info, $option) {
- if (!isset($this->converterMap[$word])) {
- throw new LoggerException("Invalid keyword '%$word' in converison pattern. Ignoring keyword.");
- }
+ $class = $this->converterMap[$word];
+ if (class_exists($class)) {
+ $converter = new $class($info, $option);
+ } else {
+ $nsClass = "Apache\\Log4php\\Pattern\\$class";
+ if (class_exists($nsClass)) {
+ $converter = new $nsClass($info, $option);
+ }
+ }
- $class = $this->converterMap[$word];
- if (class_exists($class)) {
- $converter = new $class($info, $option);
- } else {
- $nsClass = "Apache\\Log4php\\Pattern\\$class";
- if (class_exists($nsClass)) {
- $converter = new $nsClass($info, $option);
- }
- }
+ if (!isset($converter)) {
+ throw new LoggerException("Class '$class' does not exist.");
+ }
- if (!isset($converter)) {
- throw new LoggerException("Class '$class' does not exist.");
- }
+ if (!($converter instanceof AbstractConverter)) {
+ throw new LoggerException("Class '$class' is not an instance of AbstractConverter.");
+ }
- if(!($converter instanceof AbstractConverter)) {
- throw new LoggerException("Class '$class' is not an instance of AbstractConverter.");
- }
+ return $converter;
+ }
- return $converter;
- }
+ /** Adds a converter to the chain and updates $head and $tail pointers. */
+ private function addToChain(AbstractConverter $converter)
+ {
+ if (!isset($this->head)) {
+ $this->head = $converter;
+ $this->tail = $this->head;
+ } else {
+ $this->tail->next = $converter;
+ $this->tail = $this->tail->next;
+ }
+ }
- /** Adds a converter to the chain and updates $head and $tail pointers. */
- private function addToChain(AbstractConverter $converter) {
- if (!isset($this->head)) {
- $this->head = $converter;
- $this->tail = $this->head;
- } else {
- $this->tail->next = $converter;
- $this->tail = $this->tail->next;
- }
- }
+ /**
+ * Parses the formatting modifiers and produces the corresponding
+ * FormattingInfo object.
+ *
+ * @param string $modifier
+ * @return FormattingInfo
+ * @throws LoggerException
+ */
+ private function parseModifiers($modifiers)
+ {
+ $info = new FormattingInfo();
- /**
- * Parses the formatting modifiers and produces the corresponding
- * FormattingInfo object.
- *
- * @param string $modifier
- * @return FormattingInfo
- * @throws LoggerException
- */
- private function parseModifiers($modifiers) {
- $info = new FormattingInfo();
+ // If no modifiers are given, return default values
+ if (empty($modifiers)) {
+ return $info;
+ }
- // If no modifiers are given, return default values
- if (empty($modifiers)) {
- return $info;
- }
+ // Validate
+ $pattern = '/^(-?[0-9]+)?\.?-?[0-9]+$/';
+ if (!preg_match($pattern, $modifiers)) {
+ trigger_error("log4php: Invalid modifier in conversion pattern: [$modifiers]. Ignoring modifier.", E_USER_WARNING);
- // Validate
- $pattern = '/^(-?[0-9]+)?\.?-?[0-9]+$/';
- if (!preg_match($pattern, $modifiers)) {
- trigger_error("log4php: Invalid modifier in conversion pattern: [$modifiers]. Ignoring modifier.", E_USER_WARNING);
- return $info;
- }
+ return $info;
+ }
- $parts = explode('.', $modifiers);
+ $parts = explode('.', $modifiers);
- if (!empty($parts[0])) {
- $minPart = (integer) $parts[0];
- $info->min = abs($minPart);
- $info->padLeft = ($minPart > 0);
- }
+ if (!empty($parts[0])) {
+ $minPart = (integer) $parts[0];
+ $info->min = abs($minPart);
+ $info->padLeft = ($minPart > 0);
+ }
- if (!empty($parts[1])) {
- $maxPart = (integer) $parts[1];
- $info->max = abs($maxPart);
- $info->trimLeft = ($maxPart < 0);
- }
+ if (!empty($parts[1])) {
+ $maxPart = (integer) $parts[1];
+ $info->max = abs($maxPart);
+ $info->trimLeft = ($maxPart < 0);
+ }
- return $info;
- }
+ return $info;
+ }
}
diff --git a/src/Helpers/Utils.php b/src/Helpers/Utils.php
index 52be24d..01d5a40 100644
--- a/src/Helpers/Utils.php
+++ b/src/Helpers/Utils.php
@@ -22,99 +22,100 @@
* Contains various helper methods.
* @since 2.3
*/
-class Utils {
+class Utils
+{
+ /**
+ * Splits a fully qualified class name into fragments delimited by the
+ * namespace separator (\).
+ *
+ * For backward compatibility, a dot (.) can be used as a delimiter as
+ * well.
+ *
+ * @param string $name
+ *
+ * @return array Class name split into fragments.
+ */
+ public static function tokenizeClassName($name)
+ {
+ $name = str_replace('.', '\\', $name);
+ $name = trim($name, ' \\');
+ $fragments = explode('\\', $name);
- /**
- * Splits a fully qualified class name into fragments delimited by the
- * namespace separator (\).
- *
- * For backward compatibility, a dot (.) can be used as a delimiter as
- * well.
- *
- * @param string $name
- *
- * @return array Class name split into fragments.
- */
- public static function tokenizeClassName($name) {
- $name = str_replace('.', '\\', $name);
- $name = trim($name, ' \\');
- $fragments = explode('\\', $name);
+ foreach ($fragments as $key => $fragment) {
+ if (trim($fragment) === '') {
+ unset($fragments[$key]);
+ }
+ }
- foreach($fragments as $key => $fragment) {
- if (trim($fragment) === '') {
- unset($fragments[$key]);
- }
- }
+ return $fragments;
+ }
- return $fragments;
- }
+ /**
+ * Attempts to shorten the given class name to the desired length.
+ *
+ * This is done by separating the class name into fragments (delimited
+ * by \ or .) and trimming individual fragments, starting with the left,
+ * until desired length has been reached.
+ *
+ * The final fragment (i.e. class name) will never be shortened so the
+ * result may still be longer than given length.
+ *
+ * @param string $name The (qualified) class name.
+ * @param integer $length The length to shorten to. If null or 0 is given,
+ * the name will be returned without shortening.
+ */
+ public static function shortenClassName($name, $length)
+ {
+ if ($length === null || $length < 0) {
+ return $name;
+ }
- /**
- * Attempts to shorten the given class name to the desired length.
- *
- * This is done by separating the class name into fragments (delimited
- * by \ or .) and trimming individual fragments, starting with the left,
- * until desired length has been reached.
- *
- * The final fragment (i.e. class name) will never be shortened so the
- * result may still be longer than given length.
- *
- * @param string $name The (qualified) class name.
- * @param integer $length The length to shorten to. If null or 0 is given,
- * the name will be returned without shortening.
- */
- public static function shortenClassName($name, $length) {
- if ($length === null || $length < 0) {
- return $name;
- }
+ $name = str_replace('.', '\\', $name);
+ $name = trim($name, ' \\');
- $name = str_replace('.', '\\', $name);
- $name = trim($name, ' \\');
+ // Check if any shortening is required
+ $currentLength = strlen($name);
+ if ($currentLength <= $length) {
+ return $name;
+ }
- // Check if any shortening is required
- $currentLength = strlen($name);
- if ($currentLength <= $length) {
- return $name;
- }
+ // Split name into fragments
+ $fragments = explode('\\', $name);
- // Split name into fragments
- $fragments = explode('\\', $name);
+ // If zero length is specified, return only last fragment
+ if ($length == 0) {
+ return array_pop($fragments);
+ }
- // If zero length is specified, return only last fragment
- if ($length == 0) {
- return array_pop($fragments);
- }
+ // If the name splits to only one fragment, then it cannot be shortened
+ $count = count($fragments);
+ if ($count == 1) {
+ return $name;
+ }
- // If the name splits to only one fragment, then it cannot be shortened
- $count = count($fragments);
- if ($count == 1) {
- return $name;
- }
+ foreach ($fragments as $key => &$fragment) {
- foreach($fragments as $key => &$fragment) {
+ // Never shorten last fragment
+ if ($key == $count - 1) {
+ break;
+ }
- // Never shorten last fragment
- if ($key == $count - 1) {
- break;
- }
+ // Check for empty fragments (shouldn't happen but it's possible)
+ $fragLen = strlen($fragment);
+ if ($fragLen <= 1) {
+ continue;
+ }
- // Check for empty fragments (shouldn't happen but it's possible)
- $fragLen = strlen($fragment);
- if ($fragLen <= 1) {
- continue;
- }
+ // Shorten fragment to one character and check if total length satisfactory
+ $fragment = substr($fragment, 0, 1);
+ $currentLength = $currentLength - $fragLen + 1;
- // Shorten fragment to one character and check if total length satisfactory
- $fragment = substr($fragment, 0, 1);
- $currentLength = $currentLength - $fragLen + 1;
+ if ($currentLength <= $length) {
+ break;
+ }
+ }
+ unset($fragment);
- if ($currentLength <= $length) {
- break;
- }
- }
- unset($fragment);
-
- return implode('\\', $fragments);
- }
+ return implode('\\', $fragments);
+ }
}
-
diff --git a/src/Hierarchy.php b/src/Hierarchy.php
index 7b28a6b..384b8ee 100644
--- a/src/Hierarchy.php
+++ b/src/Hierarchy.php
@@ -46,211 +46,225 @@
* to the provision node. Other descendants of the same ancestor add
* themselves to the previously created provision node.</p>
*/
-class Hierarchy {
+class Hierarchy
+{
+ /** Array holding all Logger instances. */
+ protected $loggers = array();
- /** Array holding all Logger instances. */
- protected $loggers = array();
+ /**
+ * The root logger.
+ * @var RootLogger
+ */
+ protected $root;
- /**
- * The root logger.
- * @var RootLogger
- */
- protected $root;
+ /**
+ * The logger renderer map.
+ * @var RendererMap
+ */
+ protected $rendererMap;
- /**
- * The logger renderer map.
- * @var RendererMap
- */
- protected $rendererMap;
+ /**
+ * Main level threshold. Events with lower level will not be logged by any
+ * logger, regardless of it's configuration.
+ * @var Level
+ */
+ protected $threshold;
- /**
- * Main level threshold. Events with lower level will not be logged by any
- * logger, regardless of it's configuration.
- * @var Level
- */
- protected $threshold;
+ /**
+ * Creates a new logger hierarchy.
+ * @param RootLogger $root The root logger.
+ */
+ public function __construct(RootLogger $root)
+ {
+ $this->root = $root;
+ $this->setThreshold(Level::getLevelAll());
+ $this->rendererMap = new RendererMap();
+ }
- /**
- * Creates a new logger hierarchy.
- * @param RootLogger $root The root logger.
- */
- public function __construct(RootLogger $root) {
- $this->root = $root;
- $this->setThreshold(Level::getLevelAll());
- $this->rendererMap = new RendererMap();
- }
+ /**
+ * Clears all loggers.
+ */
+ public function clear()
+ {
+ $this->loggers = array();
+ }
- /**
- * Clears all loggers.
- */
- public function clear() {
- $this->loggers = array();
- }
+ /**
+ * Check if the named logger exists in the hierarchy.
+ * @param string $name
+ * @return boolean
+ */
+ public function exists($name)
+ {
+ return isset($this->loggers[$name]);
+ }
- /**
- * Check if the named logger exists in the hierarchy.
- * @param string $name
- * @return boolean
- */
- public function exists($name) {
- return isset($this->loggers[$name]);
- }
+ /**
+ * Returns all the currently defined loggers in this hierarchy as an array.
+ * @return array
+ */
+ public function getCurrentLoggers()
+ {
+ return array_values($this->loggers);
+ }
- /**
- * Returns all the currently defined loggers in this hierarchy as an array.
- * @return array
- */
- public function getCurrentLoggers() {
- return array_values($this->loggers);
- }
+ /**
+ * Returns a named logger instance logger. If it doesn't exist, one is created.
+ *
+ * @param string $name Logger name
+ * @return Logger Logger instance.
+ */
+ public function getLogger($name)
+ {
+ if (!isset($this->loggers[$name])) {
+ $logger = new Logger($name);
- /**
- * Returns a named logger instance logger. If it doesn't exist, one is created.
- *
- * @param string $name Logger name
- * @return Logger Logger instance.
- */
- public function getLogger($name) {
- if(!isset($this->loggers[$name])) {
- $logger = new Logger($name);
+ $nodes = explode('.', $name);
+ $firstNode = array_shift($nodes);
- $nodes = explode('.', $name);
- $firstNode = array_shift($nodes);
+ // if name is not a first node but another first node is their
+ if ($firstNode != $name and isset($this->loggers[$firstNode])) {
+ $logger->setParent($this->loggers[$firstNode]);
+ } else {
+ // if there is no father, set root logger as father
+ $logger->setParent($this->root);
+ }
- // if name is not a first node but another first node is their
- if($firstNode != $name and isset($this->loggers[$firstNode])) {
- $logger->setParent($this->loggers[$firstNode]);
- } else {
- // if there is no father, set root logger as father
- $logger->setParent($this->root);
- }
+ // if there are more nodes than one
+ if (count($nodes) > 0) {
+ // find parent node
+ foreach ($nodes as $node) {
+ $parentNode = "$firstNode.$node";
+ if (isset($this->loggers[$parentNode]) and $parentNode != $name) {
+ $logger->setParent($this->loggers[$parentNode]);
+ }
+ $firstNode .= ".$node";
+ }
+ }
- // if there are more nodes than one
- if(count($nodes) > 0) {
- // find parent node
- foreach($nodes as $node) {
- $parentNode = "$firstNode.$node";
- if(isset($this->loggers[$parentNode]) and $parentNode != $name) {
- $logger->setParent($this->loggers[$parentNode]);
- }
- $firstNode .= ".$node";
- }
- }
+ $this->loggers[$name] = $logger;
+ }
- $this->loggers[$name] = $logger;
- }
+ return $this->loggers[$name];
+ }
- return $this->loggers[$name];
- }
+ /**
+ * Returns the logger renderer map.
+ * @return RendererMap
+ */
+ public function getRendererMap()
+ {
+ return $this->rendererMap;
+ }
- /**
- * Returns the logger renderer map.
- * @return RendererMap
- */
- public function getRendererMap() {
- return $this->rendererMap;
- }
+ /**
+ * Returns the root logger.
+ * @return RootLogger
+ */
+ public function getRootLogger()
+ {
+ return $this->root;
+ }
- /**
- * Returns the root logger.
- * @return RootLogger
- */
- public function getRootLogger() {
- return $this->root;
- }
+ /**
+ * Returns the main threshold level.
+ * @return Level
+ */
+ public function getThreshold()
+ {
+ return $this->threshold;
+ }
- /**
- * Returns the main threshold level.
- * @return Level
- */
- public function getThreshold() {
- return $this->threshold;
- }
+ /**
+ * Returns true if the hierarchy is disabled for given log level and false
+ * otherwise.
+ * @return boolean
+ */
+ public function isDisabled(Level $level)
+ {
+ return ($this->threshold->toInt() > $level->toInt());
+ }
- /**
- * Returns true if the hierarchy is disabled for given log level and false
- * otherwise.
- * @return boolean
- */
- public function isDisabled(Level $level) {
- return ($this->threshold->toInt() > $level->toInt());
- }
+ /**
+ * Reset all values contained in this hierarchy instance to their
+ * default.
+ *
+ * This removes all appenders from all loggers, sets
+ * the level of all non-root loggers to <i>null</i>,
+ * sets their additivity flag to <i>true</i> and sets the level
+ * of the root logger to {@link LOGGER_LEVEL_DEBUG}.
+ *
+ * <p>Existing loggers are not removed. They are just reset.
+ *
+ * <p>This method should be used sparingly and with care as it will
+ * block all logging until it is completed.</p>
+ */
+ public function resetConfiguration()
+ {
+ $root = $this->getRootLogger();
- /**
- * Reset all values contained in this hierarchy instance to their
- * default.
- *
- * This removes all appenders from all loggers, sets
- * the level of all non-root loggers to <i>null</i>,
- * sets their additivity flag to <i>true</i> and sets the level
- * of the root logger to {@link LOGGER_LEVEL_DEBUG}.
- *
- * <p>Existing loggers are not removed. They are just reset.
- *
- * <p>This method should be used sparingly and with care as it will
- * block all logging until it is completed.</p>
- */
- public function resetConfiguration() {
- $root = $this->getRootLogger();
+ $root->setLevel(Level::getLevelDebug());
+ $this->setThreshold(Level::getLevelAll());
+ $this->shutDown();
- $root->setLevel(Level::getLevelDebug());
- $this->setThreshold(Level::getLevelAll());
- $this->shutDown();
+ foreach ($this->loggers as $logger) {
+ $logger->setLevel(null);
+ $logger->setAdditivity(true);
+ $logger->removeAllAppenders();
+ }
- foreach($this->loggers as $logger) {
- $logger->setLevel(null);
- $logger->setAdditivity(true);
- $logger->removeAllAppenders();
- }
+ $this->rendererMap->reset();
+ AppenderPool::clear();
+ }
- $this->rendererMap->reset();
- AppenderPool::clear();
- }
+ /**
+ * Sets the main threshold level.
+ * @param Level $l
+ */
+ public function setThreshold(Level $threshold)
+ {
+ $this->threshold = $threshold;
+ }
- /**
- * Sets the main threshold level.
- * @param Level $l
- */
- public function setThreshold(Level $threshold) {
- $this->threshold = $threshold;
- }
+ /**
+ * Shutting down a hierarchy will <i>safely</i> close and remove
+ * all appenders in all loggers including the root logger.
+ *
+ * The shutdown method is careful to close nested
+ * appenders before closing regular appenders. This is allows
+ * configurations where a regular appender is attached to a logger
+ * and again to a nested appender.
+ *
+ * @todo Check if the last paragraph is correct.
+ */
+ public function shutdown()
+ {
+ $this->root->removeAllAppenders();
- /**
- * Shutting down a hierarchy will <i>safely</i> close and remove
- * all appenders in all loggers including the root logger.
- *
- * The shutdown method is careful to close nested
- * appenders before closing regular appenders. This is allows
- * configurations where a regular appender is attached to a logger
- * and again to a nested appender.
- *
- * @todo Check if the last paragraph is correct.
- */
- public function shutdown() {
- $this->root->removeAllAppenders();
+ foreach ($this->loggers as $logger) {
+ $logger->removeAllAppenders();
+ }
+ }
- foreach($this->loggers as $logger) {
- $logger->removeAllAppenders();
- }
- }
+ /**
+ * Prints the current Logger hierarchy tree. Useful for debugging.
+ */
+ public function printHierarchy()
+ {
+ $this->printHierarchyInner($this->getRootLogger(), 0);
+ }
- /**
- * Prints the current Logger hierarchy tree. Useful for debugging.
- */
- public function printHierarchy() {
- $this->printHierarchyInner($this->getRootLogger(), 0);
- }
+ private function printHierarchyInner(Logger $current, $level)
+ {
+ for ($i = 0; $i < $level; $i++) {
+ echo ($i == $level - 1) ? "|--" : "| ";
+ }
+ echo $current->getName() . "\n";
- private function printHierarchyInner(Logger $current, $level) {
- for ($i = 0; $i < $level; $i++) {
- echo ($i == $level - 1) ? "|--" : "| ";
- }
- echo $current->getName() . "\n";
-
- foreach($this->loggers as $logger) {
- if ($logger->getParent() == $current) {
- $this->printHierarchyInner($logger, $level + 1);
- }
- }
- }
+ foreach ($this->loggers as $logger) {
+ if ($logger->getParent() == $current) {
+ $this->printHierarchyInner($logger, $level + 1);
+ }
+ }
+ }
}
diff --git a/src/Layouts/AbstractLayout.php b/src/Layouts/AbstractLayout.php
index b6a2d14..3a8e486 100644
--- a/src/Layouts/AbstractLayout.php
+++ b/src/Layouts/AbstractLayout.php
@@ -24,51 +24,58 @@
/**
* Extend this abstract class to create your own log layout format.
*/
-abstract class AbstractLayout extends Configurable {
- /**
- * Activates options for this layout.
- * Override this method if you have options to be activated.
- */
- public function activateOptions() {
- return true;
- }
+abstract class AbstractLayout extends Configurable
+{
+ /**
+ * Activates options for this layout.
+ * Override this method if you have options to be activated.
+ */
+ public function activateOptions()
+ {
+ return true;
+ }
- /**
- * Override this method to create your own layout format.
- *
- * @param LoggingEvent
- * @return string
- */
- public function format(LoggingEvent $event) {
- return $event->getRenderedMessage();
- }
+ /**
+ * Override this method to create your own layout format.
+ *
+ * @param LoggingEvent
+ * @return string
+ */
+ public function format(LoggingEvent $event)
+ {
+ return $event->getRenderedMessage();
+ }
- /**
- * Returns the content type output by this layout.
- * @return string
- */
- public function getContentType() {
- return "text/plain";
- }
+ /**
+ * Returns the content type output by this layout.
+ * @return string
+ */
+ public function getContentType()
+ {
+ return "text/plain";
+ }
- /**
- * Returns the footer for the layout format.
- * @return string
- */
- public function getFooter() {
- return null;
- }
+ /**
+ * Returns the footer for the layout format.
+ * @return string
+ */
+ public function getFooter()
+ {
+ return null;
+ }
- /**
- * Returns the header for the layout format.
- * @return string
- */
- public function getHeader() {
- return null;
- }
+ /**
+ * Returns the header for the layout format.
+ * @return string
+ */
+ public function getHeader()
+ {
+ return null;
+ }
- /** Triggers a warning for this layout with the given message. */
- protected function warn($message) {
- trigger_error("log4php: [" . get_class($this) . "]: $message", E_USER_WARNING);
- }
+ /** Triggers a warning for this layout with the given message. */
+ protected function warn($message)
+ {
+ trigger_error("log4php: [" . get_class($this) . "]: $message", E_USER_WARNING);
+ }
}
diff --git a/src/Layouts/HtmlLayout.php b/src/Layouts/HtmlLayout.php
index af74e61..6a5bd50 100644
--- a/src/Layouts/HtmlLayout.php
+++ b/src/Layouts/HtmlLayout.php
@@ -29,169 +29,179 @@
* - title
* - locationInfo
*/
-class HtmlLayout extends AbstractLayout {
- /**
- * The <b>LocationInfo</b> option takes a boolean value. By
- * default, it is set to false which means there will be no location
- * information output by this layout. If the the option is set to
- * true, then the file name and line number of the statement
- * at the origin of the log statement will be output.
- *
- * <p>If you are embedding this layout within a {@link MailAppender}
- * or a {@link MailEventAppender} then make sure to set the
- * <b>LocationInfo</b> option of that appender as well.
- * @var boolean
- */
- protected $locationInfo = false;
+class HtmlLayout extends AbstractLayout
+{
+ /**
+ * The <b>LocationInfo</b> option takes a boolean value. By
+ * default, it is set to false which means there will be no location
+ * information output by this layout. If the the option is set to
+ * true, then the file name and line number of the statement
+ * at the origin of the log statement will be output.
+ *
+ * <p>If you are embedding this layout within a {@link MailAppender}
+ * or a {@link MailEventAppender} then make sure to set the
+ * <b>LocationInfo</b> option of that appender as well.
+ * @var boolean
+ */
+ protected $locationInfo = false;
- /**
- * The <b>Title</b> option takes a String value. This option sets the
- * document title of the generated HTML document.
- * Defaults to 'Log4php Log Messages'.
- * @var string
- */
- protected $title = "Log4php Log Messages";
+ /**
+ * The <b>Title</b> option takes a String value. This option sets the
+ * document title of the generated HTML document.
+ * Defaults to 'Log4php Log Messages'.
+ * @var string
+ */
+ protected $title = "Log4php Log Messages";
- /**
- * The <b>LocationInfo</b> option takes a boolean value. By
- * default, it is set to false which means there will be no location
- * information output by this layout. If the the option is set to
- * true, then the file name and line number of the statement
- * at the origin of the log statement will be output.
- *
- * <p>If you are embedding this layout within a {@link MailAppender}
- * or a {@link MailEventAppender} then make sure to set the
- * <b>LocationInfo</b> option of that appender as well.
- */
- public function setLocationInfo($flag) {
- $this->setBoolean('locationInfo', $flag);
- }
+ /**
+ * The <b>LocationInfo</b> option takes a boolean value. By
+ * default, it is set to false which means there will be no location
+ * information output by this layout. If the the option is set to
+ * true, then the file name and line number of the statement
+ * at the origin of the log statement will be output.
+ *
+ * <p>If you are embedding this layout within a {@link MailAppender}
+ * or a {@link MailEventAppender} then make sure to set the
+ * <b>LocationInfo</b> option of that appender as well.
+ */
+ public function setLocationInfo($flag)
+ {
+ $this->setBoolean('locationInfo', $flag);
+ }
- /**
- * Returns the current value of the <b>LocationInfo</b> option.
- */
- public function getLocationInfo() {
- return $this->locationInfo;
- }
+ /**
+ * Returns the current value of the <b>LocationInfo</b> option.
+ */
+ public function getLocationInfo()
+ {
+ return $this->locationInfo;
+ }
- /**
- * The <b>Title</b> option takes a String value. This option sets the
- * document title of the generated HTML document.
- * Defaults to 'Log4php Log Messages'.
- */
- public function setTitle($title) {
- $this->setString('title', $title);
- }
+ /**
+ * The <b>Title</b> option takes a String value. This option sets the
+ * document title of the generated HTML document.
+ * Defaults to 'Log4php Log Messages'.
+ */
+ public function setTitle($title)
+ {
+ $this->setString('title', $title);
+ }
- /**
- * @return string Returns the current value of the <b>Title</b> option.
- */
- public function getTitle() {
- return $this->title;
- }
+ /**
+ * @return string Returns the current value of the <b>Title</b> option.
+ */
+ public function getTitle()
+ {
+ return $this->title;
+ }
- /**
- * @return string Returns the content type output by this layout, i.e "text/html".
- */
- public function getContentType() {
- return "text/html";
- }
+ /**
+ * @return string Returns the content type output by this layout, i.e "text/html".
+ */
+ public function getContentType()
+ {
+ return "text/html";
+ }
- /**
- * @param LoggingEvent $event
- * @return string
- */
- public function format(LoggingEvent $event) {
- $sbuf = PHP_EOL . "<tr>" . PHP_EOL;
+ /**
+ * @param LoggingEvent $event
+ * @return string
+ */
+ public function format(LoggingEvent $event)
+ {
+ $sbuf = PHP_EOL . "<tr>" . PHP_EOL;
- $sbuf .= "<td>";
- $sbuf .= round(1000 * $event->getRelativeTime());
- $sbuf .= "</td>" . PHP_EOL;
+ $sbuf .= "<td>";
+ $sbuf .= round(1000 * $event->getRelativeTime());
+ $sbuf .= "</td>" . PHP_EOL;
- $sbuf .= "<td title=\"" . $event->getThreadName() . " thread\">";
- $sbuf .= $event->getThreadName();
- $sbuf .= "</td>" . PHP_EOL;
+ $sbuf .= "<td title=\"" . $event->getThreadName() . " thread\">";
+ $sbuf .= $event->getThreadName();
+ $sbuf .= "</td>" . PHP_EOL;
- $sbuf .= "<td title=\"Level\">";
+ $sbuf .= "<td title=\"Level\">";
- $level = $event->getLevel();
+ $level = $event->getLevel();
- if ($level->equals(Level::getLevelDebug())) {
- $sbuf .= "<font color=\"#339933\">$level</font>";
- } else if ($level->equals(Level::getLevelWarn())) {
- $sbuf .= "<font color=\"#993300\"><strong>$level</strong></font>";
- } else {
- $sbuf .= $level;
- }
- $sbuf .= "</td>" . PHP_EOL;
+ if ($level->equals(Level::getLevelDebug())) {
+ $sbuf .= "<font color=\"#339933\">$level</font>";
+ } elseif ($level->equals(Level::getLevelWarn())) {
+ $sbuf .= "<font color=\"#993300\"><strong>$level</strong></font>";
+ } else {
+ $sbuf .= $level;
+ }
+ $sbuf .= "</td>" . PHP_EOL;
- $sbuf .= "<td title=\"" . htmlentities($event->getLoggerName(), ENT_QUOTES) . " category\">";
- $sbuf .= htmlentities($event->getLoggerName(), ENT_QUOTES);
- $sbuf .= "</td>" . PHP_EOL;
+ $sbuf .= "<td title=\"" . htmlentities($event->getLoggerName(), ENT_QUOTES) . " category\">";
+ $sbuf .= htmlentities($event->getLoggerName(), ENT_QUOTES);
+ $sbuf .= "</td>" . PHP_EOL;
- if ($this->locationInfo) {
- $locInfo = $event->getLocationInformation();
- $sbuf .= "<td>";
- $sbuf .= htmlentities($locInfo->getFileName(), ENT_QUOTES). ':' . $locInfo->getLineNumber();
- $sbuf .= "</td>" . PHP_EOL;
- }
+ if ($this->locationInfo) {
+ $locInfo = $event->getLocationInformation();
+ $sbuf .= "<td>";
+ $sbuf .= htmlentities($locInfo->getFileName(), ENT_QUOTES). ':' . $locInfo->getLineNumber();
+ $sbuf .= "</td>" . PHP_EOL;
+ }
- $sbuf .= "<td title=\"Message\">";
- $sbuf .= htmlentities($event->getRenderedMessage(), ENT_QUOTES);
- $sbuf .= "</td>" . PHP_EOL;
+ $sbuf .= "<td title=\"Message\">";
+ $sbuf .= htmlentities($event->getRenderedMessage(), ENT_QUOTES);
+ $sbuf .= "</td>" . PHP_EOL;
- $sbuf .= "</tr>" . PHP_EOL;
+ $sbuf .= "</tr>" . PHP_EOL;
- if ($event->getNDC() != null) {
- $sbuf .= "<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">";
- $sbuf .= "NDC: " . htmlentities($event->getNDC(), ENT_QUOTES);
- $sbuf .= "</td></tr>" . PHP_EOL;
- }
- return $sbuf;
- }
+ if ($event->getNDC() != null) {
+ $sbuf .= "<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">";
+ $sbuf .= "NDC: " . htmlentities($event->getNDC(), ENT_QUOTES);
+ $sbuf .= "</td></tr>" . PHP_EOL;
+ }
- /**
- * @return string Returns appropriate HTML headers.
- */
- public function getHeader() {
- $sbuf = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" . PHP_EOL;
- $sbuf .= "<html>" . PHP_EOL;
- $sbuf .= "<head>" . PHP_EOL;
- $sbuf .= "<title>" . $this->title . "</title>" . PHP_EOL;
- $sbuf .= "<style type=\"text/css\">" . PHP_EOL;
- $sbuf .= "<!--" . PHP_EOL;
- $sbuf .= "body, table {font-family: arial,sans-serif; font-size: x-small;}" . PHP_EOL;
- $sbuf .= "th {background: #336699; color: #FFFFFF; text-align: left;}" . PHP_EOL;
- $sbuf .= "-->" . PHP_EOL;
- $sbuf .= "</style>" . PHP_EOL;
- $sbuf .= "</head>" . PHP_EOL;
- $sbuf .= "<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">" . PHP_EOL;
- $sbuf .= "<hr size=\"1\" noshade>" . PHP_EOL;
- $sbuf .= "Log session start time " . strftime('%c', time()) . "<br>" . PHP_EOL;
- $sbuf .= "<br>" . PHP_EOL;
- $sbuf .= "<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">" . PHP_EOL;
- $sbuf .= "<tr>" . PHP_EOL;
- $sbuf .= "<th>Time</th>" . PHP_EOL;
- $sbuf .= "<th>Thread</th>" . PHP_EOL;
- $sbuf .= "<th>Level</th>" . PHP_EOL;
- $sbuf .= "<th>Category</th>" . PHP_EOL;
- if ($this->locationInfo) {
- $sbuf .= "<th>File:Line</th>" . PHP_EOL;
- }
- $sbuf .= "<th>Message</th>" . PHP_EOL;
- $sbuf .= "</tr>" . PHP_EOL;
+ return $sbuf;
+ }
- return $sbuf;
- }
+ /**
+ * @return string Returns appropriate HTML headers.
+ */
+ public function getHeader()
+ {
+ $sbuf = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" . PHP_EOL;
+ $sbuf .= "<html>" . PHP_EOL;
+ $sbuf .= "<head>" . PHP_EOL;
+ $sbuf .= "<title>" . $this->title . "</title>" . PHP_EOL;
+ $sbuf .= "<style type=\"text/css\">" . PHP_EOL;
+ $sbuf .= "<!--" . PHP_EOL;
+ $sbuf .= "body, table {font-family: arial,sans-serif; font-size: x-small;}" . PHP_EOL;
+ $sbuf .= "th {background: #336699; color: #FFFFFF; text-align: left;}" . PHP_EOL;
+ $sbuf .= "-->" . PHP_EOL;
+ $sbuf .= "</style>" . PHP_EOL;
+ $sbuf .= "</head>" . PHP_EOL;
+ $sbuf .= "<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">" . PHP_EOL;
+ $sbuf .= "<hr size=\"1\" noshade>" . PHP_EOL;
+ $sbuf .= "Log session start time " . strftime('%c', time()) . "<br>" . PHP_EOL;
+ $sbuf .= "<br>" . PHP_EOL;
+ $sbuf .= "<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">" . PHP_EOL;
+ $sbuf .= "<tr>" . PHP_EOL;
+ $sbuf .= "<th>Time</th>" . PHP_EOL;
+ $sbuf .= "<th>Thread</th>" . PHP_EOL;
+ $sbuf .= "<th>Level</th>" . PHP_EOL;
+ $sbuf .= "<th>Category</th>" . PHP_EOL;
+ if ($this->locationInfo) {
+ $sbuf .= "<th>File:Line</th>" . PHP_EOL;
+ }
+ $sbuf .= "<th>Message</th>" . PHP_EOL;
+ $sbuf .= "</tr>" . PHP_EOL;
- /**
- * @return string Returns the appropriate HTML footers.
- */
- public function getFooter() {
- $sbuf = "</table>" . PHP_EOL;
- $sbuf .= "<br>" . PHP_EOL;
- $sbuf .= "</body></html>";
+ return $sbuf;
+ }
- return $sbuf;
- }
+ /**
+ * @return string Returns the appropriate HTML footers.
+ */
+ public function getFooter()
+ {
+ $sbuf = "</table>" . PHP_EOL;
+ $sbuf .= "<br>" . PHP_EOL;
+ $sbuf .= "</body></html>";
+
+ return $sbuf;
+ }
}
diff --git a/src/Layouts/PatternLayout.php b/src/Layouts/PatternLayout.php
index c34cbe2..58f1b50 100644
--- a/src/Layouts/PatternLayout.php
+++ b/src/Layouts/PatternLayout.php
@@ -30,142 +30,148 @@
* * converionPattern - A string which controls the formatting of logging
* events. See docs for full specification.
*/
-class PatternLayout extends AbstractLayout {
+class PatternLayout extends AbstractLayout
+{
+ /** Default conversion pattern */
+ const DEFAULT_CONVERSION_PATTERN = '%date %-5level %logger %message%newline';
- /** Default conversion pattern */
- const DEFAULT_CONVERSION_PATTERN = '%date %-5level %logger %message%newline';
+ /** Default conversion TTCC Pattern */
+ const TTCC_CONVERSION_PATTERN = '%d [%t] %p %c %x - %m%n';
- /** Default conversion TTCC Pattern */
- const TTCC_CONVERSION_PATTERN = '%d [%t] %p %c %x - %m%n';
+ /** The conversion pattern. */
+ protected $pattern = self::DEFAULT_CONVERSION_PATTERN;
- /** The conversion pattern. */
- protected $pattern = self::DEFAULT_CONVERSION_PATTERN;
+ /** Maps conversion keywords to the relevant converter (default implementation). */
+ protected static $defaultConverterMap = array(
+ 'c' => 'LoggerConverter',
+ 'lo' => 'LoggerConverter',
+ 'logger' => 'LoggerConverter',
- /** Maps conversion keywords to the relevant converter (default implementation). */
- protected static $defaultConverterMap = array(
- 'c' => 'LoggerConverter',
- 'lo' => 'LoggerConverter',
- 'logger' => 'LoggerConverter',
+ 'C' => 'ClassConverter',
+ 'class' => 'ClassConverter',
- 'C' => 'ClassConverter',
- 'class' => 'ClassConverter',
+ 'cookie' => 'CookieConverter',
- 'cookie' => 'CookieConverter',
+ 'd' => 'DateConverter',
+ 'date' => 'DateConverter',
- 'd' => 'DateConverter',
- 'date' => 'DateConverter',
+ 'e' => 'EnvironmentConverter',
+ 'env' => 'EnvironmentConverter',
- 'e' => 'EnvironmentConverter',
- 'env' => 'EnvironmentConverter',
+ 'ex' => 'ThrowableConverter',
+ 'exception' => 'ThrowableConverter',
+ 'throwable' => 'ThrowableConverter',
- 'ex' => 'ThrowableConverter',
- 'exception' => 'ThrowableConverter',
- 'throwable' => 'ThrowableConverter',
+ 'F' => 'FileConverter',
+ 'file' => 'FileConverter',
- 'F' => 'FileConverter',
- 'file' => 'FileConverter',
+ 'l' => 'LocationConverter',
+ 'location' => 'LocationConverter',
- 'l' => 'LocationConverter',
- 'location' => 'LocationConverter',
+ 'L' => 'LineConverter',
+ 'line' => 'LineConverter',
- 'L' => 'LineConverter',
- 'line' => 'LineConverter',
+ 'm' => 'MessageConverter',
+ 'msg' => 'MessageConverter',
+ 'message' => 'MessageConverter',
- 'm' => 'MessageConverter',
- 'msg' => 'MessageConverter',
- 'message' => 'MessageConverter',
+ 'M' => 'MethodConverter',
+ 'method' => 'MethodConverter',
- 'M' => 'MethodConverter',
- 'method' => 'MethodConverter',
+ 'n' => 'NewLineConverter',
+ 'newline' => 'NewLineConverter',
- 'n' => 'NewLineConverter',
- 'newline' => 'NewLineConverter',
+ 'p' => 'LevelConverter',
+ 'le' => 'LevelConverter',
+ 'level' => 'LevelConverter',
- 'p' => 'LevelConverter',
- 'le' => 'LevelConverter',
- 'level' => 'LevelConverter',
+ 'r' => 'RelativeConverter',
+ 'relative' => 'RelativeConverter',
- 'r' => 'RelativeConverter',
- 'relative' => 'RelativeConverter',
+ 'req' => 'RequestConverter',
+ 'request' => 'RequestConverter',
- 'req' => 'RequestConverter',
- 'request' => 'RequestConverter',
+ 's' => 'ServerConverter',
+ 'server' => 'ServerConverter',
- 's' => 'ServerConverter',
- 'server' => 'ServerConverter',
+ 'ses' => 'SessionConverter',
+ 'session' => 'SessionConverter',
- 'ses' => 'SessionConverter',
- 'session' => 'SessionConverter',
+ 'sid' => 'SessionIdConverter',
+ 'sessionid' => 'SessionIdConverter',
- 'sid' => 'SessionIdConverter',
- 'sessionid' => 'SessionIdConverter',
+ 't' => 'ProcessConverter',
+ 'pid' => 'ProcessConverter',
+ 'process' => 'ProcessConverter',
- 't' => 'ProcessConverter',
- 'pid' => 'ProcessConverter',
- 'process' => 'ProcessConverter',
+ 'x' => 'NdcConverter',
+ 'ndc' => 'NdcConverter',
- 'x' => 'NdcConverter',
- 'ndc' => 'NdcConverter',
+ 'X' => 'MdcConverter',
+ 'mdc' => 'MdcConverter',
+ );
- 'X' => 'MdcConverter',
- 'mdc' => 'MdcConverter',
- );
+ /** Maps conversion keywords to the relevant converter. */
+ protected $converterMap = array();
- /** Maps conversion keywords to the relevant converter. */
- protected $converterMap = array();
+ /**
+ * Head of a chain of Converters.
+ * @var AbstractConverter
+ */
+ private $head;
- /**
- * Head of a chain of Converters.
- * @var AbstractConverter
- */
- private $head;
+ /** Returns the default converter map. */
+ public static function getDefaultConverterMap()
+ {
+ return self::$defaultConverterMap;
+ }
- /** Returns the default converter map. */
- public static function getDefaultConverterMap() {
- return self::$defaultConverterMap;
- }
+ /** Constructor. Initializes the converter map. */
+ public function __construct()
+ {
+ $this->converterMap = self::$defaultConverterMap;
+ }
- /** Constructor. Initializes the converter map. */
- public function __construct() {
- $this->converterMap = self::$defaultConverterMap;
- }
+ /**
+ * Sets the conversionPattern option. This is the string which
+ * controls formatting and consists of a mix of literal content and
+ * conversion specifiers.
+ * @param array $conversionPattern
+ */
+ public function setConversionPattern($conversionPattern)
+ {
+ $this->pattern = $conversionPattern;
+ }
- /**
- * Sets the conversionPattern option. This is the string which
- * controls formatting and consists of a mix of literal content and
- * conversion specifiers.
- * @param array $conversionPattern
- */
- public function setConversionPattern($conversionPattern) {
- $this->pattern = $conversionPattern;
- }
+ /**
+ * Processes the conversion pattern and creates a corresponding chain of
+ * pattern converters which will be used to format logging events.
+ */
+ public function activateOptions()
+ {
+ if (!isset($this->pattern)) {
+ throw new LoggerException("Mandatory parameter 'conversionPattern' is not set.");
+ }
- /**
- * Processes the conversion pattern and creates a corresponding chain of
- * pattern converters which will be used to format logging events.
- */
- public function activateOptions() {
- if (!isset($this->pattern)) {
- throw new LoggerException("Mandatory parameter 'conversionPattern' is not set.");
- }
+ $parser = new PatternParser($this->pattern, $this->converterMap);
+ $this->head = $parser->parse();
+ }
- $parser = new PatternParser($this->pattern, $this->converterMap);
- $this->head = $parser->parse();
- }
+ /**
+ * Produces a formatted string as specified by the conversion pattern.
+ *
+ * @param LoggingEvent $event
+ * @return string
+ */
+ public function format(LoggingEvent $event)
+ {
+ $sbuf = '';
+ $converter = $this->head;
+ while ($converter !== null) {
+ $converter->format($sbuf, $event);
+ $converter = $converter->next;
+ }
- /**
- * Produces a formatted string as specified by the conversion pattern.
- *
- * @param LoggingEvent $event
- * @return string
- */
- public function format(LoggingEvent $event) {
- $sbuf = '';
- $converter = $this->head;
- while ($converter !== null) {
- $converter->format($sbuf, $event);
- $converter = $converter->next;
- }
- return $sbuf;
- }
-}
\ No newline at end of file
+ return $sbuf;
+ }
+}
diff --git a/src/Layouts/SerializedLayout.php b/src/Layouts/SerializedLayout.php
index 5273c3b..12fb53f 100644
--- a/src/Layouts/SerializedLayout.php
+++ b/src/Layouts/SerializedLayout.php
@@ -28,26 +28,30 @@
* be serialized (slow, defaults to false).
* @since 2.2
*/
-class SerializedLayout extends AbstractLayout {
+class SerializedLayout extends AbstractLayout
+{
+ /** Whether to include the event's location information (slow). */
+ protected $locationInfo = false;
- /** Whether to include the event's location information (slow). */
- protected $locationInfo = false;
+ /** Sets the location information flag. */
+ public function setLocationInfo($value)
+ {
+ $this->setBoolean('locationInfo', $value);
+ }
- /** Sets the location information flag. */
- public function setLocationInfo($value) {
- $this->setBoolean('locationInfo', $value);
- }
+ /** Returns the location information flag. */
+ public function getLocationInfo()
+ {
+ return $this->locationInfo;
+ }
- /** Returns the location information flag. */
- public function getLocationInfo() {
- return $this->locationInfo;
- }
+ public function format(LoggingEvent $event)
+ {
+ // If required, initialize the location data
+ if ($this->locationInfo) {
+ $event->getLocationInformation();
+ }
- public function format(LoggingEvent $event) {
- // If required, initialize the location data
- if($this->locationInfo) {
- $event->getLocationInformation();
- }
- return serialize($event) . PHP_EOL;
- }
+ return serialize($event) . PHP_EOL;
+ }
}
diff --git a/src/Layouts/SimpleLayout.php b/src/Layouts/SimpleLayout.php
index 16645f3..5f57e0a 100644
--- a/src/Layouts/SimpleLayout.php
+++ b/src/Layouts/SimpleLayout.php
@@ -26,19 +26,22 @@
* Returns the log statement in a format consisting of the
* <b>level</b>, followed by " - " and then the <b>message</b>.
*/
-class SimpleLayout extends AbstractLayout {
- /**
- * Returns the log statement in a format consisting of the
- * <b>level</b>, followed by " - " and then the
- * <b>message</b>. For example,
- * <samp> INFO - "A message" </samp>
- *
- * @param LoggingEvent $event
- * @return string
- */
- public function format(LoggingEvent $event) {
- $level = $event->getLevel();
- $message = $event->getRenderedMessage();
- return "$level - $message" . PHP_EOL;
- }
+class SimpleLayout extends AbstractLayout
+{
+ /**
+ * Returns the log statement in a format consisting of the
+ * <b>level</b>, followed by " - " and then the
+ * <b>message</b>. For example,
+ * <samp> INFO - "A message" </samp>
+ *
+ * @param LoggingEvent $event
+ * @return string
+ */
+ public function format(LoggingEvent $event)
+ {
+ $level = $event->getLevel();
+ $message = $event->getRenderedMessage();
+
+ return "$level - $message" . PHP_EOL;
+ }
}
diff --git a/src/Layouts/XmlLayout.php b/src/Layouts/XmlLayout.php
index 0ada386..f3b94b0 100644
--- a/src/Layouts/XmlLayout.php
+++ b/src/Layouts/XmlLayout.php
@@ -35,158 +35,167 @@
* a correct XML file.</p>
*
*/
-class XmlLayout extends AbstractLayout {
- const LOG4J_NS_PREFIX ='log4j';
- const LOG4J_NS = 'http://jakarta.apache.org/log4j/';
+class XmlLayout extends AbstractLayout
+{
+ const LOG4J_NS_PREFIX ='log4j';
+ const LOG4J_NS = 'http://jakarta.apache.org/log4j/';
- const LOG4PHP_NS_PREFIX = 'log4php';
- const LOG4PHP_NS = 'http://logging.apache.org/log4php/';
+ const LOG4PHP_NS_PREFIX = 'log4php';
+ const LOG4PHP_NS = 'http://logging.apache.org/log4php/';
- const CDATA_START = '<![CDATA[';
- const CDATA_END = ']]>';
- const CDATA_PSEUDO_END = ']]>';
- const CDATA_EMBEDDED_END = ']]>]]><![CDATA[';
+ const CDATA_START = '<![CDATA[';
+ const CDATA_END = ']]>';
+ const CDATA_PSEUDO_END = ']]>';
+ const CDATA_EMBEDDED_END = ']]>]]><![CDATA[';
- /**
- * If set to true then the file name and line number of the origin of the
- * log statement will be output.
- * @var boolean
- */
- protected $locationInfo = true;
+ /**
+ * If set to true then the file name and line number of the origin of the
+ * log statement will be output.
+ * @var boolean
+ */
+ protected $locationInfo = true;
- /**
- * If set to true, log4j namespace will be used instead of the log4php
- * namespace.
- * @var boolean
- */
- protected $log4jNamespace = false;
+ /**
+ * If set to true, log4j namespace will be used instead of the log4php
+ * namespace.
+ * @var boolean
+ */
+ protected $log4jNamespace = false;
- /** The namespace in use. */
- protected $namespace = self::LOG4PHP_NS;
+ /** The namespace in use. */
+ protected $namespace = self::LOG4PHP_NS;
- /** The namespace prefix in use */
- protected $namespacePrefix = self::LOG4PHP_NS_PREFIX;
+ /** The namespace prefix in use */
+ protected $namespacePrefix = self::LOG4PHP_NS_PREFIX;
- public function activateOptions() {
- if ($this->getLog4jNamespace()) {
- $this->namespace = self::LOG4J_NS;
- $this->namespacePrefix = self::LOG4J_NS_PREFIX;
- } else {
- $this->namespace = self::LOG4PHP_NS;
- $this->namespacePrefix = self::LOG4PHP_NS_PREFIX;
- }
- }
+ public function activateOptions()
+ {
+ if ($this->getLog4jNamespace()) {
+ $this->namespace = self::LOG4J_NS;
+ $this->namespacePrefix = self::LOG4J_NS_PREFIX;
+ } else {
+ $this->namespace = self::LOG4PHP_NS;
+ $this->namespacePrefix = self::LOG4PHP_NS_PREFIX;
+ }
+ }
- /**
- * @return string
- */
- public function getHeader() {
- return "<{$this->namespacePrefix}:eventSet ".
- "xmlns:{$this->namespacePrefix}=\"{$this->namespace}\" ".
- "version=\"0.3\" ".
- "includesLocationInfo=\"".($this->getLocationInfo() ? "true" : "false")."\"".
- ">" . PHP_EOL;
- }
+ /**
+ * @return string
+ */
+ public function getHeader()
+ {
+ return "<{$this->namespacePrefix}:eventSet ".
+ "xmlns:{$this->namespacePrefix}=\"{$this->namespace}\" ".
+ "version=\"0.3\" ".
+ "includesLocationInfo=\"".($this->getLocationInfo() ? "true" : "false")."\"".
+ ">" . PHP_EOL;
+ }
- /**
- * Formats a {@link LoggingEvent} in conformance with the log4php.dtd.
- *
- * @param LoggingEvent $event
- * @return string
- */
- public function format(LoggingEvent $event) {
- $ns = $this->namespacePrefix;
+ /**
+ * Formats a {@link LoggingEvent} in conformance with the log4php.dtd.
+ *
+ * @param LoggingEvent $event
+ * @return string
+ */
+ public function format(LoggingEvent $event)
+ {
+ $ns = $this->namespacePrefix;
- $loggerName = $event->getLoggerName();
- $timeStamp = number_format((float)($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $level = $event->getLevel()->toString();
+ $loggerName = $event->getLoggerName();
+ $timeStamp = number_format((float) ($event->getTimeStamp() * 1000), 0, '', '');
+ $thread = $event->getThreadName();
+ $level = $event->getLevel()->toString();
- $buf = "<$ns:event logger=\"{$loggerName}\" level=\"{$level}\" thread=\"{$thread}\" timestamp=\"{$timeStamp}\">".PHP_EOL;
- $buf .= "<$ns:message>";
- $buf .= $this->encodeCDATA($event->getRenderedMessage());
- $buf .= "</$ns:message>".PHP_EOL;
+ $buf = "<$ns:event logger=\"{$loggerName}\" level=\"{$level}\" thread=\"{$thread}\" timestamp=\"{$timeStamp}\">".PHP_EOL;
+ $buf .= "<$ns:message>";
+ $buf .= $this->encodeCDATA($event->getRenderedMessage());
+ $buf .= "</$ns:message>".PHP_EOL;
- $ndc = $event->getNDC();
- if(!empty($ndc)) {
- $buf .= "<$ns:NDC><![CDATA[";
- $buf .= $this->encodeCDATA($ndc);
- $buf .= "]]></$ns:NDC>".PHP_EOL;
- }
+ $ndc = $event->getNDC();
+ if (!empty($ndc)) {
+ $buf .= "<$ns:NDC><![CDATA[";
+ $buf .= $this->encodeCDATA($ndc);
+ $buf .= "]]></$ns:NDC>".PHP_EOL;
+ }
- $mdcMap = $event->getMDCMap();
- if (!empty($mdcMap)) {
- $buf .= "<$ns:properties>".PHP_EOL;
- foreach ($mdcMap as $name=>$value) {
- $buf .= "<$ns:data name=\"$name\" value=\"$value\" />".PHP_EOL;
- }
- $buf .= "</$ns:properties>".PHP_EOL;
- }
+ $mdcMap = $event->getMDCMap();
+ if (!empty($mdcMap)) {
+ $buf .= "<$ns:properties>".PHP_EOL;
+ foreach ($mdcMap as $name=>$value) {
+ $buf .= "<$ns:data name=\"$name\" value=\"$value\" />".PHP_EOL;
+ }
+ $buf .= "</$ns:properties>".PHP_EOL;
+ }
- if ($this->getLocationInfo()) {
- $locationInfo = $event->getLocationInformation();
- $buf .= "<$ns:locationInfo ".
- "class=\"" . $locationInfo->getClassName() . "\" ".
- "file=\"" . htmlentities($locationInfo->getFileName(), ENT_QUOTES) . "\" ".
- "line=\"" . $locationInfo->getLineNumber() . "\" ".
- "method=\"" . $locationInfo->getMethodName() . "\" ";
- $buf .= "/>".PHP_EOL;
- }
+ if ($this->getLocationInfo()) {
+ $locationInfo = $event->getLocationInformation();
+ $buf .= "<$ns:locationInfo ".
+ "class=\"" . $locationInfo->getClassName() . "\" ".
+ "file=\"" . htmlentities($locationInfo->getFileName(), ENT_QUOTES) . "\" ".
+ "line=\"" . $locationInfo->getLineNumber() . "\" ".
+ "method=\"" . $locationInfo->getMethodName() . "\" ";
+ $buf .= "/>".PHP_EOL;
+ }
- $buf .= "</$ns:event>".PHP_EOL;
+ $buf .= "</$ns:event>".PHP_EOL;
- return $buf;
- }
+ return $buf;
+ }
- /**
- * @return string
- */
- public function getFooter() {
- return "</{$this->namespacePrefix}:eventSet>" . PHP_EOL;
- }
+ /**
+ * @return string
+ */
+ public function getFooter()
+ {
+ return "</{$this->namespacePrefix}:eventSet>" . PHP_EOL;
+ }
+ /**
+ * Whether or not file name and line number will be included in the output.
+ * @return boolean
+ */
+ public function getLocationInfo()
+ {
+ return $this->locationInfo;
+ }
- /**
- * Whether or not file name and line number will be included in the output.
- * @return boolean
- */
- public function getLocationInfo() {
- return $this->locationInfo;
- }
+ /**
+ * The {@link $locationInfo} option takes a boolean value. By default,
+ * it is set to false which means there will be no location
+ * information output by this layout. If the the option is set to
+ * true, then the file name and line number of the statement at the
+ * origin of the log statement will be output.
+ */
+ public function setLocationInfo($flag)
+ {
+ $this->setBoolean('locationInfo', $flag);
+ }
- /**
- * The {@link $locationInfo} option takes a boolean value. By default,
- * it is set to false which means there will be no location
- * information output by this layout. If the the option is set to
- * true, then the file name and line number of the statement at the
- * origin of the log statement will be output.
- */
- public function setLocationInfo($flag) {
- $this->setBoolean('locationInfo', $flag);
- }
+ /**
+ * @return boolean
+ */
+ public function getLog4jNamespace()
+ {
+ return $this->log4jNamespace;
+ }
- /**
- * @return boolean
- */
- public function getLog4jNamespace() {
- return $this->log4jNamespace;
- }
+ /**
+ * @param boolean
+ */
+ public function setLog4jNamespace($flag)
+ {
+ $this->setBoolean('log4jNamespace', $flag);
+ }
- /**
- * @param boolean
- */
- public function setLog4jNamespace($flag) {
- $this->setBoolean('log4jNamespace', $flag);
- }
+ /**
+ * Encases a string in CDATA tags, and escapes any existing CDATA end
+ * tags already present in the string.
+ * @param string $string
+ */
+ private function encodeCDATA($string)
+ {
+ $string = str_replace(self::CDATA_END, self::CDATA_EMBEDDED_END, $string);
- /**
- * Encases a string in CDATA tags, and escapes any existing CDATA end
- * tags already present in the string.
- * @param string $string
- */
- private function encodeCDATA($string) {
- $string = str_replace(self::CDATA_END, self::CDATA_EMBEDDED_END, $string);
- return self::CDATA_START . $string . self::CDATA_END;
- }
+ return self::CDATA_START . $string . self::CDATA_END;
+ }
}
-
diff --git a/src/Level.php b/src/Level.php
index f17f0fc..78f8642 100644
--- a/src/Level.php
+++ b/src/Level.php
@@ -28,226 +28,250 @@
* level set.</p>
* @since 0.5
*/
-class Level {
+class Level
+{
+ const OFF = 2147483647;
+ const FATAL = 50000;
+ const ERROR = 40000;
+ const WARN = 30000;
+ const INFO = 20000;
+ const DEBUG = 10000;
+ const TRACE = 5000;
+ const ALL = -2147483647;
- const OFF = 2147483647;
- const FATAL = 50000;
- const ERROR = 40000;
- const WARN = 30000;
- const INFO = 20000;
- const DEBUG = 10000;
- const TRACE = 5000;
- const ALL = -2147483647;
+ /** Integer level value. */
+ private $level;
- /** Integer level value. */
- private $level;
+ /** Contains a list of instantiated levels. */
+ private static $levelMap;
- /** Contains a list of instantiated levels. */
- private static $levelMap;
+ /** String representation of the level. */
+ private $levelStr;
- /** String representation of the level. */
- private $levelStr;
+ /**
+ * Equivalent syslog level.
+ * @var integer
+ */
+ private $syslogEquivalent;
- /**
- * Equivalent syslog level.
- * @var integer
- */
- private $syslogEquivalent;
+ /**
+ * Constructor
+ *
+ * @param integer $level
+ * @param string $levelStr
+ * @param integer $syslogEquivalent
+ */
+ private function __construct($level, $levelStr, $syslogEquivalent)
+ {
+ $this->level = $level;
+ $this->levelStr = $levelStr;
+ $this->syslogEquivalent = $syslogEquivalent;
+ }
- /**
- * Constructor
- *
- * @param integer $level
- * @param string $levelStr
- * @param integer $syslogEquivalent
- */
- private function __construct($level, $levelStr, $syslogEquivalent) {
- $this->level = $level;
- $this->levelStr = $levelStr;
- $this->syslogEquivalent = $syslogEquivalent;
- }
+ /**
+ * Compares two logger levels.
+ *
+ * @param Level $other
+ * @return boolean
+ */
+ public function equals($other)
+ {
+ if ($other instanceof Level) {
+ if ($this->level == $other->level) {
+ return true;
+ }
+ } else {
+ return false;
+ }
+ }
- /**
- * Compares two logger levels.
- *
- * @param Level $other
- * @return boolean
- */
- public function equals($other) {
- if($other instanceof Level) {
- if($this->level == $other->level) {
- return true;
- }
- } else {
- return false;
- }
- }
+ /**
+ * Returns an Off Level
+ * @return Level
+ */
+ public static function getLevelOff()
+ {
+ if (!isset(self::$levelMap[Level::OFF])) {
+ self::$levelMap[Level::OFF] = new Level(Level::OFF, 'OFF', LOG_ALERT);
+ }
- /**
- * Returns an Off Level
- * @return Level
- */
- public static function getLevelOff() {
- if(!isset(self::$levelMap[Level::OFF])) {
- self::$levelMap[Level::OFF] = new Level(Level::OFF, 'OFF', LOG_ALERT);
- }
- return self::$levelMap[Level::OFF];
- }
+ return self::$levelMap[Level::OFF];
+ }
- /**
- * Returns a Fatal Level
- * @return Level
- */
- public static function getLevelFatal() {
- if(!isset(self::$levelMap[Level::FATAL])) {
- self::$levelMap[Level::FATAL] = new Level(Level::FATAL, 'FATAL', LOG_ALERT);
- }
- return self::$levelMap[Level::FATAL];
- }
+ /**
+ * Returns a Fatal Level
+ * @return Level
+ */
+ public static function getLevelFatal()
+ {
+ if (!isset(self::$levelMap[Level::FATAL])) {
+ self::$levelMap[Level::FATAL] = new Level(Level::FATAL, 'FATAL', LOG_ALERT);
+ }
- /**
- * Returns an Error Level
- * @return Level
- */
- public static function getLevelError() {
- if(!isset(self::$levelMap[Level::ERROR])) {
- self::$levelMap[Level::ERROR] = new Level(Level::ERROR, 'ERROR', LOG_ERR);
- }
- return self::$levelMap[Level::ERROR];
- }
+ return self::$levelMap[Level::FATAL];
+ }
- /**
- * Returns a Warn Level
- * @return Level
- */
- public static function getLevelWarn() {
- if(!isset(self::$levelMap[Level::WARN])) {
- self::$levelMap[Level::WARN] = new Level(Level::WARN, 'WARN', LOG_WARNING);
- }
- return self::$levelMap[Level::WARN];
- }
+ /**
+ * Returns an Error Level
+ * @return Level
+ */
+ public static function getLevelError()
+ {
+ if (!isset(self::$levelMap[Level::ERROR])) {
+ self::$levelMap[Level::ERROR] = new Level(Level::ERROR, 'ERROR', LOG_ERR);
+ }
- /**
- * Returns an Info Level
- * @return Level
- */
- public static function getLevelInfo() {
- if(!isset(self::$levelMap[Level::INFO])) {
- self::$levelMap[Level::INFO] = new Level(Level::INFO, 'INFO', LOG_INFO);
- }
- return self::$levelMap[Level::INFO];
- }
+ return self::$levelMap[Level::ERROR];
+ }
- /**
- * Returns a Debug Level
- * @return Level
- */
- public static function getLevelDebug() {
- if(!isset(self::$levelMap[Level::DEBUG])) {
- self::$levelMap[Level::DEBUG] = new Level(Level::DEBUG, 'DEBUG', LOG_DEBUG);
- }
- return self::$levelMap[Level::DEBUG];
- }
+ /**
+ * Returns a Warn Level
+ * @return Level
+ */
+ public static function getLevelWarn()
+ {
+ if (!isset(self::$levelMap[Level::WARN])) {
+ self::$levelMap[Level::WARN] = new Level(Level::WARN, 'WARN', LOG_WARNING);
+ }
- /**
- * Returns a Trace Level
- * @return Level
- */
- public static function getLevelTrace() {
- if(!isset(self::$levelMap[Level::TRACE])) {
- self::$levelMap[Level::TRACE] = new Level(Level::TRACE, 'TRACE', LOG_DEBUG);
- }
- return self::$levelMap[Level::TRACE];
- }
+ return self::$levelMap[Level::WARN];
+ }
- /**
- * Returns an All Level
- * @return Level
- */
- public static function getLevelAll() {
- if(!isset(self::$levelMap[Level::ALL])) {
- self::$levelMap[Level::ALL] = new Level(Level::ALL, 'ALL', LOG_DEBUG);
- }
- return self::$levelMap[Level::ALL];
- }
+ /**
+ * Returns an Info Level
+ * @return Level
+ */
+ public static function getLevelInfo()
+ {
+ if (!isset(self::$levelMap[Level::INFO])) {
+ self::$levelMap[Level::INFO] = new Level(Level::INFO, 'INFO', LOG_INFO);
+ }
- /**
- * Return the syslog equivalent of this level as an integer.
- * @return integer
- */
- public function getSyslogEquivalent() {
- return $this->syslogEquivalent;
- }
+ return self::$levelMap[Level::INFO];
+ }
- /**
- * Returns <i>true</i> if this level has a higher or equal
- * level than the level passed as argument, <i>false</i>
- * otherwise.
- *
- * @param Level $other
- * @return boolean
- */
- public function isGreaterOrEqual($other) {
- return $this->level >= $other->level;
- }
+ /**
+ * Returns a Debug Level
+ * @return Level
+ */
+ public static function getLevelDebug()
+ {
+ if (!isset(self::$levelMap[Level::DEBUG])) {
+ self::$levelMap[Level::DEBUG] = new Level(Level::DEBUG, 'DEBUG', LOG_DEBUG);
+ }
- /**
- * Returns the string representation of this level.
- * @return string
- */
- public function toString() {
- return $this->levelStr;
- }
+ return self::$levelMap[Level::DEBUG];
+ }
- /**
- * Returns the string representation of this level.
- * @return string
- */
- public function __toString() {
- return $this->toString();
- }
+ /**
+ * Returns a Trace Level
+ * @return Level
+ */
+ public static function getLevelTrace()
+ {
+ if (!isset(self::$levelMap[Level::TRACE])) {
+ self::$levelMap[Level::TRACE] = new Level(Level::TRACE, 'TRACE', LOG_DEBUG);
+ }
- /**
- * Returns the integer representation of this level.
- * @return integer
- */
- public function toInt() {
- return $this->level;
- }
+ return self::$levelMap[Level::TRACE];
+ }
- /**
- * Convert the input argument to a level. If the conversion fails, then
- * this method returns the provided default level.
- *
- * @param mixed $arg The value to convert to level.
- * @param Level $default Value to return if conversion is not possible.
- * @return Level
- */
- public static function toLevel($arg, $defaultLevel = null) {
- if(is_int($arg)) {
- switch($arg) {
- case self::ALL: return self::getLevelAll();
- case self::TRACE: return self::getLevelTrace();
- case self::DEBUG: return self::getLevelDebug();
- case self::INFO: return self::getLevelInfo();
- case self::WARN: return self::getLevelWarn();
- case self::ERROR: return self::getLevelError();
- case self::FATAL: return self::getLevelFatal();
- case self::OFF: return self::getLevelOff();
- default: return $defaultLevel;
- }
- } else {
- switch(strtoupper($arg)) {
- case 'ALL': return self::getLevelAll();
- case 'TRACE': return self::getLevelTrace();
- case 'DEBUG': return self::getLevelDebug();
- case 'INFO': return self::getLevelInfo();
- case 'WARN': return self::getLevelWarn();
- case 'ERROR': return self::getLevelError();
- case 'FATAL': return self::getLevelFatal();
- case 'OFF': return self::getLevelOff();
- default: return $defaultLevel;
- }
- }
- }
+ /**
+ * Returns an All Level
+ * @return Level
+ */
+ public static function getLevelAll()
+ {
+ if (!isset(self::$levelMap[Level::ALL])) {
+ self::$levelMap[Level::ALL] = new Level(Level::ALL, 'ALL', LOG_DEBUG);
+ }
+
+ return self::$levelMap[Level::ALL];
+ }
+
+ /**
+ * Return the syslog equivalent of this level as an integer.
+ * @return integer
+ */
+ public function getSyslogEquivalent()
+ {
+ return $this->syslogEquivalent;
+ }
+
+ /**
+ * Returns <i>true</i> if this level has a higher or equal
+ * level than the level passed as argument, <i>false</i>
+ * otherwise.
+ *
+ * @param Level $other
+ * @return boolean
+ */
+ public function isGreaterOrEqual($other)
+ {
+ return $this->level >= $other->level;
+ }
+
+ /**
+ * Returns the string representation of this level.
+ * @return string
+ */
+ public function toString()
+ {
+ return $this->levelStr;
+ }
+
+ /**
+ * Returns the string representation of this level.
+ * @return string
+ */
+ public function __toString()
+ {
+ return $this->toString();
+ }
+
+ /**
+ * Returns the integer representation of this level.
+ * @return integer
+ */
+ public function toInt()
+ {
+ return $this->level;
+ }
+
+ /**
+ * Convert the input argument to a level. If the conversion fails, then
+ * this method returns the provided default level.
+ *
+ * @param mixed $arg The value to convert to level.
+ * @param Level $default Value to return if conversion is not possible.
+ * @return Level
+ */
+ public static function toLevel($arg, $defaultLevel = null)
+ {
+ if (is_int($arg)) {
+ switch ($arg) {
+ case self::ALL: return self::getLevelAll();
+ case self::TRACE: return self::getLevelTrace();
+ case self::DEBUG: return self::getLevelDebug();
+ case self::INFO: return self::getLevelInfo();
+ case self::WARN: return self::getLevelWarn();
+ case self::ERROR: return self::getLevelError();
+ case self::FATAL: return self::getLevelFatal();
+ case self::OFF: return self::getLevelOff();
+ default: return $defaultLevel;
+ }
+ } else {
+ switch (strtoupper($arg)) {
+ case 'ALL': return self::getLevelAll();
+ case 'TRACE': return self::getLevelTrace();
+ case 'DEBUG': return self::getLevelDebug();
+ case 'INFO': return self::getLevelInfo();
+ case 'WARN': return self::getLevelWarn();
+ case 'ERROR': return self::getLevelError();
+ case 'FATAL': return self::getLevelFatal();
+ case 'OFF': return self::getLevelOff();
+ default: return $defaultLevel;
+ }
+ }
+ }
}
diff --git a/src/LocationInfo.php b/src/LocationInfo.php
index 4615962..bbb9fd9 100644
--- a/src/LocationInfo.php
+++ b/src/LocationInfo.php
@@ -22,79 +22,85 @@
* The internal representation of caller location information.
* @since 0.3
*/
-class LocationInfo {
+class LocationInfo
+{
+ /** The value to return when the location information is not available. */
+ const LOCATION_INFO_NA = 'NA';
- /** The value to return when the location information is not available. */
- const LOCATION_INFO_NA = 'NA';
+ /**
+ * Caller line number.
+ * @var integer
+ */
+ protected $lineNumber;
- /**
- * Caller line number.
- * @var integer
- */
- protected $lineNumber;
+ /**
+ * Caller file name.
+ * @var string
+ */
+ protected $fileName;
- /**
- * Caller file name.
- * @var string
- */
- protected $fileName;
+ /**
+ * Caller class name.
+ * @var string
+ */
+ protected $className;
- /**
- * Caller class name.
- * @var string
- */
- protected $className;
+ /**
+ * Caller method name.
+ * @var string
+ */
+ protected $methodName;
- /**
- * Caller method name.
- * @var string
- */
- protected $methodName;
+ /**
+ * All the information combined.
+ * @var string
+ */
+ protected $fullInfo;
- /**
- * All the information combined.
- * @var string
- */
- protected $fullInfo;
+ /**
+ * Instantiate location information based on a {@link PHP_MANUAL#debug_backtrace}.
+ *
+ * @param array $trace
+ * @param mixed $caller
+ */
+ public function __construct($trace, $fqcn = null)
+ {
+ $this->lineNumber = isset($trace['line']) ? $trace['line'] : null;
+ $this->fileName = isset($trace['file']) ? $trace['file'] : null;
+ $this->className = isset($trace['class']) ? $trace['class'] : null;
+ $this->methodName = isset($trace['function']) ? $trace['function'] : null;
+ $this->fullInfo = $this->getClassName() . '.' . $this->getMethodName() .
+ '(' . $this->getFileName() . ':' . $this->getLineNumber() . ')';
+ }
- /**
- * Instantiate location information based on a {@link PHP_MANUAL#debug_backtrace}.
- *
- * @param array $trace
- * @param mixed $caller
- */
- public function __construct($trace, $fqcn = null) {
- $this->lineNumber = isset($trace['line']) ? $trace['line'] : null;
- $this->fileName = isset($trace['file']) ? $trace['file'] : null;
- $this->className = isset($trace['class']) ? $trace['class'] : null;
- $this->methodName = isset($trace['function']) ? $trace['function'] : null;
- $this->fullInfo = $this->getClassName() . '.' . $this->getMethodName() .
- '(' . $this->getFileName() . ':' . $this->getLineNumber() . ')';
- }
+ /** Returns the caller class name. */
+ public function getClassName()
+ {
+ return ($this->className === null) ? self::LOCATION_INFO_NA : $this->className;
+ }
- /** Returns the caller class name. */
- public function getClassName() {
- return ($this->className === null) ? self::LOCATION_INFO_NA : $this->className;
- }
+ /** Returns the caller file name. */
+ public function getFileName()
+ {
+ return ($this->fileName === null) ? self::LOCATION_INFO_NA : $this->fileName;
+ }
- /** Returns the caller file name. */
- public function getFileName() {
- return ($this->fileName === null) ? self::LOCATION_INFO_NA : $this->fileName;
- }
+ /** Returns the caller line number. */
+ public function getLineNumber()
+ {
+ return ($this->lineNumber === null) ? self::LOCATION_INFO_NA : $this->lineNumber;
+ }
- /** Returns the caller line number. */
- public function getLineNumber() {
- return ($this->lineNumber === null) ? self::LOCATION_INFO_NA : $this->lineNumber;
- }
+ /** Returns the caller method name. */
+ public function getMethodName()
+ {
+ return ($this->methodName === null) ? self::LOCATION_INFO_NA : $this->methodName;
+ }
- /** Returns the caller method name. */
- public function getMethodName() {
- return ($this->methodName === null) ? self::LOCATION_INFO_NA : $this->methodName;
- }
-
- /** Returns the full information of the caller. */
- public function getFullInfo() {
- return ($this->fullInfo === null) ? self::LOCATION_INFO_NA : $this->fullInfo;
- }
+ /** Returns the full information of the caller. */
+ public function getFullInfo()
+ {
+ return ($this->fullInfo === null) ? self::LOCATION_INFO_NA : $this->fullInfo;
+ }
}
diff --git a/src/Logger.php b/src/Logger.php
index 27eca1c..055cd34 100644
--- a/src/Logger.php
+++ b/src/Logger.php
@@ -35,558 +35,609 @@
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php
*/
-class Logger {
+class Logger
+{
+ /**
+ * Logger additivity. If set to true then child loggers will inherit
+ * the appenders of their ancestors by default.
+ * @var boolean
+ */
+ private $additive = true;
- /**
- * Logger additivity. If set to true then child loggers will inherit
- * the appenders of their ancestors by default.
- * @var boolean
- */
- private $additive = true;
+ /**
+ * The Logger's fully qualified class name.
+ * TODO: Determine if this is useful.
+ */
+ private $fqcn = 'Logger';
- /**
- * The Logger's fully qualified class name.
- * TODO: Determine if this is useful.
- */
- private $fqcn = 'Logger';
+ /** The assigned Logger level. */
+ private $level;
- /** The assigned Logger level. */
- private $level;
+ /** The name of this Logger instance. */
+ private $name;
- /** The name of this Logger instance. */
- private $name;
+ /** The parent logger. Set to null if this is the root logger. */
+ private $parent;
- /** The parent logger. Set to null if this is the root logger. */
- private $parent;
+ /** A collection of appenders linked to this logger. */
+ private $appenders = array();
- /** A collection of appenders linked to this logger. */
- private $appenders = array();
+ /**
+ * Constructor.
+ * @param string $name Name of the logger.
+ */
+ public function __construct($name)
+ {
+ $this->name = $name;
+ }
- /**
- * Constructor.
- * @param string $name Name of the logger.
- */
- public function __construct($name) {
- $this->name = $name;
- }
+ /**
+ * Returns the logger name.
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
- /**
- * Returns the logger name.
- * @return string
- */
- public function getName() {
- return $this->name;
- }
+ /**
+ * Returns the parent Logger. Can be null if this is the root logger.
+ * @return Logger
+ */
+ public function getParent()
+ {
+ return $this->parent;
+ }
- /**
- * Returns the parent Logger. Can be null if this is the root logger.
- * @return Logger
- */
- public function getParent() {
- return $this->parent;
- }
+ // ******************************************
+ // *** Logging methods ***
+ // ******************************************
- // ******************************************
- // *** Logging methods ***
- // ******************************************
+ /**
+ * Log a message object with the TRACE level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function trace($message, $throwable = null)
+ {
+ $this->log(Level::getLevelTrace(), $message, $throwable);
+ }
- /**
- * Log a message object with the TRACE level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function trace($message, $throwable = null) {
- $this->log(Level::getLevelTrace(), $message, $throwable);
- }
+ /**
+ * Log a message object with the DEBUG level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function debug($message, $throwable = null)
+ {
+ $this->log(Level::getLevelDebug(), $message, $throwable);
+ }
- /**
- * Log a message object with the DEBUG level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function debug($message, $throwable = null) {
- $this->log(Level::getLevelDebug(), $message, $throwable);
- }
+ /**
+ * Log a message object with the INFO Level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function info($message, $throwable = null)
+ {
+ $this->log(Level::getLevelInfo(), $message, $throwable);
+ }
- /**
- * Log a message object with the INFO Level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function info($message, $throwable = null) {
- $this->log(Level::getLevelInfo(), $message, $throwable);
- }
+ /**
+ * Log a message with the WARN level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function warn($message, $throwable = null)
+ {
+ $this->log(Level::getLevelWarn(), $message, $throwable);
+ }
- /**
- * Log a message with the WARN level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function warn($message, $throwable = null) {
- $this->log(Level::getLevelWarn(), $message, $throwable);
- }
+ /**
+ * Log a message object with the ERROR level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function error($message, $throwable = null)
+ {
+ $this->log(Level::getLevelError(), $message, $throwable);
+ }
- /**
- * Log a message object with the ERROR level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function error($message, $throwable = null) {
- $this->log(Level::getLevelError(), $message, $throwable);
- }
+ /**
+ * Log a message object with the FATAL level.
+ *
+ * @param mixed $message message
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function fatal($message, $throwable = null)
+ {
+ $this->log(Level::getLevelFatal(), $message, $throwable);
+ }
- /**
- * Log a message object with the FATAL level.
- *
- * @param mixed $message message
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function fatal($message, $throwable = null) {
- $this->log(Level::getLevelFatal(), $message, $throwable);
- }
+ /**
+ * Log a message using the provided logging level.
+ *
+ * @param Level $level The logging level.
+ * @param mixed $message Message to log.
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ */
+ public function log(Level $level, $message, $throwable = null)
+ {
+ if ($this->isEnabledFor($level)) {
+ $event = new LoggingEvent($this->fqcn, $this, $level, $message, null, $throwable);
+ $this->callAppenders($event);
+ }
- /**
- * Log a message using the provided logging level.
- *
- * @param Level $level The logging level.
- * @param mixed $message Message to log.
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- */
- public function log(Level $level, $message, $throwable = null) {
- if($this->isEnabledFor($level)) {
- $event = new LoggingEvent($this->fqcn, $this, $level, $message, null, $throwable);
- $this->callAppenders($event);
- }
+ // Forward the event upstream if additivity is turned on
+ if (isset($this->parent) && $this->getAdditivity()) {
- // Forward the event upstream if additivity is turned on
- if(isset($this->parent) && $this->getAdditivity()) {
+ // Use the event if already created
+ if (isset($event)) {
+ $this->parent->logEvent($event);
+ } else {
+ $this->parent->log($level, $message, $throwable);
+ }
+ }
+ }
- // Use the event if already created
- if (isset($event)) {
- $this->parent->logEvent($event);
- } else {
- $this->parent->log($level, $message, $throwable);
- }
- }
- }
+ /**
+ * Logs an already prepared logging event object.
+ * @param LoggingEvent $event
+ */
+ public function logEvent(LoggingEvent $event)
+ {
+ if ($this->isEnabledFor($event->getLevel())) {
+ $this->callAppenders($event);
+ }
- /**
- * Logs an already prepared logging event object.
- * @param LoggingEvent $event
- */
- public function logEvent(LoggingEvent $event) {
- if($this->isEnabledFor($event->getLevel())) {
- $this->callAppenders($event);
- }
+ // Forward the event upstream if additivity is turned on
+ if (isset($this->parent) && $this->getAdditivity()) {
+ $this->parent->logEvent($event);
+ }
+ }
- // Forward the event upstream if additivity is turned on
- if(isset($this->parent) && $this->getAdditivity()) {
- $this->parent->logEvent($event);
- }
- }
+ /**
+ * If assertion parameter evaluates as false, then logs the message
+ * using the ERROR level.
+ *
+ * @param bool $assertion
+ * @param string $msg message to log
+ */
+ public function assertLog($assertion = true, $msg = '')
+ {
+ if ($assertion == false) {
+ $this->error($msg);
+ }
+ }
- /**
- * If assertion parameter evaluates as false, then logs the message
- * using the ERROR level.
- *
- * @param bool $assertion
- * @param string $msg message to log
- */
- public function assertLog($assertion = true, $msg = '') {
- if($assertion == false) {
- $this->error($msg);
- }
- }
+ /**
+ * This method creates a new logging event and logs the event without
+ * further checks.
+ *
+ * It should not be called directly. Use {@link trace()}, {@link debug()},
+ * {@link info()}, {@link warn()}, {@link error()} and {@link fatal()}
+ * wrappers.
+ *
+ * @param string $fqcn Fully qualified class name of the Logger
+ * @param Exception $throwable Optional throwable information to include
+ * in the logging event.
+ * @param Level $level log level
+ * @param mixed $message message to log
+ */
+ public function forcedLog($fqcn, $throwable, Level $level, $message)
+ {
+ $event = new LoggingEvent($fqcn, $this, $level, $message, null, $throwable);
+ $this->callAppenders($event);
- /**
- * This method creates a new logging event and logs the event without
- * further checks.
- *
- * It should not be called directly. Use {@link trace()}, {@link debug()},
- * {@link info()}, {@link warn()}, {@link error()} and {@link fatal()}
- * wrappers.
- *
- * @param string $fqcn Fully qualified class name of the Logger
- * @param Exception $throwable Optional throwable information to include
- * in the logging event.
- * @param Level $level log level
- * @param mixed $message message to log
- */
- public function forcedLog($fqcn, $throwable, Level $level, $message) {
- $event = new LoggingEvent($fqcn, $this, $level, $message, null, $throwable);
- $this->callAppenders($event);
+ // Forward the event upstream if additivity is turned on
+ if (isset($this->parent) && $this->getAdditivity()) {
+ $this->parent->logEvent($event);
+ }
+ }
- // Forward the event upstream if additivity is turned on
- if(isset($this->parent) && $this->getAdditivity()) {
- $this->parent->logEvent($event);
- }
- }
+ /**
+ * Forwards the given logging event to all linked appenders.
+ * @param LoggingEvent $event
+ */
+ public function callAppenders($event)
+ {
+ foreach ($this->appenders as $appender) {
+ $appender->doAppend($event);
+ }
+ }
- /**
- * Forwards the given logging event to all linked appenders.
- * @param LoggingEvent $event
- */
- public function callAppenders($event) {
- foreach($this->appenders as $appender) {
- $appender->doAppend($event);
- }
- }
+ // ******************************************
+ // *** Checker methods ***
+ // ******************************************
- // ******************************************
- // *** Checker methods ***
- // ******************************************
+ /**
+ * Check whether this Logger is enabled for a given Level passed as parameter.
+ *
+ * @param Level level
+ * @return boolean
+ */
+ public function isEnabledFor(Level $level)
+ {
+ return $level->isGreaterOrEqual($this->getEffectiveLevel());
+ }
- /**
- * Check whether this Logger is enabled for a given Level passed as parameter.
- *
- * @param Level level
- * @return boolean
- */
- public function isEnabledFor(Level $level) {
- return $level->isGreaterOrEqual($this->getEffectiveLevel());
- }
+ /**
+ * Check whether this Logger is enabled for the TRACE Level.
+ * @return boolean
+ */
+ public function isTraceEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelTrace());
+ }
- /**
- * Check whether this Logger is enabled for the TRACE Level.
- * @return boolean
- */
- public function isTraceEnabled() {
- return $this->isEnabledFor(Level::getLevelTrace());
- }
+ /**
+ * Check whether this Logger is enabled for the DEBUG Level.
+ * @return boolean
+ */
+ public function isDebugEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelDebug());
+ }
- /**
- * Check whether this Logger is enabled for the DEBUG Level.
- * @return boolean
- */
- public function isDebugEnabled() {
- return $this->isEnabledFor(Level::getLevelDebug());
- }
+ /**
+ * Check whether this Logger is enabled for the INFO Level.
+ * @return boolean
+ */
+ public function isInfoEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelInfo());
+ }
- /**
- * Check whether this Logger is enabled for the INFO Level.
- * @return boolean
- */
- public function isInfoEnabled() {
- return $this->isEnabledFor(Level::getLevelInfo());
- }
+ /**
+ * Check whether this Logger is enabled for the WARN Level.
+ * @return boolean
+ */
+ public function isWarnEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelWarn());
+ }
- /**
- * Check whether this Logger is enabled for the WARN Level.
- * @return boolean
- */
- public function isWarnEnabled() {
- return $this->isEnabledFor(Level::getLevelWarn());
- }
+ /**
+ * Check whether this Logger is enabled for the ERROR Level.
+ * @return boolean
+ */
+ public function isErrorEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelError());
+ }
+
+ /**
+ * Check whether this Logger is enabled for the FATAL Level.
+ * @return boolean
+ */
+ public function isFatalEnabled()
+ {
+ return $this->isEnabledFor(Level::getLevelFatal());
+ }
+
+ // ******************************************
+ // *** Configuration methods ***
+ // ******************************************
+
+ /**
+ * Adds a new appender to the Logger.
+ * @param Appender $appender The appender to add.
+ */
+ public function addAppender($appender)
+ {
+ $appenderName = $appender->getName();
+ $this->appenders[$appenderName] = $appender;
+ }
+
+ /** Removes all appenders from the Logger. */
+ public function removeAllAppenders()
+ {
+ foreach ($this->appenders as $name => $appender) {
+ $this->removeAppender($name);
+ }
+ }
+
+ /**
+ * Remove the appender passed as parameter form the Logger.
+ * @param mixed $appender an appender name or a {@link Appender} instance.
+ */
+ public function removeAppender($appender)
+ {
+ if ($appender instanceof Appender) {
+ $appender->close();
+ unset($this->appenders[$appender->getName()]);
+ } elseif (is_string($appender) and isset($this->appenders[$appender])) {
+ $this->appenders[$appender]->close();
+ unset($this->appenders[$appender]);
+ }
+ }
+
+ /**
+ * Returns the appenders linked to this logger as an array.
+ * @return array collection of appender names
+ */
+ public function getAllAppenders()
+ {
+ return $this->appenders;
+ }
- /**
- * Check whether this Logger is enabled for the ERROR Level.
- * @return boolean
- */
- public function isErrorEnabled() {
- return $this->isEnabledFor(Level::getLevelError());
- }
+ /**
+ * Returns a linked appender by name.
+ * @return Appender
+ */
+ public function getAppender($name)
+ {
+ return $this->appenders[$name];
+ }
- /**
- * Check whether this Logger is enabled for the FATAL Level.
- * @return boolean
- */
- public function isFatalEnabled() {
- return $this->isEnabledFor(Level::getLevelFatal());
- }
+ /**
+ * Sets the additivity flag.
+ * @param boolean $additive
+ */
+ public function setAdditivity($additive)
+ {
+ $this->additive = (bool) $additive;
+ }
- // ******************************************
- // *** Configuration methods ***
- // ******************************************
+ /**
+ * Returns the additivity flag.
+ * @return boolean
+ */
+ public function getAdditivity()
+ {
+ return $this->additive;
+ }
- /**
- * Adds a new appender to the Logger.
- * @param Appender $appender The appender to add.
- */
- public function addAppender($appender) {
- $appenderName = $appender->getName();
- $this->appenders[$appenderName] = $appender;
- }
+ /**
+ * Starting from this Logger, search the Logger hierarchy for a non-null level and return it.
+ * @see Level
+ * @return Level or null
+ */
+ public function getEffectiveLevel()
+ {
+ for ($logger = $this; $logger !== null; $logger = $logger->getParent()) {
+ if ($logger->getLevel() !== null) {
+ return $logger->getLevel();
+ }
+ }
+ }
- /** Removes all appenders from the Logger. */
- public function removeAllAppenders() {
- foreach($this->appenders as $name => $appender) {
- $this->removeAppender($name);
- }
- }
+ /**
+ * Get the assigned Logger level.
+ * @return Level The assigned level or null if none is assigned.
+ */
+ public function getLevel()
+ {
+ return $this->level;
+ }
- /**
- * Remove the appender passed as parameter form the Logger.
- * @param mixed $appender an appender name or a {@link Appender} instance.
- */
- public function removeAppender($appender) {
- if($appender instanceof Appender) {
- $appender->close();
- unset($this->appenders[$appender->getName()]);
- } else if (is_string($appender) and isset($this->appenders[$appender])) {
- $this->appenders[$appender]->close();
- unset($this->appenders[$appender]);
- }
- }
+ /**
+ * Set the Logger level.
+ *
+ * Use Level::getLevelXXX() methods to get a Level object, e.g.
+ * <code>$logger->setLevel(Level::getLevelInfo());</code>
+ *
+ * @param Level $level The level to set, or NULL to clear the logger level.
+ */
+ public function setLevel(Level $level = null)
+ {
+ $this->level = $level;
+ }
- /**
- * Returns the appenders linked to this logger as an array.
- * @return array collection of appender names
- */
- public function getAllAppenders() {
- return $this->appenders;
- }
+ /**
+ * Checks whether an appender is attached to this logger instance.
+ *
+ * @param Appender $appender
+ * @return boolean
+ */
+ public function isAttached(Appender $appender)
+ {
+ return isset($this->appenders[$appender->getName()]);
+ }
- /**
- * Returns a linked appender by name.
- * @return Appender
- */
- public function getAppender($name) {
- return $this->appenders[$name];
- }
+ /**
+ * Sets the parent logger.
+ * @param Logger $logger
+ */
+ public function setParent(Logger $logger)
+ {
+ $this->parent = $logger;
+ }
- /**
- * Sets the additivity flag.
- * @param boolean $additive
- */
- public function setAdditivity($additive) {
- $this->additive = (bool)$additive;
- }
+ // ******************************************
+ // *** Static methods and properties ***
+ // ******************************************
- /**
- * Returns the additivity flag.
- * @return boolean
- */
- public function getAdditivity() {
- return $this->additive;
- }
+ /** The logger hierarchy used by log4php. */
+ private static $hierarchy;
- /**
- * Starting from this Logger, search the Logger hierarchy for a non-null level and return it.
- * @see Level
- * @return Level or null
- */
- public function getEffectiveLevel() {
- for($logger = $this; $logger !== null; $logger = $logger->getParent()) {
- if($logger->getLevel() !== null) {
- return $logger->getLevel();
- }
- }
- }
+ /** Inidicates if log4php has been initialized */
+ private static $initialized = false;
- /**
- * Get the assigned Logger level.
- * @return Level The assigned level or null if none is assigned.
- */
- public function getLevel() {
- return $this->level;
- }
+ /**
+ * Returns the hierarchy used by this Logger.
+ *
+ * Caution: do not use this hierarchy unless you have called initialize().
+ * To get Loggers, use the Logger::getLogger and Logger::getRootLogger
+ * methods instead of operating on on the hierarchy directly.
+ *
+ * @return Hierarchy
+ */
+ public static function getHierarchy()
+ {
+ if (!isset(self::$hierarchy)) {
+ self::$hierarchy = new Hierarchy(new RootLogger());
+ }
- /**
- * Set the Logger level.
- *
- * Use Level::getLevelXXX() methods to get a Level object, e.g.
- * <code>$logger->setLevel(Level::getLevelInfo());</code>
- *
- * @param Level $level The level to set, or NULL to clear the logger level.
- */
- public function setLevel(Level $level = null) {
- $this->level = $level;
- }
+ return self::$hierarchy;
+ }
- /**
- * Checks whether an appender is attached to this logger instance.
- *
- * @param Appender $appender
- * @return boolean
- */
- public function isAttached(Appender $appender) {
- return isset($this->appenders[$appender->getName()]);
- }
+ /**
+ * Returns a Logger by name. If it does not exist, it will be created.
+ *
+ * @param string $name The logger name
+ * @return Logger
+ */
+ public static function getLogger($name)
+ {
+ if (!self::isInitialized()) {
+ self::configure();
+ }
- /**
- * Sets the parent logger.
- * @param Logger $logger
- */
- public function setParent(Logger $logger) {
- $this->parent = $logger;
- }
+ return self::getHierarchy()->getLogger($name);
+ }
- // ******************************************
- // *** Static methods and properties ***
- // ******************************************
+ /**
+ * Returns the Root Logger.
+ * @return RootLogger
+ */
+ public static function getRootLogger()
+ {
+ if (!self::isInitialized()) {
+ self::configure();
+ }
- /** The logger hierarchy used by log4php. */
- private static $hierarchy;
+ return self::getHierarchy()->getRootLogger();
+ }
- /** Inidicates if log4php has been initialized */
- private static $initialized = false;
+ /**
+ * Clears all Logger definitions from the logger hierarchy.
+ * @return boolean
+ */
+ public static function clear()
+ {
+ return self::getHierarchy()->clear();
+ }
- /**
- * Returns the hierarchy used by this Logger.
- *
- * Caution: do not use this hierarchy unless you have called initialize().
- * To get Loggers, use the Logger::getLogger and Logger::getRootLogger
- * methods instead of operating on on the hierarchy directly.
- *
- * @return Hierarchy
- */
- public static function getHierarchy() {
- if(!isset(self::$hierarchy)) {
- self::$hierarchy = new Hierarchy(new RootLogger());
- }
- return self::$hierarchy;
- }
+ /**
+ * Destroy configurations for logger definitions
+ */
+ public static function resetConfiguration()
+ {
+ self::getHierarchy()->resetConfiguration();
+ self::getHierarchy()->clear(); // TODO: clear or not?
+ self::$initialized = false;
+ }
- /**
- * Returns a Logger by name. If it does not exist, it will be created.
- *
- * @param string $name The logger name
- * @return Logger
- */
- public static function getLogger($name) {
- if(!self::isInitialized()) {
- self::configure();
- }
- return self::getHierarchy()->getLogger($name);
- }
+ /**
+ * Safely close all appenders.
+ * @deprecated This is no longer necessary due the appenders shutdown via
+ * destructors.
+ */
+ public static function shutdown()
+ {
+ return self::getHierarchy()->shutdown();
+ }
- /**
- * Returns the Root Logger.
- * @return RootLogger
- */
- public static function getRootLogger() {
- if(!self::isInitialized()) {
- self::configure();
- }
- return self::getHierarchy()->getRootLogger();
- }
+ /**
+ * check if a given logger exists.
+ *
+ * @param string $name logger name
+ * @return boolean
+ */
+ public static function exists($name)
+ {
+ return self::getHierarchy()->exists($name);
+ }
- /**
- * Clears all Logger definitions from the logger hierarchy.
- * @return boolean
- */
- public static function clear() {
- return self::getHierarchy()->clear();
- }
+ /**
+ * Returns an array this whole Logger instances.
+ * @see Logger
+ * @return array
+ */
+ public static function getCurrentLoggers()
+ {
+ return self::getHierarchy()->getCurrentLoggers();
+ }
- /**
- * Destroy configurations for logger definitions
- */
- public static function resetConfiguration() {
- self::getHierarchy()->resetConfiguration();
- self::getHierarchy()->clear(); // TODO: clear or not?
- self::$initialized = false;
- }
+ /**
+ * Configures log4php.
+ *
+ * This method needs to be called before the first logging event has
+ * occured. If this method is not called before then the default
+ * configuration will be used.
+ *
+ * @param string|array $configuration Either a path to the configuration
+ * file, or a configuration array.
+ *
+ * @param string|Configurator $configurator A custom
+ * configurator class: either a class name (string) , or an object which
+ * implements the Configurator interface. If left empty, the default
+ * configurator implementation will be used.
+ */
+ public static function configure($configuration = null, $configurator = null)
+ {
+ self::resetConfiguration();
+ $configurator = self::getConfigurator($configurator);
+ $configurator->configure(self::getHierarchy(), $configuration);
+ self::$initialized = true;
+ }
- /**
- * Safely close all appenders.
- * @deprecated This is no longer necessary due the appenders shutdown via
- * destructors.
- */
- public static function shutdown() {
- return self::getHierarchy()->shutdown();
- }
+ /**
+ * Creates a logger configurator instance based on the provided
+ * configurator class. If no class is given, returns an instance of
+ * the default configurator.
+ *
+ * @param string|Configurator $configurator The configurator class
+ * or Configurator instance.
+ */
+ private static function getConfigurator($configurator = null)
+ {
+ if ($configurator === null) {
+ return new Configuration\DefaultConfigurator();
+ }
- /**
- * check if a given logger exists.
- *
- * @param string $name logger name
- * @return boolean
- */
- public static function exists($name) {
- return self::getHierarchy()->exists($name);
- }
+ if (is_object($configurator)) {
+ if ($configurator instanceof Configurator) {
+ return $configurator;
+ } else {
+ trigger_error("log4php: Given configurator object [$configurator] does not implement the Configurator interface. Reverting to default configurator.", E_USER_WARNING);
- /**
- * Returns an array this whole Logger instances.
- * @see Logger
- * @return array
- */
- public static function getCurrentLoggers() {
- return self::getHierarchy()->getCurrentLoggers();
- }
+ return new Configuration\DefaultConfigurator();
+ }
+ }
- /**
- * Configures log4php.
- *
- * This method needs to be called before the first logging event has
- * occured. If this method is not called before then the default
- * configuration will be used.
- *
- * @param string|array $configuration Either a path to the configuration
- * file, or a configuration array.
- *
- * @param string|Configurator $configurator A custom
- * configurator class: either a class name (string), or an object which
- * implements the Configurator interface. If left empty, the default
- * configurator implementation will be used.
- */
- public static function configure($configuration = null, $configurator = null) {
- self::resetConfiguration();
- $configurator = self::getConfigurator($configurator);
- $configurator->configure(self::getHierarchy(), $configuration);
- self::$initialized = true;
- }
+ if (is_string($configurator)) {
+ if (!class_exists($configurator)) {
+ trigger_error("log4php: Specified configurator class [$configurator] does not exist. Reverting to default configurator.", E_USER_WARNING);
- /**
- * Creates a logger configurator instance based on the provided
- * configurator class. If no class is given, returns an instance of
- * the default configurator.
- *
- * @param string|Configurator $configurator The configurator class
- * or Configurator instance.
- */
- private static function getConfigurator($configurator = null) {
- if ($configurator === null) {
- return new Configuration\DefaultConfigurator();
- }
+ return new Configuration\DefaultConfigurator();
+ }
- if (is_object($configurator)) {
- if ($configurator instanceof Configurator) {
- return $configurator;
- } else {
- trigger_error("log4php: Given configurator object [$configurator] does not implement the Configurator interface. Reverting to default configurator.", E_USER_WARNING);
- return new Configuration\DefaultConfigurator();
- }
- }
+ $instance = new $configurator();
- if (is_string($configurator)) {
- if (!class_exists($configurator)) {
- trigger_error("log4php: Specified configurator class [$configurator] does not exist. Reverting to default configurator.", E_USER_WARNING);
- return new Configuration\DefaultConfigurator();
- }
+ if (!($instance instanceof Configurator)) {
+ trigger_error("log4php: Specified configurator class [$configurator] does not implement the Configurator interface. Reverting to default configurator.", E_USER_WARNING);
- $instance = new $configurator();
+ return new Configuration\DefaultConfigurator();
+ }
- if (!($instance instanceof Configurator)) {
- trigger_error("log4php: Specified configurator class [$configurator] does not implement the Configurator interface. Reverting to default configurator.", E_USER_WARNING);
- return new Configuration\DefaultConfigurator();
- }
+ return $instance;
+ }
- return $instance;
- }
+ trigger_error("log4php: Invalid configurator specified. Expected either a string or a Configurator instance. Reverting to default configurator.", E_USER_WARNING);
- trigger_error("log4php: Invalid configurator specified. Expected either a string or a Configurator instance. Reverting to default configurator.", E_USER_WARNING);
- return new Configuration\DefaultConfigurator();
- }
+ return new Configuration\DefaultConfigurator();
+ }
- /**
- * Returns true if the log4php framework has been initialized.
- * @return boolean
- */
- private static function isInitialized() {
- return self::$initialized;
- }
+ /**
+ * Returns true if the log4php framework has been initialized.
+ * @return boolean
+ */
+ private static function isInitialized()
+ {
+ return self::$initialized;
+ }
}
diff --git a/src/LoggerException.php b/src/LoggerException.php
index 103c532..3641e90 100644
--- a/src/LoggerException.php
+++ b/src/LoggerException.php
@@ -21,5 +21,6 @@
/**
* LoggerException class
*/
-class LoggerException extends \Exception {
+class LoggerException extends \Exception
+{
}
diff --git a/src/LoggingEvent.php b/src/LoggingEvent.php
index f0fd7e3..0167c6a 100644
--- a/src/LoggingEvent.php
+++ b/src/LoggingEvent.php
@@ -21,345 +21,370 @@
/**
* The internal representation of logging event.
*/
-class LoggingEvent {
+class LoggingEvent
+{
+ private static $startTime;
- private static $startTime;
+ /**
+ * @var string Fully Qualified Class Name of the calling category class.
+ */
+ private $fqcn;
- /**
- * @var string Fully Qualified Class Name of the calling category class.
- */
- private $fqcn;
+ /**
+ * @var Logger reference
+ */
+ private $logger;
- /**
- * @var Logger reference
- */
- private $logger;
+ /**
+ * The category (logger) name.
+ * This field will be marked as private in future
+ * releases. Please do not access it directly.
+ * Use the {@link getLoggerName()} method instead.
+ * @deprecated
+ */
+ private $categoryName;
- /**
- * The category (logger) name.
- * This field will be marked as private in future
- * releases. Please do not access it directly.
- * Use the {@link getLoggerName()} method instead.
- * @deprecated
- */
- private $categoryName;
+ /**
+ * Level of the logging event.
+ * @var Level
+ */
+ protected $level;
- /**
- * Level of the logging event.
- * @var Level
- */
- protected $level;
+ /**
+ * The nested diagnostic context (NDC) of logging event.
+ * @var string
+ */
+ private $ndc;
- /**
- * The nested diagnostic context (NDC) of logging event.
- * @var string
- */
- private $ndc;
+ /**
+ * Have we tried to do an NDC lookup? If we did, there is no need
+ * to do it again. Note that its value is always false when
+ * serialized. Thus, a receiving SocketNode will never use it's own
+ * (incorrect) NDC. See also writeObject method.
+ * @var boolean
+ */
+ private $ndcLookupRequired = true;
- /**
- * Have we tried to do an NDC lookup? If we did, there is no need
- * to do it again. Note that its value is always false when
- * serialized. Thus, a receiving SocketNode will never use it's own
- * (incorrect) NDC. See also writeObject method.
- * @var boolean
- */
- private $ndcLookupRequired = true;
+ /**
+ * @var mixed The application supplied message of logging event.
+ */
+ private $message;
- /**
- * @var mixed The application supplied message of logging event.
- */
- private $message;
+ /**
+ * The application supplied message rendered through the log4php
+ * objet rendering mechanism. At present renderedMessage == message.
+ * @var string
+ */
+ private $renderedMessage;
- /**
- * The application supplied message rendered through the log4php
- * objet rendering mechanism. At present renderedMessage == message.
- * @var string
- */
- private $renderedMessage;
+ /**
+ * The name of thread in which this logging event was generated.
+ * log4php saves here the process id via {@link PHP_MANUAL#getmypid getmypid()}
+ * @var mixed
+ */
+ private $threadName;
- /**
- * The name of thread in which this logging event was generated.
- * log4php saves here the process id via {@link PHP_MANUAL#getmypid getmypid()}
- * @var mixed
- */
- private $threadName;
+ /**
+ * The number of seconds elapsed from 1/1/1970 until logging event
+ * was created plus microseconds if available.
+ * @var float
+ */
+ public $timeStamp;
- /**
- * The number of seconds elapsed from 1/1/1970 until logging event
- * was created plus microseconds if available.
- * @var float
- */
- public $timeStamp;
+ /**
+ * @var LocationInfo Location information for the caller.
+ */
+ private $locationInfo;
- /**
- * @var LocationInfo Location information for the caller.
- */
- private $locationInfo;
+ /**
+ * @var ThrowableInformation log4php internal representation of throwable
+ */
+ private $throwableInfo;
- /**
- * @var ThrowableInformation log4php internal representation of throwable
- */
- private $throwableInfo;
+ /**
+ * Instantiate a LoggingEvent from the supplied parameters.
+ *
+ * Except {@link $timeStamp} all the other fields of
+ * LoggingEvent are filled when actually needed.
+ *
+ * @param string $fqcn name of the caller class.
+ * @param mixed $logger The {@link Logger} category of this event or the logger name.
+ * @param Level $level The level of this event.
+ * @param mixed $message The message of this event.
+ * @param integer $timeStamp the timestamp of this logging event.
+ * @param Exception $throwable The throwable associated with logging event
+ */
+ public function __construct($fqcn, $logger, Level $level, $message, $timeStamp = null, $throwable = null)
+ {
+ $this->fqcn = $fqcn;
+ if ($logger instanceof Logger) {
+ $this->logger = $logger;
+ $this->categoryName = $logger->getName();
+ } else {
+ $this->categoryName = strval($logger);
+ }
+ $this->level = $level;
+ $this->message = $message;
+ if ($timeStamp !== null && is_numeric($timeStamp)) {
+ $this->timeStamp = $timeStamp;
+ } else {
+ $this->timeStamp = microtime(true);
+ }
- /**
- * Instantiate a LoggingEvent from the supplied parameters.
- *
- * Except {@link $timeStamp} all the other fields of
- * LoggingEvent are filled when actually needed.
- *
- * @param string $fqcn name of the caller class.
- * @param mixed $logger The {@link Logger} category of this event or the logger name.
- * @param Level $level The level of this event.
- * @param mixed $message The message of this event.
- * @param integer $timeStamp the timestamp of this logging event.
- * @param Exception $throwable The throwable associated with logging event
- */
- public function __construct($fqcn, $logger, Level $level, $message, $timeStamp = null, $throwable = null) {
- $this->fqcn = $fqcn;
- if($logger instanceof Logger) {
- $this->logger = $logger;
- $this->categoryName = $logger->getName();
- } else {
- $this->categoryName = strval($logger);
- }
- $this->level = $level;
- $this->message = $message;
- if($timeStamp !== null && is_numeric($timeStamp)) {
- $this->timeStamp = $timeStamp;
- } else {
- $this->timeStamp = microtime(true);
- }
+ if (isset($throwable) && $throwable instanceof \Exception) {
+ $this->throwableInfo = new ThrowableInformation($throwable);
+ }
+ }
- if (isset($throwable) && $throwable instanceof \Exception) {
- $this->throwableInfo = new ThrowableInformation($throwable);
- }
- }
+ /**
+ * Returns the full qualified classname.
+ * TODO: PHP does contain namespaces in 5.3. Those should be returned too,
+ */
+ public function getFullQualifiedClassname()
+ {
+ return $this->fqcn;
+ }
- /**
- * Returns the full qualified classname.
- * TODO: PHP does contain namespaces in 5.3. Those should be returned too,
- */
- public function getFullQualifiedClassname() {
- return $this->fqcn;
- }
+ /**
+ * Set the location information for this logging event. The collected
+ * information is cached for future use.
+ *
+ * <p>This method uses {@link PHP_MANUAL#debug_backtrace debug_backtrace()} function (if exists)
+ * to collect informations about caller.</p>
+ * <p>It only recognize informations generated by {@link Logger} and its subclasses.</p>
+ * @return LocationInfo
+ */
+ public function getLocationInformation()
+ {
+ if ($this->locationInfo === null) {
- /**
- * Set the location information for this logging event. The collected
- * information is cached for future use.
- *
- * <p>This method uses {@link PHP_MANUAL#debug_backtrace debug_backtrace()} function (if exists)
- * to collect informations about caller.</p>
- * <p>It only recognize informations generated by {@link Logger} and its subclasses.</p>
- * @return LocationInfo
- */
- public function getLocationInformation() {
- if($this->locationInfo === null) {
+ $locationInfo = array();
+ $trace = debug_backtrace();
+ $prevHop = null;
- $locationInfo = array();
- $trace = debug_backtrace();
- $prevHop = null;
+ // make a downsearch to identify the caller
+ $hop = array_pop($trace);
+ while ($hop !== null) {
+ if (isset($hop['class'])) {
+ $className = $hop['class'];
- // make a downsearch to identify the caller
- $hop = array_pop($trace);
- while($hop !== null) {
- if(isset($hop['class'])) {
- $className = $hop['class'];
+ if ($className === "Apache\\Log4php\\Logger" ||
+ $className === "Apache\\Log4php\\RootLogger") {
+ $locationInfo['line'] = $hop['line'];
+ $locationInfo['file'] = $hop['file'];
+ break;
+ }
+ }
+ $prevHop = $hop;
+ $hop = array_pop($trace);
+ }
+ $locationInfo['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main';
+ if(isset($prevHop['function']) and
+ $prevHop['function'] !== 'include' and
+ $prevHop['function'] !== 'include_once' and
+ $prevHop['function'] !== 'require' and
+ $prevHop['function'] !== 'require_once') {
- if($className === "Apache\\Log4php\\Logger" ||
- $className === "Apache\\Log4php\\RootLogger") {
- $locationInfo['line'] = $hop['line'];
- $locationInfo['file'] = $hop['file'];
- break;
- }
- }
- $prevHop = $hop;
- $hop = array_pop($trace);
- }
- $locationInfo['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main';
- if(isset($prevHop['function']) and
- $prevHop['function'] !== 'include' and
- $prevHop['function'] !== 'include_once' and
- $prevHop['function'] !== 'require' and
- $prevHop['function'] !== 'require_once') {
+ $locationInfo['function'] = $prevHop['function'];
+ } else {
+ $locationInfo['function'] = 'main';
+ }
- $locationInfo['function'] = $prevHop['function'];
- } else {
- $locationInfo['function'] = 'main';
- }
+ $this->locationInfo = new LocationInfo($locationInfo, $this->fqcn);
+ }
- $this->locationInfo = new LocationInfo($locationInfo, $this->fqcn);
- }
- return $this->locationInfo;
- }
+ return $this->locationInfo;
+ }
- /**
- * Return the level of this event. Use this form instead of directly
- * accessing the {@link $level} field.
- * @return Level
- */
- public function getLevel() {
- return $this->level;
- }
+ /**
+ * Return the level of this event. Use this form instead of directly
+ * accessing the {@link $level} field.
+ * @return Level
+ */
+ public function getLevel()
+ {
+ return $this->level;
+ }
- /**
- * Returns the logger which created the event.
- * @return Logger
- */
- public function getLogger() {
- return $this->logger;
- }
+ /**
+ * Returns the logger which created the event.
+ * @return Logger
+ */
+ public function getLogger()
+ {
+ return $this->logger;
+ }
- /**
- * Return the name of the logger. Use this form instead of directly
- * accessing the {@link $categoryName} field.
- * @return string
- */
- public function getLoggerName() {
- return $this->categoryName;
- }
+ /**
+ * Return the name of the logger. Use this form instead of directly
+ * accessing the {@link $categoryName} field.
+ * @return string
+ */
+ public function getLoggerName()
+ {
+ return $this->categoryName;
+ }
- /**
- * Return the message for this logging event.
- * @return mixed
- */
- public function getMessage() {
- return $this->message;
- }
+ /**
+ * Return the message for this logging event.
+ * @return mixed
+ */
+ public function getMessage()
+ {
+ return $this->message;
+ }
- /**
- * This method returns the NDC for this event. It will return the
- * correct content even if the event was generated in a different
- * thread or even on a different machine. The {@link NDC::get()} method
- * should <b>never</b> be called directly.
- * @return string
- */
- public function getNDC() {
- if($this->ndcLookupRequired) {
- $this->ndcLookupRequired = false;
- $this->ndc = NDC::get();
- }
- return $this->ndc;
- }
+ /**
+ * This method returns the NDC for this event. It will return the
+ * correct content even if the event was generated in a different
+ * thread or even on a different machine. The {@link NDC::get()} method
+ * should <b>never</b> be called directly.
+ * @return string
+ */
+ public function getNDC()
+ {
+ if ($this->ndcLookupRequired) {
+ $this->ndcLookupRequired = false;
+ $this->ndc = NDC::get();
+ }
- /**
- * Returns the the context corresponding to the <code>key</code>
- * parameter.
- * @return string
- */
- public function getMDC($key) {
- return MDC::get($key);
- }
+ return $this->ndc;
+ }
- /**
- * Returns the entire MDC context.
- * @return array
- */
- public function getMDCMap () {
- return MDC::getMap();
- }
+ /**
+ * Returns the the context corresponding to the <code>key</code>
+ * parameter.
+ * @return string
+ */
+ public function getMDC($key)
+ {
+ return MDC::get($key);
+ }
- /**
- * Render message.
- * @return string
- */
- public function getRenderedMessage() {
- if($this->renderedMessage === null and $this->message !== null) {
- if(is_string($this->message)) {
- $this->renderedMessage = $this->message;
- } else {
- $rendererMap = Logger::getHierarchy()->getRendererMap();
- $this->renderedMessage= $rendererMap->findAndRender($this->message);
- }
- }
- return $this->renderedMessage;
- }
+ /**
+ * Returns the entire MDC context.
+ * @return array
+ */
+ public function getMDCMap()
+ {
+ return MDC::getMap();
+ }
- /**
- * Returns the time when the application started, as a UNIX timestamp
- * with microseconds.
- * @return float
- */
- public static function getStartTime() {
- if(!isset(self::$startTime)) {
- self::$startTime = microtime(true);
- }
- return self::$startTime;
- }
+ /**
+ * Render message.
+ * @return string
+ */
+ public function getRenderedMessage()
+ {
+ if ($this->renderedMessage === null and $this->message !== null) {
+ if (is_string($this->message)) {
+ $this->renderedMessage = $this->message;
+ } else {
+ $rendererMap = Logger::getHierarchy()->getRendererMap();
+ $this->renderedMessage= $rendererMap->findAndRender($this->message);
+ }
+ }
- /**
- * @return float
- */
- public function getTimeStamp() {
- return $this->timeStamp;
- }
+ return $this->renderedMessage;
+ }
- /**
- * Returns the time in seconds passed from the beginning of execution to
- * the time the event was constructed.
- *
- * @return float Seconds with microseconds in decimals.
- */
- public function getRelativeTime() {
- return $this->timeStamp - self::$startTime;
- }
+ /**
+ * Returns the time when the application started, as a UNIX timestamp
+ * with microseconds.
+ * @return float
+ */
+ public static function getStartTime()
+ {
+ if (!isset(self::$startTime)) {
+ self::$startTime = microtime(true);
+ }
- /**
- * Returns the time in milliseconds passed from the beginning of execution
- * to the time the event was constructed.
- *
- * @deprecated This method has been replaced by getRelativeTime which
- * does not perform unneccesary multiplication and formatting.
- *
- * @return integer
- */
- public function getTime() {
- $eventTime = $this->getTimeStamp();
- $eventStartTime = LoggingEvent::getStartTime();
- return number_format(($eventTime - $eventStartTime) * 1000, 0, '', '');
- }
+ return self::$startTime;
+ }
- /**
- * @return mixed
- */
- public function getThreadName() {
- if ($this->threadName === null) {
- $this->threadName = (string)getmypid();
- }
- return $this->threadName;
- }
+ /**
+ * @return float
+ */
+ public function getTimeStamp()
+ {
+ return $this->timeStamp;
+ }
- /**
- * @return mixed ThrowableInformation
- */
- public function getThrowableInformation() {
- return $this->throwableInfo;
- }
+ /**
+ * Returns the time in seconds passed from the beginning of execution to
+ * the time the event was constructed.
+ *
+ * @return float Seconds with microseconds in decimals.
+ */
+ public function getRelativeTime()
+ {
+ return $this->timeStamp - self::$startTime;
+ }
- /**
- * Serialize this object
- * @return string
- */
- public function toString() {
- serialize($this);
- }
+ /**
+ * Returns the time in milliseconds passed from the beginning of execution
+ * to the time the event was constructed.
+ *
+ * @deprecated This method has been replaced by getRelativeTime which
+ * does not perform unneccesary multiplication and formatting.
+ *
+ * @return integer
+ */
+ public function getTime()
+ {
+ $eventTime = $this->getTimeStamp();
+ $eventStartTime = LoggingEvent::getStartTime();
- /**
- * Avoid serialization of the {@link $logger} object
- */
- public function __sleep() {
- return array(
- 'fqcn',
- 'categoryName',
- 'level',
- 'ndc',
- 'ndcLookupRequired',
- 'message',
- 'renderedMessage',
- 'threadName',
- 'timeStamp',
- 'locationInfo',
- );
- }
+ return number_format(($eventTime - $eventStartTime) * 1000, 0, '', '');
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getThreadName()
+ {
+ if ($this->threadName === null) {
+ $this->threadName = (string) getmypid();
+ }
+
+ return $this->threadName;
+ }
+
+ /**
+ * @return mixed ThrowableInformation
+ */
+ public function getThrowableInformation()
+ {
+ return $this->throwableInfo;
+ }
+
+ /**
+ * Serialize this object
+ * @return string
+ */
+ public function toString()
+ {
+ serialize($this);
+ }
+
+ /**
+ * Avoid serialization of the {@link $logger} object
+ */
+ public function __sleep()
+ {
+ return array(
+ 'fqcn',
+ 'categoryName',
+ 'level',
+ 'ndc',
+ 'ndcLookupRequired',
+ 'message',
+ 'renderedMessage',
+ 'threadName',
+ 'timeStamp',
+ 'locationInfo',
+ );
+ }
}
diff --git a/src/MDC.php b/src/MDC.php
index 9f911c6..6e7f008 100644
--- a/src/MDC.php
+++ b/src/MDC.php
@@ -32,56 +32,61 @@
* @since 0.3
*
*/
-class MDC {
+class MDC
+{
+ /** Holds the context map. */
+ private static $map = array();
- /** Holds the context map. */
- private static $map = array();
+ /**
+ * Stores a context value as identified with the key parameter into the
+ * context map.
+ *
+ * @param string $key the key
+ * @param string $value the value
+ */
+ public static function put($key, $value)
+ {
+ self::$map[$key] = $value;
+ }
- /**
- * Stores a context value as identified with the key parameter into the
- * context map.
- *
- * @param string $key the key
- * @param string $value the value
- */
- public static function put($key, $value) {
- self::$map[$key] = $value;
- }
+ /**
+ * Returns the context value identified by the key parameter.
+ *
+ * @param string $key The key.
+ * @return string The context or an empty string if no context found
+ * for given key.
+ */
+ public static function get($key)
+ {
+ return isset(self::$map[$key]) ? self::$map[$key] : '';
+ }
- /**
- * Returns the context value identified by the key parameter.
- *
- * @param string $key The key.
- * @return string The context or an empty string if no context found
- * for given key.
- */
- public static function get($key) {
- return isset(self::$map[$key]) ? self::$map[$key] : '';
- }
+ /**
+ * Returns the contex map as an array.
+ * @return array The MDC context map.
+ */
+ public static function getMap()
+ {
+ return self::$map;
+ }
- /**
- * Returns the contex map as an array.
- * @return array The MDC context map.
- */
- public static function getMap() {
- return self::$map;
- }
+ /**
+ * Removes the the context identified by the key parameter.
+ *
+ * Only affects user mappings, not $_ENV or $_SERVER.
+ *
+ * @param string $key The key to be removed.
+ */
+ public static function remove($key)
+ {
+ unset(self::$map[$key]);
+ }
- /**
- * Removes the the context identified by the key parameter.
- *
- * Only affects user mappings, not $_ENV or $_SERVER.
- *
- * @param string $key The key to be removed.
- */
- public static function remove($key) {
- unset(self::$map[$key]);
- }
-
- /**
- * Clears the mapped diagnostic context.
- */
- public static function clear() {
- self::$map = array();
- }
+ /**
+ * Clears the mapped diagnostic context.
+ */
+ public static function clear()
+ {
+ self::$map = array();
+ }
}
diff --git a/src/NDC.php b/src/NDC.php
index b3de74a..c81c233 100644
--- a/src/NDC.php
+++ b/src/NDC.php
@@ -74,111 +74,119 @@
*
* @since 0.3
*/
-class NDC {
+class NDC
+{
+ /** This is the repository of NDC stack */
+ private static $stack = array();
- /** This is the repository of NDC stack */
- private static $stack = array();
+ /**
+ * Clear any nested diagnostic information if any. This method is
+ * useful in cases where the same thread can be potentially used
+ * over and over in different unrelated contexts.
+ *
+ * <p>This method is equivalent to calling the {@link setMaxDepth()}
+ * method with a zero <var>maxDepth</var> argument.
+ */
+ public static function clear()
+ {
+ self::$stack = array();
+ }
- /**
- * Clear any nested diagnostic information if any. This method is
- * useful in cases where the same thread can be potentially used
- * over and over in different unrelated contexts.
- *
- * <p>This method is equivalent to calling the {@link setMaxDepth()}
- * method with a zero <var>maxDepth</var> argument.
- */
- public static function clear() {
- self::$stack = array();
- }
+ /**
+ * Never use this method directly, use the {@link LoggingEvent::getNDC()} method instead.
+ * @return array
+ */
+ public static function get()
+ {
+ return implode(' ', self::$stack);
+ }
- /**
- * Never use this method directly, use the {@link LoggingEvent::getNDC()} method instead.
- * @return array
- */
- public static function get() {
- return implode(' ', self::$stack);
- }
+ /**
+ * Get the current nesting depth of this diagnostic context.
+ *
+ * @see setMaxDepth()
+ * @return integer
+ */
+ public static function getDepth()
+ {
+ return count(self::$stack);
+ }
- /**
- * Get the current nesting depth of this diagnostic context.
- *
- * @see setMaxDepth()
- * @return integer
- */
- public static function getDepth() {
- return count(self::$stack);
- }
+ /**
+ * Clients should call this method before leaving a diagnostic
+ * context.
+ *
+ * <p>The returned value is the value that was pushed last. If no
+ * context is available, then the empty string "" is returned.</p>
+ *
+ * @return string The innermost diagnostic context.
+ */
+ public static function pop()
+ {
+ if (count(self::$stack) > 0) {
+ return array_pop(self::$stack);
+ } else {
+ return '';
+ }
+ }
- /**
- * Clients should call this method before leaving a diagnostic
- * context.
- *
- * <p>The returned value is the value that was pushed last. If no
- * context is available, then the empty string "" is returned.</p>
- *
- * @return string The innermost diagnostic context.
- */
- public static function pop() {
- if(count(self::$stack) > 0) {
- return array_pop(self::$stack);
- } else {
- return '';
- }
- }
+ /**
+ * Looks at the last diagnostic context at the top of this NDC
+ * without removing it.
+ *
+ * <p>The returned value is the value that was pushed last. If no
+ * context is available, then the empty string "" is returned.</p>
+ * @return string The innermost diagnostic context.
+ */
+ public static function peek()
+ {
+ if (count(self::$stack) > 0) {
+ return end(self::$stack);
+ } else {
+ return '';
+ }
+ }
- /**
- * Looks at the last diagnostic context at the top of this NDC
- * without removing it.
- *
- * <p>The returned value is the value that was pushed last. If no
- * context is available, then the empty string "" is returned.</p>
- * @return string The innermost diagnostic context.
- */
- public static function peek() {
- if(count(self::$stack) > 0) {
- return end(self::$stack);
- } else {
- return '';
- }
- }
+ /**
+ * Push new diagnostic context information for the current thread.
+ *
+ * <p>The contents of the <var>message</var> parameter is
+ * determined solely by the client.
+ *
+ * @param string $message The new diagnostic context information.
+ */
+ public static function push($message)
+ {
+ array_push(self::$stack, (string) $message);
+ }
- /**
- * Push new diagnostic context information for the current thread.
- *
- * <p>The contents of the <var>message</var> parameter is
- * determined solely by the client.
- *
- * @param string $message The new diagnostic context information.
- */
- public static function push($message) {
- array_push(self::$stack, (string)$message);
- }
+ /**
+ * Remove the diagnostic context for this thread.
+ */
+ public static function remove()
+ {
+ NDC::clear();
+ }
- /**
- * Remove the diagnostic context for this thread.
- */
- public static function remove() {
- NDC::clear();
- }
-
- /**
- * Set maximum depth of this diagnostic context. If the current
- * depth is smaller or equal to <var>maxDepth</var>, then no
- * action is taken.
- *
- * <p>This method is a convenient alternative to multiple
- * {@link pop()} calls. Moreover, it is often the case that at
- * the end of complex call sequences, the depth of the NDC is
- * unpredictable. The {@link setMaxDepth()} method circumvents
- * this problem.
- *
- * @param integer $maxDepth
- * @see getDepth()
- */
- public static function setMaxDepth($maxDepth) {
- $maxDepth = (int)$maxDepth;
- if(NDC::getDepth() > $maxDepth) {
- self::$stack = array_slice(self::$stack, 0, $maxDepth);
- }
- }
+ /**
+ * Set maximum depth of this diagnostic context. If the current
+ * depth is smaller or equal to <var>maxDepth</var>, then no
+ * action is taken.
+ *
+ * <p>This method is a convenient alternative to multiple
+ * {@link pop()} calls. Moreover, it is often the case that at
+ * the end of complex call sequences, the depth of the NDC is
+ * unpredictable. The {@link setMaxDepth()} method circumvents
+ * this problem.
+ *
+ * @param integer $maxDepth
+ * @see getDepth()
+ */
+ public static function setMaxDepth($maxDepth)
+ {
+ $maxDepth = (int) $maxDepth;
+ if (NDC::getDepth() > $maxDepth) {
+ self::$stack = array_slice(self::$stack, 0, $maxDepth);
+ }
+ }
}
diff --git a/src/Pattern/AbstractConverter.php b/src/Pattern/AbstractConverter.php
index dc13f4b..57c6dfc 100644
--- a/src/Pattern/AbstractConverter.php
+++ b/src/Pattern/AbstractConverter.php
@@ -30,101 +30,105 @@
* converting a logging event in a converter specific manner.</p>
* @since 0.3
*/
-abstract class AbstractConverter {
+abstract class AbstractConverter
+{
+ /**
+ * Next converter in the converter chain.
+ * @var AbstractConverter
+ */
+ public $next = null;
- /**
- * Next converter in the converter chain.
- * @var AbstractConverter
- */
- public $next = null;
+ /**
+ * Formatting information, parsed from pattern modifiers.
+ * @var FormattingInfo
+ */
+ protected $formattingInfo;
- /**
- * Formatting information, parsed from pattern modifiers.
- * @var FormattingInfo
- */
- protected $formattingInfo;
+ /**
+ * Converter-specific formatting options.
+ * @var array
+ */
+ protected $option;
- /**
- * Converter-specific formatting options.
- * @var array
- */
- protected $option;
+ /**
+ * Constructor
+ * @param FormattingInfo $formattingInfo
+ * @param array $option
+ */
+ public function __construct(FormattingInfo $formattingInfo = null, $option = null)
+ {
+ $this->formattingInfo = $formattingInfo;
+ $this->option = $option;
+ $this->activateOptions();
+ }
- /**
- * Constructor
- * @param FormattingInfo $formattingInfo
- * @param array $option
- */
- public function __construct(FormattingInfo $formattingInfo = null, $option = null) {
- $this->formattingInfo = $formattingInfo;
- $this->option = $option;
- $this->activateOptions();
- }
+ /**
+ * Called in constructor. Converters which need to process the options
+ * can override this method.
+ */
+ public function activateOptions() { }
- /**
- * Called in constructor. Converters which need to process the options
- * can override this method.
- */
- public function activateOptions() { }
+ /**
+ * Converts the logging event to the desired format. Derived pattern
+ * converters must implement this method.
+ *
+ * @param LoggingEvent $event
+ */
+ abstract public function convert(LoggingEvent $event);
- /**
- * Converts the logging event to the desired format. Derived pattern
- * converters must implement this method.
- *
- * @param LoggingEvent $event
- */
- abstract public function convert(LoggingEvent $event);
+ /**
+ * Converts the event and formats it according to setting in the
+ * Formatting information object.
+ *
+ * @param string &$sbuf string buffer to write to
+ * @param LoggingEvent $event Event to be formatted.
+ */
+ public function format(&$sbuf, $event)
+ {
+ $string = $this->convert($event);
- /**
- * Converts the event and formats it according to setting in the
- * Formatting information object.
- *
- * @param string &$sbuf string buffer to write to
- * @param LoggingEvent $event Event to be formatted.
- */
- public function format(&$sbuf, $event) {
- $string = $this->convert($event);
+ if (!isset($this->formattingInfo)) {
+ $sbuf .= $string;
- if (!isset($this->formattingInfo)) {
- $sbuf .= $string;
- return;
- }
+ return;
+ }
- $fi = $this->formattingInfo;
+ $fi = $this->formattingInfo;
- // Empty string
- if($string === '' || is_null($string)) {
- if($fi->min > 0) {
- $sbuf .= str_repeat(' ', $fi->min);
- }
- return;
- }
+ // Empty string
+ if ($string === '' || is_null($string)) {
+ if ($fi->min > 0) {
+ $sbuf .= str_repeat(' ', $fi->min);
+ }
- $len = strlen($string);
+ return;
+ }
- // Trim the string if needed
- if($len > $fi->max) {
- if ($fi->trimLeft) {
- $sbuf .= substr($string, $len - $fi->max, $fi->max);
- } else {
- $sbuf .= substr($string , 0, $fi->max);
- }
- }
+ $len = strlen($string);
- // Add padding if needed
- else if($len < $fi->min) {
- if($fi->padLeft) {
- $sbuf .= str_repeat(' ', $fi->min - $len);
- $sbuf .= $string;
- } else {
- $sbuf .= $string;
- $sbuf .= str_repeat(' ', $fi->min - $len);
- }
- }
+ // Trim the string if needed
+ if ($len > $fi->max) {
+ if ($fi->trimLeft) {
+ $sbuf .= substr($string, $len - $fi->max, $fi->max);
+ } else {
+ $sbuf .= substr($string , 0, $fi->max);
+ }
+ }
- // No action needed
- else {
- $sbuf .= $string;
- }
- }
+ // Add padding if needed
+ else if ($len < $fi->min) {
+ if ($fi->padLeft) {
+ $sbuf .= str_repeat(' ', $fi->min - $len);
+ $sbuf .= $string;
+ } else {
+ $sbuf .= $string;
+ $sbuf .= str_repeat(' ', $fi->min - $len);
+ }
+ }
+
+ // No action needed
+ else {
+ $sbuf .= $string;
+ }
+ }
}
diff --git a/src/Pattern/ClassConverter.php b/src/Pattern/ClassConverter.php
index b5e658c..09b87da 100644
--- a/src/Pattern/ClassConverter.php
+++ b/src/Pattern/ClassConverter.php
@@ -26,37 +26,39 @@
* request was issued.
* @since 2.3
*/
-class ClassConverter extends AbstractConverter {
+class ClassConverter extends AbstractConverter
+{
+ /** Length to which to shorten the class name. */
+ private $length;
- /** Length to which to shorten the class name. */
- private $length;
+ /** Holds processed class names. */
+ private $cache = array();
- /** Holds processed class names. */
- private $cache = array();
+ public function activateOptions()
+ {
+ // Parse the option (desired output length)
+ if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
+ $this->length = (integer) $this->option;
+ }
+ }
- public function activateOptions() {
- // Parse the option (desired output length)
- if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
- $this->length = (integer) $this->option;
- }
- }
+ public function convert(LoggingEvent $event)
+ {
+ $name = $event->getLocationInformation()->getClassName();
- public function convert(LoggingEvent $event) {
- $name = $event->getLocationInformation()->getClassName();
+ if (!isset($this->cache[$name])) {
- if (!isset($this->cache[$name])) {
+ // If length is set return shortened class name
+ if (isset($this->length)) {
+ $this->cache[$name] = Utils::shortenClassName($name, $this->length);
+ }
- // If length is set return shortened class name
- if (isset($this->length)) {
- $this->cache[$name] = Utils::shortenClassName($name, $this->length);
- }
+ // If no length is specified return the full class name
+ else {
+ $this->cache[$name] = $name;
+ }
+ }
- // If no length is specified return the full class name
- else {
- $this->cache[$name] = $name;
- }
- }
-
- return $this->cache[$name];
- }
+ return $this->cache[$name];
+ }
}
diff --git a/src/Pattern/CookieConverter.php b/src/Pattern/CookieConverter.php
index 69b5738..245c11d 100644
--- a/src/Pattern/CookieConverter.php
+++ b/src/Pattern/CookieConverter.php
@@ -27,6 +27,7 @@
*
* @since 2.3
*/
-class CookieConverter extends SuperglobalConverter {
- protected $name = '_COOKIE';
-}
\ No newline at end of file
+class CookieConverter extends SuperglobalConverter
+{
+ protected $name = '_COOKIE';
+}
diff --git a/src/Pattern/DateConverter.php b/src/Pattern/DateConverter.php
index 5a1ad4a..d6ddc7e 100644
--- a/src/Pattern/DateConverter.php
+++ b/src/Pattern/DateConverter.php
@@ -30,60 +30,63 @@
* 'ISO8601', 'ABSOLUTE' and 'DATE'.
* @since 2.3
*/
-class DateConverter extends AbstractConverter {
+class DateConverter extends AbstractConverter
+{
+ const DATE_FORMAT_ISO8601 = 'c';
- const DATE_FORMAT_ISO8601 = 'c';
+ const DATE_FORMAT_ABSOLUTE = 'H:i:s';
- const DATE_FORMAT_ABSOLUTE = 'H:i:s';
+ const DATE_FORMAT_DATE = 'd M Y H:i:s.u';
- const DATE_FORMAT_DATE = 'd M Y H:i:s.u';
+ private $format = self::DATE_FORMAT_ISO8601;
- private $format = self::DATE_FORMAT_ISO8601;
+ private $specials = array(
+ 'ISO8601' => self::DATE_FORMAT_ISO8601,
+ 'ABSOLUTE' => self::DATE_FORMAT_ABSOLUTE,
+ 'DATE' => self::DATE_FORMAT_DATE,
+ );
- private $specials = array(
- 'ISO8601' => self::DATE_FORMAT_ISO8601,
- 'ABSOLUTE' => self::DATE_FORMAT_ABSOLUTE,
- 'DATE' => self::DATE_FORMAT_DATE,
- );
+ private $useLocalDate = false;
- private $useLocalDate = false;
+ public function activateOptions()
+ {
+ // Parse the option (date format)
+ if (!empty($this->option)) {
+ if (isset($this->specials[$this->option])) {
+ $this->format = $this->specials[$this->option];
+ } else {
+ $this->format = $this->option;
+ }
+ }
- public function activateOptions() {
+ // Check whether the pattern contains milliseconds (u)
+ if (preg_match('/(?<!\\\\)u/', $this->format)) {
+ $this->useLocalDate = true;
+ }
+ }
- // Parse the option (date format)
- if (!empty($this->option)) {
- if(isset($this->specials[$this->option])) {
- $this->format = $this->specials[$this->option];
- } else {
- $this->format = $this->option;
- }
- }
+ public function convert(LoggingEvent $event)
+ {
+ if ($this->useLocalDate) {
+ return $this->date($this->format, $event->getTimeStamp());
+ }
- // Check whether the pattern contains milliseconds (u)
- if (preg_match('/(?<!\\\\)u/', $this->format)) {
- $this->useLocalDate = true;
- }
- }
+ return date($this->format, $event->getTimeStamp());
+ }
- public function convert(LoggingEvent $event) {
- if ($this->useLocalDate) {
- return $this->date($this->format, $event->getTimeStamp());
- }
- return date($this->format, $event->getTimeStamp());
- }
+ /**
+ * Currently, PHP date() function always returns zeros for milliseconds (u)
+ * on Windows. This is a replacement function for date() which correctly
+ * displays milliseconds on all platforms.
+ *
+ * It is slower than PHP date() so it should only be used if necessary.
+ */
+ private function date($format, $utimestamp)
+ {
+ $timestamp = floor($utimestamp);
+ $ms = floor(($utimestamp - $timestamp) * 1000);
+ $ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
- /**
- * Currently, PHP date() function always returns zeros for milliseconds (u)
- * on Windows. This is a replacement function for date() which correctly
- * displays milliseconds on all platforms.
- *
- * It is slower than PHP date() so it should only be used if necessary.
- */
- private function date($format, $utimestamp) {
- $timestamp = floor($utimestamp);
- $ms = floor(($utimestamp - $timestamp) * 1000);
- $ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
-
- return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
- }
+ return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
+ }
}
diff --git a/src/Pattern/EnvironmentConverter.php b/src/Pattern/EnvironmentConverter.php
index 7be0272..6d1afa7 100644
--- a/src/Pattern/EnvironmentConverter.php
+++ b/src/Pattern/EnvironmentConverter.php
@@ -28,6 +28,7 @@
*
* @since 2.3
*/
-class EnvironmentConverter extends SuperglobalConverter {
- protected $name = '_ENV';
+class EnvironmentConverter extends SuperglobalConverter
+{
+ protected $name = '_ENV';
}
diff --git a/src/Pattern/FileConverter.php b/src/Pattern/FileConverter.php
index 809192d..15ce1ba 100644
--- a/src/Pattern/FileConverter.php
+++ b/src/Pattern/FileConverter.php
@@ -24,9 +24,10 @@
* Returns the name of the file from which the logging request was issued.
* @since 2.3
*/
-class FileConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getLocationInformation()->getFileName();
- }
+class FileConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getLocationInformation()->getFileName();
+ }
}
diff --git a/src/Pattern/LevelConverter.php b/src/Pattern/LevelConverter.php
index 3b42fe0..dabd5c3 100644
--- a/src/Pattern/LevelConverter.php
+++ b/src/Pattern/LevelConverter.php
@@ -24,9 +24,10 @@
* Returns the event's level.
* @since 2.3
*/
-class LevelConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getLevel()->toString();
- }
+class LevelConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getLevel()->toString();
+ }
}
diff --git a/src/Pattern/LineConverter.php b/src/Pattern/LineConverter.php
index 659fa11..6a47e2e 100644
--- a/src/Pattern/LineConverter.php
+++ b/src/Pattern/LineConverter.php
@@ -25,9 +25,10 @@
* issued.
* @since 2.3
*/
-class LineConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getLocationInformation()->getLineNumber();
- }
+class LineConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getLocationInformation()->getLineNumber();
+ }
}
diff --git a/src/Pattern/LiteralConverter.php b/src/Pattern/LiteralConverter.php
index 089fa7f..061aed5 100644
--- a/src/Pattern/LiteralConverter.php
+++ b/src/Pattern/LiteralConverter.php
@@ -24,15 +24,17 @@
* Returns the literal value passed in the constructor, without modifications.
* @since 2.3
*/
-class LiteralConverter extends AbstractConverter {
+class LiteralConverter extends AbstractConverter
+{
+ private $literalValue;
- private $literalValue;
+ public function __construct($literalValue)
+ {
+ $this->literalValue = $literalValue;
+ }
- public function __construct($literalValue) {
- $this->literalValue = $literalValue;
- }
-
- public function convert(LoggingEvent $event) {
- return $this->literalValue;
- }
+ public function convert(LoggingEvent $event)
+ {
+ return $this->literalValue;
+ }
}
diff --git a/src/Pattern/LocationConverter.php b/src/Pattern/LocationConverter.php
index 4334ec7..c100807 100644
--- a/src/Pattern/LocationConverter.php
+++ b/src/Pattern/LocationConverter.php
@@ -25,13 +25,14 @@
* issued.
* @since 2.3
*/
-class LocationConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return
- $event->getLocationInformation()->getClassName() . '.' .
- $event->getLocationInformation()->getMethodName() . '(' .
- $event->getLocationInformation()->getFileName() . ':' .
- $event->getLocationInformation()->getLineNumber() . ')';
- }
+class LocationConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return
+ $event->getLocationInformation()->getClassName() . '.' .
+ $event->getLocationInformation()->getMethodName() . '(' .
+ $event->getLocationInformation()->getFileName() . ':' .
+ $event->getLocationInformation()->getLineNumber() . ')';
+ }
}
diff --git a/src/Pattern/LoggerConverter.php b/src/Pattern/LoggerConverter.php
index 0433659..7c419ac 100644
--- a/src/Pattern/LoggerConverter.php
+++ b/src/Pattern/LoggerConverter.php
@@ -28,37 +28,39 @@
* name will be shortened to the given length, if possible.
* @since 2.3
*/
-class LoggerConverter extends AbstractConverter {
+class LoggerConverter extends AbstractConverter
+{
+ /** Length to which to shorten the name. */
+ private $length;
- /** Length to which to shorten the name. */
- private $length;
+ /** Holds processed logger names. */
+ private $cache = array();
- /** Holds processed logger names. */
- private $cache = array();
+ public function activateOptions()
+ {
+ // Parse the option (desired output length)
+ if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
+ $this->length = (integer) $this->option;
+ }
+ }
- public function activateOptions() {
- // Parse the option (desired output length)
- if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
- $this->length = (integer) $this->option;
- }
- }
+ public function convert(LoggingEvent $event)
+ {
+ $name = $event->getLoggerName();
- public function convert(LoggingEvent $event) {
- $name = $event->getLoggerName();
+ if (!isset($this->cache[$name])) {
- if (!isset($this->cache[$name])) {
+ // If length is set return shortened logger name
+ if (isset($this->length)) {
+ $this->cache[$name] = Utils::shortenClassName($name, $this->length);
+ }
- // If length is set return shortened logger name
- if (isset($this->length)) {
- $this->cache[$name] = Utils::shortenClassName($name, $this->length);
- }
+ // If no length is specified return full logger name
+ else {
+ $this->cache[$name] = $name;
+ }
+ }
- // If no length is specified return full logger name
- else {
- $this->cache[$name] = $name;
- }
- }
-
- return $this->cache[$name];
- }
+ return $this->cache[$name];
+ }
}
diff --git a/src/Pattern/MdcConverter.php b/src/Pattern/MdcConverter.php
index cb50c8e..6739694 100644
--- a/src/Pattern/MdcConverter.php
+++ b/src/Pattern/MdcConverter.php
@@ -27,26 +27,29 @@
* [0] the MDC key
* @since 2.3
*/
-class MdcConverter extends AbstractConverter {
+class MdcConverter extends AbstractConverter
+{
+ private $key;
- private $key;
+ public function activateOptions()
+ {
+ if (isset($this->option) && $this->option !== '') {
+ $this->key = $this->option;
+ }
+ }
- public function activateOptions() {
- if (isset($this->option) && $this->option !== '') {
- $this->key = $this->option;
- }
- }
+ public function convert(LoggingEvent $event)
+ {
+ if (isset($this->key)) {
+ return $event->getMDC($this->key);
+ } else {
+ $buff = array();
+ $map = $event->getMDCMap();
+ foreach ($map as $key => $value) {
+ $buff []= "$key=$value";
+ }
- public function convert(LoggingEvent $event) {
- if (isset($this->key)) {
- return $event->getMDC($this->key);
- } else {
- $buff = array();
- $map = $event->getMDCMap();
- foreach($map as $key => $value) {
- $buff []= "$key=$value";
- }
- return implode(', ', $buff);
- }
- }
+ return implode(', ', $buff);
+ }
+ }
}
diff --git a/src/Pattern/MessageConverter.php b/src/Pattern/MessageConverter.php
index acd53d8..de9004d 100644
--- a/src/Pattern/MessageConverter.php
+++ b/src/Pattern/MessageConverter.php
@@ -24,9 +24,10 @@
* Returns the logged message.
* @since 2.3
*/
-class MessageConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getRenderedMessage();
- }
+class MessageConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getRenderedMessage();
+ }
}
diff --git a/src/Pattern/MethodConverter.php b/src/Pattern/MethodConverter.php
index d0c29e8..523693b 100644
--- a/src/Pattern/MethodConverter.php
+++ b/src/Pattern/MethodConverter.php
@@ -25,9 +25,10 @@
* was issued.
* @since 2.3
*/
-class MethodConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getLocationInformation()->getMethodName();
- }
+class MethodConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getLocationInformation()->getMethodName();
+ }
}
diff --git a/src/Pattern/NdcConverter.php b/src/Pattern/NdcConverter.php
index fb0027e..12255a4 100644
--- a/src/Pattern/NdcConverter.php
+++ b/src/Pattern/NdcConverter.php
@@ -24,9 +24,10 @@
* Returns the full Nested Diagnostic Context.
* @since 2.3
*/
-class NdcConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return $event->getNDC();
- }
+class NdcConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return $event->getNDC();
+ }
}
diff --git a/src/Pattern/NewLineConverter.php b/src/Pattern/NewLineConverter.php
index 2e3f7e6..8754952 100644
--- a/src/Pattern/NewLineConverter.php
+++ b/src/Pattern/NewLineConverter.php
@@ -24,9 +24,10 @@
* Returns platform-specific newline character(s).
* @since 2.3
*/
-class NewLineConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return PHP_EOL;
- }
+class NewLineConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return PHP_EOL;
+ }
}
diff --git a/src/Pattern/ProcessConverter.php b/src/Pattern/ProcessConverter.php
index 4ba2151..e0d87f3 100644
--- a/src/Pattern/ProcessConverter.php
+++ b/src/Pattern/ProcessConverter.php
@@ -24,9 +24,10 @@
* Returns the PID of the current process.
* @since 2.3
*/
-class ProcessConverter extends AbstractConverter {
-
- public function convert(LoggingEvent $event) {
- return getmypid();
- }
+class ProcessConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return getmypid();
+ }
}
diff --git a/src/Pattern/RelativeConverter.php b/src/Pattern/RelativeConverter.php
index d6e3111..02fe940 100644
--- a/src/Pattern/RelativeConverter.php
+++ b/src/Pattern/RelativeConverter.php
@@ -25,10 +25,12 @@
* application until the creation of the logging event.
* @since 2.3
*/
-class RelativeConverter extends AbstractConverter {
+class RelativeConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ $ts = $event->getRelativeTime();
- public function convert(LoggingEvent $event) {
- $ts = $event->getRelativeTime();
- return number_format($ts, 4);
- }
+ return number_format($ts, 4);
+ }
}
diff --git a/src/Pattern/RequestConverter.php b/src/Pattern/RequestConverter.php
index 5440e75..9c72c33 100644
--- a/src/Pattern/RequestConverter.php
+++ b/src/Pattern/RequestConverter.php
@@ -18,8 +18,6 @@
namespace Apache\Log4php\Pattern;
-use Apache\Log4php\LoggingEvent;
-
/**
* Returns a value from the $_REQUEST superglobal array corresponding to the
* given key.
@@ -30,6 +28,7 @@
*
* @since 2.3
*/
-class RequestConverter extends SuperglobalConverter {
- protected $name = '_REQUEST';
-}
\ No newline at end of file
+class RequestConverter extends SuperglobalConverter
+{
+ protected $name = '_REQUEST';
+}
diff --git a/src/Pattern/ServerConverter.php b/src/Pattern/ServerConverter.php
index c6085ce..0ed7d5a 100644
--- a/src/Pattern/ServerConverter.php
+++ b/src/Pattern/ServerConverter.php
@@ -18,8 +18,6 @@
namespace Apache\Log4php\Pattern;
-use Apache\Log4php\LoggingEvent;
-
/**
* Returns a value from the $_SERVER superglobal array corresponding to the
* given key.
@@ -30,6 +28,7 @@
*
* @since 2.3
*/
-class ServerConverter extends SuperglobalConverter {
- protected $name = '_SERVER';
+class ServerConverter extends SuperglobalConverter
+{
+ protected $name = '_SERVER';
}
diff --git a/src/Pattern/SessionConverter.php b/src/Pattern/SessionConverter.php
index c5d812b..52343de 100644
--- a/src/Pattern/SessionConverter.php
+++ b/src/Pattern/SessionConverter.php
@@ -18,8 +18,6 @@
namespace Apache\Log4php\Pattern;
-use Apache\Log4php\LoggingEvent;
-
/**
* Returns a value from the $_SESSION superglobal array corresponding to the
* given key.
@@ -30,6 +28,7 @@
*
* @since 2.3
*/
-class SessionConverter extends SuperglobalConverter {
- protected $name = '_SESSION';
+class SessionConverter extends SuperglobalConverter
+{
+ protected $name = '_SESSION';
}
diff --git a/src/Pattern/SessionIdConverter.php b/src/Pattern/SessionIdConverter.php
index c5d622c..23324c4 100644
--- a/src/Pattern/SessionIdConverter.php
+++ b/src/Pattern/SessionIdConverter.php
@@ -24,8 +24,10 @@
* Returns the active session ID, or an empty string if out of session.
* @since 2.3
*/
-class SessionIdConverter extends AbstractConverter {
- public function convert(LoggingEvent $event) {
- return session_id();
- }
+class SessionIdConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ return session_id();
+ }
}
diff --git a/src/Pattern/SuperglobalConverter.php b/src/Pattern/SuperglobalConverter.php
index c43d0c0..7befa67 100644
--- a/src/Pattern/SuperglobalConverter.php
+++ b/src/Pattern/SuperglobalConverter.php
@@ -34,67 +34,70 @@
* @see http://www.php.net/manual/en/ini.core.php#ini.variables-order
* @since 2.3
*/
-abstract class SuperglobalConverter extends AbstractConverter {
+abstract class SuperglobalConverter extends AbstractConverter
+{
+ /**
+ * Name of the superglobal variable, to be defined by subclasses.
+ * For example: "_SERVER" or "_ENV".
+ */
+ protected $name;
- /**
- * Name of the superglobal variable, to be defined by subclasses.
- * For example: "_SERVER" or "_ENV".
- */
- protected $name;
+ protected $value = '';
- protected $value = '';
+ public function activateOptions()
+ {
+ // Read the key from options array
+ if (isset($this->option) && $this->option !== '') {
+ $key = $this->option;
+ }
- public function activateOptions() {
- // Read the key from options array
- if (isset($this->option) && $this->option !== '') {
- $key = $this->option;
- }
+ /*
+ * There is a bug in PHP which doesn't allow superglobals to be
+ * accessed when their name is stored in a variable, e.g.:
+ *
+ * $name = '_SERVER';
+ * $array = $$name;
+ *
+ * This code does not work when run from within a method (only when run
+ * in global scope). But the following code does work:
+ *
+ * $name = '_SERVER';
+ * global $$name;
+ * $array = $$name;
+ *
+ * That's why global is used here.
+ */
+ global ${$this->name};
- /*
- * There is a bug in PHP which doesn't allow superglobals to be
- * accessed when their name is stored in a variable, e.g.:
- *
- * $name = '_SERVER';
- * $array = $$name;
- *
- * This code does not work when run from within a method (only when run
- * in global scope). But the following code does work:
- *
- * $name = '_SERVER';
- * global $$name;
- * $array = $$name;
- *
- * That's why global is used here.
- */
- global ${$this->name};
+ // Check the given superglobal exists. It is possible that it is not initialized.
+ if (!isset(${$this->name})) {
+ $class = basename(get_class($this));
+ trigger_error("log4php: $class: Cannot find superglobal variable \${$this->name}.", E_USER_WARNING);
- // Check the given superglobal exists. It is possible that it is not initialized.
- if (!isset(${$this->name})) {
- $class = basename(get_class($this));
- trigger_error("log4php: $class: Cannot find superglobal variable \${$this->name}.", E_USER_WARNING);
- return;
- }
+ return;
+ }
- $source = ${$this->name};
+ $source = ${$this->name};
- // When the key is set, display the matching value
- if (isset($key)) {
- if (isset($source[$key])) {
- $this->value = $source[$key];
- }
- }
+ // When the key is set, display the matching value
+ if (isset($key)) {
+ if (isset($source[$key])) {
+ $this->value = $source[$key];
+ }
+ }
- // When the key is not set, display all values
- else {
- $values = array();
- foreach($source as $key => $value) {
- $values[] = "$key=$value";
- }
- $this->value = implode(', ', $values);
- }
- }
+ // When the key is not set, display all values
+ else {
+ $values = array();
+ foreach ($source as $key => $value) {
+ $values[] = "$key=$value";
+ }
+ $this->value = implode(', ', $values);
+ }
+ }
- public function convert(LoggingEvent $event) {
- return $this->value;
- }
+ public function convert(LoggingEvent $event)
+ {
+ return $this->value;
+ }
}
diff --git a/src/Pattern/ThrowableConverter.php b/src/Pattern/ThrowableConverter.php
index f18e322..8f12a84 100644
--- a/src/Pattern/ThrowableConverter.php
+++ b/src/Pattern/ThrowableConverter.php
@@ -22,14 +22,17 @@
* Returns the throwable information linked to the logging event, if any.
* @since 2.3
*/
-class ThrowableConverter extends AbstractConverter {
+class ThrowableConverter extends AbstractConverter
+{
+ public function convert(LoggingEvent $event)
+ {
+ $info = $event->getThrowableInformation();
+ if (isset($info)) {
+ $ex = $info->getThrowable();
- public function convert(LoggingEvent $event) {
- $info = $event->getThrowableInformation();
- if (isset($info)) {
- $ex = $info->getThrowable();
- return (string) $ex . PHP_EOL;
- }
- return '';
- }
+ return (string) $ex . PHP_EOL;
+ }
+
+ return '';
+ }
}
diff --git a/src/ReflectionUtils.php b/src/ReflectionUtils.php
index cc39ec3..38793fd 100644
--- a/src/ReflectionUtils.php
+++ b/src/ReflectionUtils.php
@@ -21,131 +21,140 @@
/**
* Provides methods for reflective use on php objects
*/
-class ReflectionUtils {
+class ReflectionUtils
+{
+ /** the target object */
+ private $obj;
- /** the target object */
- private $obj;
+ /**
+ * Create a new ReflectionUtils for the specified Object.
+ * This is done in prepartion for invoking {@link setProperty()}
+ * one or more times.
+ * @param object &$obj the object for which to set properties
+ */
+ public function __construct($obj)
+ {
+ $this->obj = $obj;
+ }
- /**
- * Create a new ReflectionUtils for the specified Object.
- * This is done in prepartion for invoking {@link setProperty()}
- * one or more times.
- * @param object &$obj the object for which to set properties
- */
- public function __construct($obj) {
- $this->obj = $obj;
- }
+ /**
+ * Set the properties of an object passed as a parameter in one
+ * go. The <code>properties</code> are parsed relative to a
+ * <code>prefix</code>.
+ *
+ * @param object $obj The object to configure.
+ * @param array $properties An array containing keys and values.
+ * @param string $prefix Only keys having the specified prefix will be set.
+ */
+ // TODO: check, if this is really useful
+ public static function setPropertiesByObject($obj, $properties, $prefix)
+ {
+ $pSetter = new ReflectionUtils($obj);
- /**
- * Set the properties of an object passed as a parameter in one
- * go. The <code>properties</code> are parsed relative to a
- * <code>prefix</code>.
- *
- * @param object $obj The object to configure.
- * @param array $properties An array containing keys and values.
- * @param string $prefix Only keys having the specified prefix will be set.
- */
- // TODO: check, if this is really useful
- public static function setPropertiesByObject($obj, $properties, $prefix) {
- $pSetter = new ReflectionUtils($obj);
- return $pSetter->setProperties($properties, $prefix);
- }
+ return $pSetter->setProperties($properties, $prefix);
+ }
- /**
- * Set the properites for the object that match the
- * <code>prefix</code> passed as parameter.
- *
- * Example:
- *
- * $arr['xxxname'] = 'Joe';
- * $arr['xxxmale'] = true;
- * and prefix xxx causes setName and setMale.
- *
- * @param array $properties An array containing keys and values.
- * @param string $prefix Only keys having the specified prefix will be set.
- */
- public function setProperties($properties, $prefix) {
- $len = strlen($prefix);
- reset($properties);
- while(list($key,) = each($properties)) {
- if(strpos($key, $prefix) === 0) {
- if(strpos($key, '.', ($len + 1)) > 0) {
- continue;
- }
- $value = $properties[$key];
- $key = substr($key, $len);
- if($key == 'layout' and ($this->obj instanceof Appender)) {
- continue;
- }
- $this->setProperty($key, $value);
- }
- }
- $this->activate();
- }
+ /**
+ * Set the properites for the object that match the
+ * <code>prefix</code> passed as parameter.
+ *
+ * Example:
+ *
+ * $arr['xxxname'] = 'Joe';
+ * $arr['xxxmale'] = true;
+ * and prefix xxx causes setName and setMale.
+ *
+ * @param array $properties An array containing keys and values.
+ * @param string $prefix Only keys having the specified prefix will be set.
+ */
+ public function setProperties($properties, $prefix)
+ {
+ $len = strlen($prefix);
+ reset($properties);
+ while (list($key,) = each($properties)) {
+ if (strpos($key, $prefix) === 0) {
+ if (strpos($key, '.', ($len + 1)) > 0) {
+ continue;
+ }
+ $value = $properties[$key];
+ $key = substr($key, $len);
+ if ($key == 'layout' and ($this->obj instanceof Appender)) {
+ continue;
+ }
+ $this->setProperty($key, $value);
+ }
+ }
+ $this->activate();
+ }
- /**
- * Set a property on this PropertySetter's Object. If successful, this
- * method will invoke a setter method on the underlying Object. The
- * setter is the one for the specified property name and the value is
- * determined partly from the setter argument type and partly from the
- * value specified in the call to this method.
- *
- * <p>If the setter expects a String no conversion is necessary.
- * If it expects an int, then an attempt is made to convert 'value'
- * to an int using new Integer(value). If the setter expects a boolean,
- * the conversion is by new Boolean(value).
- *
- * @param string $name name of the property
- * @param string $value String value of the property
- */
- public function setProperty($name, $value) {
- if($value === null) {
- return;
- }
+ /**
+ * Set a property on this PropertySetter's Object. If successful, this
+ * method will invoke a setter method on the underlying Object. The
+ * setter is the one for the specified property name and the value is
+ * determined partly from the setter argument type and partly from the
+ * value specified in the call to this method.
+ *
+ * <p>If the setter expects a String no conversion is necessary.
+ * If it expects an int, then an attempt is made to convert 'value'
+ * to an int using new Integer(value). If the setter expects a boolean,
+ * the conversion is by new Boolean(value).
+ *
+ * @param string $name name of the property
+ * @param string $value String value of the property
+ */
+ public function setProperty($name, $value)
+ {
+ if ($value === null) {
+ return;
+ }
- $method = "set" . ucfirst($name);
+ $method = "set" . ucfirst($name);
- if(!method_exists($this->obj, $method)) {
- throw new Exception("Error setting log4php property $name to $value: no method $method in class ".get_class($this->obj)."!");
- } else {
- return call_user_func(array($this->obj, $method), $value);
- }
- }
+ if (!method_exists($this->obj, $method)) {
+ throw new Exception("Error setting log4php property $name to $value: no method $method in class ".get_class($this->obj)."!");
+ } else {
+ return call_user_func(array($this->obj, $method), $value);
+ }
+ }
- public function activate() {
- if(method_exists($this->obj, 'activateoptions')) {
- return call_user_func(array($this->obj, 'activateoptions'));
- }
- }
+ public function activate()
+ {
+ if (method_exists($this->obj, 'activateoptions')) {
+ return call_user_func(array($this->obj, 'activateoptions'));
+ }
+ }
- /**
- * Creates an instances from the given class name.
- *
- * @param string $classname
- * @return an object from the class with the given classname
- */
- public static function createObject($class) {
- if(!empty($class)) {
- return new $class();
- }
- return null;
- }
+ /**
+ * Creates an instances from the given class name.
+ *
+ * @param string $classname
+ * @return an object from the class with the given classname
+ */
+ public static function createObject($class)
+ {
+ if (!empty($class)) {
+ return new $class();
+ }
- /**
- * @param object $object
- * @param string $name
- * @param mixed $value
- */
- public static function setter($object, $name, $value) {
- if (empty($name)) {
- return false;
- }
- $methodName = 'set'.ucfirst($name);
- if (method_exists($object, $methodName)) {
- return call_user_func(array($object, $methodName), $value);
- } else {
- return false;
- }
- }
+ return null;
+ }
+
+ /**
+ * @param object $object
+ * @param string $name
+ * @param mixed $value
+ */
+ public static function setter($object, $name, $value)
+ {
+ if (empty($name)) {
+ return false;
+ }
+ $methodName = 'set'.ucfirst($name);
+ if (method_exists($object, $methodName)) {
+ return call_user_func(array($object, $methodName), $value);
+ } else {
+ return false;
+ }
+ }
}
diff --git a/src/Renderers/DefaultRenderer.php b/src/Renderers/DefaultRenderer.php
index 78b844c..6d1a2be 100644
--- a/src/Renderers/DefaultRenderer.php
+++ b/src/Renderers/DefaultRenderer.php
@@ -24,10 +24,11 @@
* Renders the input using <var>print_r</var>.
* @since 0.3
*/
-class DefaultRenderer implements RendererInterface {
-
- /** @inheritdoc */
- public function render($input) {
- return print_r($input, true);
- }
+class DefaultRenderer implements RendererInterface
+{
+ /** @inheritdoc */
+ public function render($input)
+ {
+ return print_r($input, true);
+ }
}
diff --git a/src/Renderers/ExceptionRenderer.php b/src/Renderers/ExceptionRenderer.php
index d625ae8..ad9b09f 100644
--- a/src/Renderers/ExceptionRenderer.php
+++ b/src/Renderers/ExceptionRenderer.php
@@ -22,12 +22,12 @@
* Renderer used for Exceptions.
* @since 2.1
*/
-class ExceptionRenderer implements RendererInterface {
-
- public function render($input) {
-
- // Exception class has a very decent __toString method
- // so let's just use that instead of writing lots of code.
- return (string) $input;
- }
+class ExceptionRenderer implements RendererInterface
+{
+ public function render($input)
+ {
+ // Exception class has a very decent __toString method
+ // so let's just use that instead of writing lots of code.
+ return (string) $input;
+ }
}
diff --git a/src/Renderers/RendererInterface.php b/src/Renderers/RendererInterface.php
index 8bfda22..ad96b85 100644
--- a/src/Renderers/RendererInterface.php
+++ b/src/Renderers/RendererInterface.php
@@ -22,11 +22,12 @@
* Implement this interface in order to render objects to strings.
* @since 0.3
*/
-interface RendererInterface {
- /**
- * Renders the entity passed as <var>input</var> to a string.
- * @param mixed $input The entity to render.
- * @return string The rendered string.
- */
- public function render($input);
+interface RendererInterface
+{
+ /**
+ * Renders the entity passed as <var>input</var> to a string.
+ * @param mixed $input The entity to render.
+ * @return string The rendered string.
+ */
+ public function render($input);
}
diff --git a/src/Renderers/RendererMap.php b/src/Renderers/RendererMap.php
index 1444d25..1165720 100644
--- a/src/Renderers/RendererMap.php
+++ b/src/Renderers/RendererMap.php
@@ -23,167 +23,180 @@
* input.
* @since 0.3
*/
-class RendererMap {
+class RendererMap
+{
+ /**
+ * Maps class names to appropriate renderers.
+ * @var array
+ */
+ private $map = array();
- /**
- * Maps class names to appropriate renderers.
- * @var array
- */
- private $map = array();
+ /**
+ * The default renderer to use if no specific renderer is found.
+ * @var RendererInterface
+ */
+ private $defaultRenderer;
- /**
- * The default renderer to use if no specific renderer is found.
- * @var RendererInterface
- */
- private $defaultRenderer;
+ public function __construct()
+ {
+ // Set default config
+ $this->reset();
+ }
- public function __construct() {
+ /**
+ * Adds a renderer to the map.
+ *
+ * If a renderer already exists for the given <var>$renderedClass</var> it
+ * will be overwritten without warning.
+ *
+ * @param string $renderedClass The name of the class which will be
+ * rendered by the renderer.
+ * @param string $renderingClass The name of the class which will
+ * perform the rendering.
+ */
+ public function addRenderer($renderedClass, $renderingClass)
+ {
+ if (class_exists($renderingClass)) {
+ $renderer = new $renderingClass();
+ } else {
+ // Try to find renderer in the default namespace
+ $namespaced = "Apache\\Log4php\\Renderers\\$renderingClass";
+ if (class_exists($namespaced)) {
+ $renderer = new $namespaced();
+ }
+ }
- // Set default config
- $this->reset();
- }
+ if (!isset($renderer)) {
+ trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] not found.");
- /**
- * Adds a renderer to the map.
- *
- * If a renderer already exists for the given <var>$renderedClass</var> it
- * will be overwritten without warning.
- *
- * @param string $renderedClass The name of the class which will be
- * rendered by the renderer.
- * @param string $renderingClass The name of the class which will
- * perform the rendering.
- */
- public function addRenderer($renderedClass, $renderingClass) {
+ return;
+ }
- if (class_exists($renderingClass)) {
- $renderer = new $renderingClass();
- } else {
- // Try to find renderer in the default namespace
- $namespaced = "Apache\\Log4php\\Renderers\\$renderingClass";
- if (class_exists($namespaced)) {
- $renderer = new $namespaced();
- }
- }
+ // Check the class implements the right interface
+ if (!($renderer instanceof RendererInterface)) {
+ trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] does not implement the RendererInterface interface.");
- if (!isset($renderer)) {
- trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] not found.");
- return;
- }
+ return;
+ }
- // Check the class implements the right interface
- if (!($renderer instanceof RendererInterface)) {
- trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] does not implement the RendererInterface interface.");
- return;
- }
+ // Convert to lowercase since class names in PHP are not case sensitive
+ $renderedClass = strtolower($renderedClass);
- // Convert to lowercase since class names in PHP are not case sensitive
- $renderedClass = strtolower($renderedClass);
+ $this->map[$renderedClass] = $renderer;
+ }
- $this->map[$renderedClass] = $renderer;
- }
+ /**
+ * Sets a custom default renderer class.
+ *
+ * TODO: there's code duplication here. This method is almost identical to
+ * addRenderer(). However, it has custom error messages so let it sit for
+ * now.
+ *
+ * @param string $renderingClass The name of the class which will
+ * perform the rendering.
+ */
+ public function setDefaultRenderer($renderingClass)
+ {
+ // Check the class exists
+ if (!class_exists($renderingClass)) {
+ trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] not found.");
- /**
- * Sets a custom default renderer class.
- *
- * TODO: there's code duplication here. This method is almost identical to
- * addRenderer(). However, it has custom error messages so let it sit for
- * now.
- *
- * @param string $renderingClass The name of the class which will
- * perform the rendering.
- */
- public function setDefaultRenderer($renderingClass) {
- // Check the class exists
- if (!class_exists($renderingClass)) {
- trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] not found.");
- return;
- }
+ return;
+ }
- // Create the instance
- $renderer = new $renderingClass();
+ // Create the instance
+ $renderer = new $renderingClass();
- // Check the class implements the right interface
- if (!($renderer instanceof RendererInterface)) {
- trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] does not implement the RendererInterface interface.");
- return;
- }
+ // Check the class implements the right interface
+ if (!($renderer instanceof RendererInterface)) {
+ trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] does not implement the RendererInterface interface.");
- $this->defaultRenderer = $renderer;
- }
+ return;
+ }
- /**
- * Returns the default renderer.
- * @var RendererInterface
- */
- public function getDefaultRenderer() {
- return $this->defaultRenderer;
- }
+ $this->defaultRenderer = $renderer;
+ }
- /**
- * Finds the appropriate renderer for the given <var>input</var>, and
- * renders it (i.e. converts it to a string).
- *
- * @param mixed $input Input to render.
- * @return string The rendered contents.
- */
- public function findAndRender($input) {
- if ($input === null) {
- return null;
- }
+ /**
+ * Returns the default renderer.
+ * @var RendererInterface
+ */
+ public function getDefaultRenderer()
+ {
+ return $this->defaultRenderer;
+ }
- // For objects, try to find a renderer in the map
- if(is_object($input)) {
- $renderer = $this->getByClassName(get_class($input));
- if (isset($renderer)) {
- return $renderer->render($input);
- }
- }
+ /**
+ * Finds the appropriate renderer for the given <var>input</var>, and
+ * renders it (i.e. converts it to a string).
+ *
+ * @param mixed $input Input to render.
+ * @return string The rendered contents.
+ */
+ public function findAndRender($input)
+ {
+ if ($input === null) {
+ return null;
+ }
- // Fall back to the default renderer
- return $this->defaultRenderer->render($input);
- }
+ // For objects, try to find a renderer in the map
+ if (is_object($input)) {
+ $renderer = $this->getByClassName(get_class($input));
+ if (isset($renderer)) {
+ return $renderer->render($input);
+ }
+ }
- /**
- * Returns the appropriate renderer for a given object.
- *
- * @param mixed $object
- * @return RendererInterface Or null if none found.
- */
- public function getByObject($object) {
- if (!is_object($object)) {
- return null;
- }
- return $this->getByClassName(get_class($object));
- }
+ // Fall back to the default renderer
+ return $this->defaultRenderer->render($input);
+ }
- /**
- * Returns the appropriate renderer for a given class name.
- *
- * If no renderer could be found, returns NULL.
- *
- * @param string $class
- * @return LoggerRendererObject Or null if not found.
- */
- public function getByClassName($class) {
- for(; !empty($class); $class = get_parent_class($class)) {
- $class = strtolower($class);
- if(isset($this->map[$class])) {
- return $this->map[$class];
- }
- }
- return null;
- }
+ /**
+ * Returns the appropriate renderer for a given object.
+ *
+ * @param mixed $object
+ * @return RendererInterface Or null if none found.
+ */
+ public function getByObject($object)
+ {
+ if (!is_object($object)) {
+ return null;
+ }
- /** Empties the renderer map. */
- public function clear() {
- $this->map = array();
- }
+ return $this->getByClassName(get_class($object));
+ }
- /** Resets the renderer map to it's default configuration. */
- public function reset() {
- $this->defaultRenderer = new DefaultRenderer();
- $this->clear();
- $this->addRenderer('Exception', 'ExceptionRenderer');
- }
+ /**
+ * Returns the appropriate renderer for a given class name.
+ *
+ * If no renderer could be found, returns NULL.
+ *
+ * @param string $class
+ * @return LoggerRendererObject Or null if not found.
+ */
+ public function getByClassName($class)
+ {
+ for (; !empty($class); $class = get_parent_class($class)) {
+ $class = strtolower($class);
+ if (isset($this->map[$class])) {
+ return $this->map[$class];
+ }
+ }
+
+ return null;
+ }
+
+ /** Empties the renderer map. */
+ public function clear()
+ {
+ $this->map = array();
+ }
+
+ /** Resets the renderer map to it's default configuration. */
+ public function reset()
+ {
+ $this->defaultRenderer = new DefaultRenderer();
+ $this->clear();
+ $this->addRenderer('Exception', 'ExceptionRenderer');
+ }
}
diff --git a/src/RootLogger.php b/src/RootLogger.php
index ba7f5c3..bd9b089 100644
--- a/src/RootLogger.php
+++ b/src/RootLogger.php
@@ -24,46 +24,50 @@
*/
class RootLogger extends Logger
{
- /**
- * Constructor
- *
- * @param integer $level initial log level
- */
- public function __construct(Level $level = null) {
- parent::__construct('root');
+ /**
+ * Constructor
+ *
+ * @param integer $level initial log level
+ */
+ public function __construct(Level $level = null)
+ {
+ parent::__construct('root');
- if($level == null) {
- $level = Level::getLevelAll();
- }
- $this->setLevel($level);
- }
+ if ($level == null) {
+ $level = Level::getLevelAll();
+ }
+ $this->setLevel($level);
+ }
- /**
- * @return Level the level
- */
- public function getEffectiveLevel() {
- return $this->getLevel();
- }
+ /**
+ * @return Level the level
+ */
+ public function getEffectiveLevel()
+ {
+ return $this->getLevel();
+ }
- /**
- * Override level setter to prevent setting the root logger's level to
- * null. Root logger must always have a level.
- *
- * @param Level $level
- */
- public function setLevel(Level $level = null) {
- if (isset($level)) {
- parent::setLevel($level);
- } else {
- trigger_error("log4php: Cannot set RootLogger level to null.", E_USER_WARNING);
- }
- }
+ /**
+ * Override level setter to prevent setting the root logger's level to
+ * null. Root logger must always have a level.
+ *
+ * @param Level $level
+ */
+ public function setLevel(Level $level = null)
+ {
+ if (isset($level)) {
+ parent::setLevel($level);
+ } else {
+ trigger_error("log4php: Cannot set RootLogger level to null.", E_USER_WARNING);
+ }
+ }
- /**
- * Override parent setter. Root logger cannot have a parent.
- * @param Logger $parent
- */
- public function setParent(Logger $parent) {
- trigger_error("log4php: RootLogger cannot have a parent.", E_USER_WARNING);
- }
+ /**
+ * Override parent setter. Root logger cannot have a parent.
+ * @param Logger $parent
+ */
+ public function setParent(Logger $parent)
+ {
+ trigger_error("log4php: RootLogger cannot have a parent.", E_USER_WARNING);
+ }
}
diff --git a/src/ThrowableInformation.php b/src/ThrowableInformation.php
index e2befeb..255c0b8 100644
--- a/src/ThrowableInformation.php
+++ b/src/ThrowableInformation.php
@@ -25,43 +25,46 @@
*/
class ThrowableInformation
{
- /** @var Exception Throwable to log */
- private $throwable;
+ /** @var Exception Throwable to log */
+ private $throwable;
- /** @var array Array of throwable messages */
- private $throwableArray;
+ /** @var array Array of throwable messages */
+ private $throwableArray;
- /**
- * Create a new instance
- *
- * @param $throwable - a throwable as a exception
- * @param $logger - Logger reference
- */
- public function __construct(\Exception $throwable) {
- $this->throwable = $throwable;
- }
+ /**
+ * Create a new instance
+ *
+ * @param $throwable - a throwable as a exception
+ * @param $logger - Logger reference
+ */
+ public function __construct(\Exception $throwable)
+ {
+ $this->throwable = $throwable;
+ }
- /**
- * Return source exception
- *
- * @return Exception
- */
- public function getThrowable() {
- return $this->throwable;
- }
+ /**
+ * Return source exception
+ *
+ * @return Exception
+ */
+ public function getThrowable()
+ {
+ return $this->throwable;
+ }
- /**
- * @desc Returns string representation of throwable
- *
- * @return array
- */
- public function getStringRepresentation() {
- if (!is_array($this->throwableArray)) {
- $renderer = new Renderers\ExceptionRenderer();
+ /**
+ * @desc Returns string representation of throwable
+ *
+ * @return array
+ */
+ public function getStringRepresentation()
+ {
+ if (!is_array($this->throwableArray)) {
+ $renderer = new Renderers\ExceptionRenderer();
- $this->throwableArray = explode("\n", $renderer->render($this->throwable));
- }
+ $this->throwableArray = explode("\n", $renderer->render($this->throwable));
+ }
- return $this->throwableArray;
- }
+ return $this->throwableArray;
+ }
}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index b95c505..3d81583 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -30,7 +30,7 @@
// Define a temp dir where tests may write to
$tmpDir = __DIR__ . '/../target/temp/phpunit';
if (!is_dir($tmpDir)) {
- mkdir($tmpDir, 0777, true);
+ mkdir($tmpDir, 0777, true);
}
define('PHPUNIT_TEMP_DIR', realpath($tmpDir));
diff --git a/tests/resources/configs/adapters/php/config_empty.php b/tests/resources/configs/adapters/php/config_empty.php
index 5ca9004..eaf556c 100644
--- a/tests/resources/configs/adapters/php/config_empty.php
+++ b/tests/resources/configs/adapters/php/config_empty.php
@@ -1,26 +1,24 @@
-<?php
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @category tests
- * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
- * @link http://logging.apache.org/log4php
- */
-
-// Empty config
-
-?>
\ No newline at end of file
+<?php
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @category tests
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
+ * @link http://logging.apache.org/log4php
+ */
+
+// Empty config
diff --git a/tests/resources/configs/adapters/php/config_invalid_syntax.php b/tests/resources/configs/adapters/php/config_invalid_syntax.php
index 5019f68..49df5f4 100644
--- a/tests/resources/configs/adapters/php/config_invalid_syntax.php
+++ b/tests/resources/configs/adapters/php/config_invalid_syntax.php
@@ -1,40 +1,38 @@
-<?php
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @category tests
- * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
- * @link http://logging.apache.org/log4php
- */
-
-return array(
- 'rootLogger' => array(
- 'level' => 'info',
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- )
- )
- )
-
-// Invalid file - no closing brace.
-
-?>
\ No newline at end of file
+<?php
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @category tests
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
+ * @link http://logging.apache.org/log4php
+ */
+
+return array(
+ 'rootLogger' => array(
+ 'level' => 'info',
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ )
+ )
+ )
+
+// Invalid file - no closing brace.
diff --git a/tests/resources/configs/adapters/php/config_not_an_array.php b/tests/resources/configs/adapters/php/config_not_an_array.php
index 030bb10..a4b3945 100644
--- a/tests/resources/configs/adapters/php/config_not_an_array.php
+++ b/tests/resources/configs/adapters/php/config_not_an_array.php
@@ -1,27 +1,25 @@
-<?php
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @category tests
- * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
- * @link http://logging.apache.org/log4php
- */
-
-// Not an array
-return new Exception();
-
-?>
\ No newline at end of file
+<?php
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @category tests
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
+ * @link http://logging.apache.org/log4php
+ */
+
+// Not an array
+return new Exception();
diff --git a/tests/resources/configs/adapters/php/config_valid.php b/tests/resources/configs/adapters/php/config_valid.php
index bfabfce..6485239 100644
--- a/tests/resources/configs/adapters/php/config_valid.php
+++ b/tests/resources/configs/adapters/php/config_valid.php
@@ -1,40 +1,38 @@
-<?php
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @category tests
- * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
- * @link http://logging.apache.org/log4php
- */
-
-return array(
- 'rootLogger' => array(
- 'level' => 'info',
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- )
- )
- )
-)
-;
-
-?>
\ No newline at end of file
+<?php
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @category tests
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
+ * @link http://logging.apache.org/log4php
+ */
+
+return array(
+ 'rootLogger' => array(
+ 'level' => 'info',
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ )
+ )
+ )
+)
+;
diff --git a/tests/resources/configs/adapters/xml/config_duplicate_logger.xml b/tests/resources/configs/adapters/xml/config_duplicate_logger.xml
index 978b9c7..db60593 100644
--- a/tests/resources/configs/adapters/xml/config_duplicate_logger.xml
+++ b/tests/resources/configs/adapters/xml/config_duplicate_logger.xml
@@ -1,39 +1,39 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
-
- <appender name="default" class="EchoAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <!-- Duplicate logger -->
- <logger name="foo">
- <level value="info" />
- <appender_ref ref="default" />
- </logger>
-
- <logger name="foo">
- <level value="warn" />
- <appender_ref ref="default" />
- </logger>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
\ No newline at end of file
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+
+ <appender name="default" class="EchoAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <!-- Duplicate logger -->
+ <logger name="foo">
+ <level value="info" />
+ <appender_ref ref="default" />
+ </logger>
+
+ <logger name="foo">
+ <level value="warn" />
+ <appender_ref ref="default" />
+ </logger>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/adapters/xml/config_duplicate_renderer.xml b/tests/resources/configs/adapters/xml/config_duplicate_renderer.xml
index 4ac97bc..a79b0e0 100644
--- a/tests/resources/configs/adapters/xml/config_duplicate_renderer.xml
+++ b/tests/resources/configs/adapters/xml/config_duplicate_renderer.xml
@@ -1,30 +1,30 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration>
- <!-- Duplicate renderer -->
- <renderer renderedClass="Fruit" renderingClass="FruitRenderer1" />
- <renderer renderedClass="Fruit" renderingClass="FruitRenderer2" />
- <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
- <appender name="default" class="EchoAppender">
- <layout class="SimpleLayout"/>
- </appender>
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration>
+ <!-- Duplicate renderer -->
+ <renderer renderedClass="Fruit" renderingClass="FruitRenderer1" />
+ <renderer renderedClass="Fruit" renderingClass="FruitRenderer2" />
+ <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
+ <appender name="default" class="EchoAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/adapters/xml/config_invalid_syntax.xml b/tests/resources/configs/adapters/xml/config_invalid_syntax.xml
index 6592fa5..1e2c3c1 100644
--- a/tests/resources/configs/adapters/xml/config_invalid_syntax.xml
+++ b/tests/resources/configs/adapters/xml/config_invalid_syntax.xml
@@ -1,39 +1,39 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <appender name="default" class="EchoAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <!-- Duplicate logger -->
- <logger name="foo">
- <level value="info" />
- <appender_ref ref="default" />
- </logger>
-
- <logger name="foo">
- <level value="warn" />
- <appender_ref ref="default" />
- </logger>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-
- <!-- Invalid XML file for testing -->
\ No newline at end of file
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <appender name="default" class="EchoAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <!-- Duplicate logger -->
+ <logger name="foo">
+ <level value="info" />
+ <appender_ref ref="default" />
+ </logger>
+
+ <logger name="foo">
+ <level value="warn" />
+ <appender_ref ref="default" />
+ </logger>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+
+ <!-- Invalid XML file for testing -->
diff --git a/tests/resources/configs/adapters/xml/config_valid.xml b/tests/resources/configs/adapters/xml/config_valid.xml
index 6553c44..bb326a6 100644
--- a/tests/resources/configs/adapters/xml/config_valid.xml
+++ b/tests/resources/configs/adapters/xml/config_valid.xml
@@ -1,54 +1,54 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
- <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
- <appender name="default" class="EchoAppender">
- <layout class="LoggerLayoutTTCC"/>
- <filter class="LevelRangeFilter">
- <param name="levelMin" value="ERROR" />
- <param name="levelMax" value="FATAL" />
- <param name="acceptOnMatch" value="false" />
- </filter>
- <filter class="DenyAllFilter" />
- </appender>
- <appender name="file" class="DailyFileAppender" threshold="warn">
- <param name="datePattern" value="Ymd" />
- <param name="file" value="target/examples/daily_%s.log" />
- <layout class="PatternLayout">
- <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
- </layout>
- </appender>
- <logger name="foo.bar.baz" additivity="false">
- <level value="trace" />
- <appender_ref ref="default" />
- </logger>
- <logger name="foo.bar" additivity="true">
- <level value="debug" />
- <appender_ref ref="file" />
- </logger>
- <logger name="foo">
- <level value="warn" />
- <appender_ref ref="default" />
- <appender_ref ref="file" />
- </logger>
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
+ <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
+ <appender name="default" class="EchoAppender">
+ <layout class="LoggerLayoutTTCC"/>
+ <filter class="LevelRangeFilter">
+ <param name="levelMin" value="ERROR" />
+ <param name="levelMax" value="FATAL" />
+ <param name="acceptOnMatch" value="false" />
+ </filter>
+ <filter class="DenyAllFilter" />
+ </appender>
+ <appender name="file" class="DailyFileAppender" threshold="warn">
+ <param name="datePattern" value="Ymd" />
+ <param name="file" value="target/examples/daily_%s.log" />
+ <layout class="PatternLayout">
+ <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
+ </layout>
+ </appender>
+ <logger name="foo.bar.baz" additivity="false">
+ <level value="trace" />
+ <appender_ref ref="default" />
+ </logger>
+ <logger name="foo.bar" additivity="true">
+ <level value="debug" />
+ <appender_ref ref="file" />
+ </logger>
+ <logger name="foo">
+ <level value="warn" />
+ <appender_ref ref="default" />
+ <appender_ref ref="file" />
+ </logger>
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/adapters/xml/config_valid_underscore.xml b/tests/resources/configs/adapters/xml/config_valid_underscore.xml
index 4ff6e21..179629e 100644
--- a/tests/resources/configs/adapters/xml/config_valid_underscore.xml
+++ b/tests/resources/configs/adapters/xml/config_valid_underscore.xml
@@ -1,57 +1,57 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<!-- Same as config_valid.xml but uses appender-ref instead of appender_ref -->
-
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
- <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
- <appender name="default" class="EchoAppender">
- <layout class="LoggerLayoutTTCC"/>
- <filter class="LevelRangeFilter">
- <param name="levelMin" value="ERROR" />
- <param name="levelMax" value="FATAL" />
- <param name="acceptOnMatch" value="false" />
- </filter>
- <filter class="DenyAllFilter" />
- </appender>
- <appender name="file" class="DailyFileAppender" threshold="warn">
- <param name="datePattern" value="Ymd" />
- <param name="file" value="target/examples/daily_%s.log" />
- <layout class="PatternLayout">
- <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
- </layout>
- </appender>
- <logger name="foo.bar.baz" additivity="false">
- <level value="trace" />
- <appender-ref ref="default" />
- </logger>
- <logger name="foo.bar" additivity="true">
- <level value="debug" />
- <appender-ref ref="file" />
- </logger>
- <logger name="foo">
- <level value="warn" />
- <appender-ref ref="default" />
- <appender-ref ref="file" />
- </logger>
- <root>
- <level value="DEBUG" />
- <appender-ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Same as config_valid.xml but uses appender-ref instead of appender_ref -->
+
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
+ <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
+ <appender name="default" class="EchoAppender">
+ <layout class="LoggerLayoutTTCC"/>
+ <filter class="LevelRangeFilter">
+ <param name="levelMin" value="ERROR" />
+ <param name="levelMax" value="FATAL" />
+ <param name="acceptOnMatch" value="false" />
+ </filter>
+ <filter class="DenyAllFilter" />
+ </appender>
+ <appender name="file" class="DailyFileAppender" threshold="warn">
+ <param name="datePattern" value="Ymd" />
+ <param name="file" value="target/examples/daily_%s.log" />
+ <layout class="PatternLayout">
+ <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
+ </layout>
+ </appender>
+ <logger name="foo.bar.baz" additivity="false">
+ <level value="trace" />
+ <appender-ref ref="default" />
+ </logger>
+ <logger name="foo.bar" additivity="true">
+ <level value="debug" />
+ <appender-ref ref="file" />
+ </logger>
+ <logger name="foo">
+ <level value="warn" />
+ <appender-ref ref="default" />
+ <appender-ref ref="file" />
+ </logger>
+ <root>
+ <level value="DEBUG" />
+ <appender-ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_invalid_appender_class.xml b/tests/resources/configs/appenders/config_invalid_appender_class.xml
index db3ccf0..0f72552 100644
--- a/tests/resources/configs/appenders/config_invalid_appender_class.xml
+++ b/tests/resources/configs/appenders/config_invalid_appender_class.xml
@@ -1,25 +1,25 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <appender name="foo" class="stdClass"/>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <appender name="foo" class="stdClass"/>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_invalid_filter_class.xml b/tests/resources/configs/appenders/config_invalid_filter_class.xml
index 80c9736..cc9b958 100644
--- a/tests/resources/configs/appenders/config_invalid_filter_class.xml
+++ b/tests/resources/configs/appenders/config_invalid_filter_class.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <filter class="stdClass" />
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <filter class="stdClass" />
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_invalid_filter_parameters.xml b/tests/resources/configs/appenders/config_invalid_filter_parameters.xml
index d17183d..af23f3e 100644
--- a/tests/resources/configs/appenders/config_invalid_filter_parameters.xml
+++ b/tests/resources/configs/appenders/config_invalid_filter_parameters.xml
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <filter class="StringMatchFilter">
- <param name="fooParameter" value="bar" />
- </filter>
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <filter class="StringMatchFilter">
+ <param name="fooParameter" value="bar" />
+ </filter>
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_invalid_layout_class.xml b/tests/resources/configs/appenders/config_invalid_layout_class.xml
index 308243f..4713f72 100644
--- a/tests/resources/configs/appenders/config_invalid_layout_class.xml
+++ b/tests/resources/configs/appenders/config_invalid_layout_class.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="stdClass" />
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="stdClass" />
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_no_class.xml b/tests/resources/configs/appenders/config_no_class.xml
index 1e581f3..d0804b0 100644
--- a/tests/resources/configs/appenders/config_no_class.xml
+++ b/tests/resources/configs/appenders/config_no_class.xml
@@ -1,26 +1,26 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
-
- <appender name="foo" />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+
+ <appender name="foo" />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_no_layout_class.xml b/tests/resources/configs/appenders/config_no_layout_class.xml
index 035226b..bf2df80 100644
--- a/tests/resources/configs/appenders/config_no_layout_class.xml
+++ b/tests/resources/configs/appenders/config_no_layout_class.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="" />
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="" />
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_not_existing_class.xml b/tests/resources/configs/appenders/config_not_existing_class.xml
index ec5aae0..6a9a80d 100644
--- a/tests/resources/configs/appenders/config_not_existing_class.xml
+++ b/tests/resources/configs/appenders/config_not_existing_class.xml
@@ -1,25 +1,25 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <appender name="foo" class="unknownClass"/>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <appender name="foo" class="unknownClass"/>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_not_existing_filter_class.xml b/tests/resources/configs/appenders/config_not_existing_filter_class.xml
index 1d4e1ea..8be90e6 100644
--- a/tests/resources/configs/appenders/config_not_existing_filter_class.xml
+++ b/tests/resources/configs/appenders/config_not_existing_filter_class.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <filter class="Foo" />
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <filter class="Foo" />
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/appenders/config_not_existing_layout_class.xml b/tests/resources/configs/appenders/config_not_existing_layout_class.xml
index 5fc72a5..dcee56d 100644
--- a/tests/resources/configs/appenders/config_not_existing_layout_class.xml
+++ b/tests/resources/configs/appenders/config_not_existing_layout_class.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="Foo" />
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="Foo" />
+ </appender>
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/config.yml b/tests/resources/configs/config.yml
index 07b86fb..03803a9 100644
--- a/tests/resources/configs/config.yml
+++ b/tests/resources/configs/config.yml
@@ -1,14 +1,14 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/tests/resources/configs/config1.xml b/tests/resources/configs/config1.xml
index 6553c44..bb326a6 100644
--- a/tests/resources/configs/config1.xml
+++ b/tests/resources/configs/config1.xml
@@ -1,54 +1,54 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
- <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
- <appender name="default" class="EchoAppender">
- <layout class="LoggerLayoutTTCC"/>
- <filter class="LevelRangeFilter">
- <param name="levelMin" value="ERROR" />
- <param name="levelMax" value="FATAL" />
- <param name="acceptOnMatch" value="false" />
- </filter>
- <filter class="DenyAllFilter" />
- </appender>
- <appender name="file" class="DailyFileAppender" threshold="warn">
- <param name="datePattern" value="Ymd" />
- <param name="file" value="target/examples/daily_%s.log" />
- <layout class="PatternLayout">
- <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
- </layout>
- </appender>
- <logger name="foo.bar.baz" additivity="false">
- <level value="trace" />
- <appender_ref ref="default" />
- </logger>
- <logger name="foo.bar" additivity="true">
- <level value="debug" />
- <appender_ref ref="file" />
- </logger>
- <logger name="foo">
- <level value="warn" />
- <appender_ref ref="default" />
- <appender_ref ref="file" />
- </logger>
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <renderer renderedClass="Fruit" renderingClass="FruitRenderer" />
+ <renderer renderedClass="Beer" renderingClass="BeerRenderer" />
+ <appender name="default" class="EchoAppender">
+ <layout class="LoggerLayoutTTCC"/>
+ <filter class="LevelRangeFilter">
+ <param name="levelMin" value="ERROR" />
+ <param name="levelMax" value="FATAL" />
+ <param name="acceptOnMatch" value="false" />
+ </filter>
+ <filter class="DenyAllFilter" />
+ </appender>
+ <appender name="file" class="DailyFileAppender" threshold="warn">
+ <param name="datePattern" value="Ymd" />
+ <param name="file" value="target/examples/daily_%s.log" />
+ <layout class="PatternLayout">
+ <param name="conversionPattern" value= "%d{ISO8601} [%p] %c: %m (at %F line %L)%n" />
+ </layout>
+ </appender>
+ <logger name="foo.bar.baz" additivity="false">
+ <level value="trace" />
+ <appender_ref ref="default" />
+ </logger>
+ <logger name="foo.bar" additivity="true">
+ <level value="debug" />
+ <appender_ref ref="file" />
+ </logger>
+ <logger name="foo">
+ <level value="warn" />
+ <appender_ref ref="default" />
+ <appender_ref ref="file" />
+ </logger>
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/loggers/config_invalid_additivity.xml b/tests/resources/configs/loggers/config_invalid_additivity.xml
index 13fe2cc..e6128bd 100644
--- a/tests/resources/configs/loggers/config_invalid_additivity.xml
+++ b/tests/resources/configs/loggers/config_invalid_additivity.xml
@@ -1,30 +1,30 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <appender name="default" class="EchoAppender">
- <layout class="SimpleLayout"/>
- </appender>
- <logger name="myLogger" additivity="4711">
- <level value="warn" />
- <appender_ref ref="default" />
- </logger>
- <root>
- <level value="DEBUG" />
- <appender_ref ref="default" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <appender name="default" class="EchoAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+ <logger name="myLogger" additivity="4711">
+ <level value="warn" />
+ <appender_ref ref="default" />
+ </logger>
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="default" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/loggers/config_not_existing_appenders.xml b/tests/resources/configs/loggers/config_not_existing_appenders.xml
index 5e5ea1e..3f19039 100644
--- a/tests/resources/configs/loggers/config_not_existing_appenders.xml
+++ b/tests/resources/configs/loggers/config_not_existing_appenders.xml
@@ -1,23 +1,23 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
- <logger name="myLogger">
- <level value="warn" />
- <appender_ref ref="unknownAppender" />
- </logger>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php" threshold="debug">
+ <logger name="myLogger">
+ <level value="warn" />
+ <appender_ref ref="unknownAppender" />
+ </logger>
+</configuration>
diff --git a/tests/resources/configs/renderers/config_default_renderer.xml b/tests/resources/configs/renderers/config_default_renderer.xml
index 5c22323..9bdb545 100644
--- a/tests/resources/configs/renderers/config_default_renderer.xml
+++ b/tests/resources/configs/renderers/config_default_renderer.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender" />
-
- <defaultRenderer renderingClass="FruitRenderer3" />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender" />
+
+ <defaultRenderer renderingClass="FruitRenderer3" />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/renderers/config_invalid_rendering_class.xml b/tests/resources/configs/renderers/config_invalid_rendering_class.xml
index 51886fe..f722d56 100644
--- a/tests/resources/configs/renderers/config_invalid_rendering_class.xml
+++ b/tests/resources/configs/renderers/config_invalid_rendering_class.xml
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <renderer renderedClass="stdClass" renderingClass="stdClass" />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <renderer renderedClass="stdClass" renderingClass="stdClass" />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/renderers/config_no_rendered_class.xml b/tests/resources/configs/renderers/config_no_rendered_class.xml
index 836815e..209a2ef 100644
--- a/tests/resources/configs/renderers/config_no_rendered_class.xml
+++ b/tests/resources/configs/renderers/config_no_rendered_class.xml
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <renderer renderingClass="DefaultRenderer" />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <renderer renderingClass="DefaultRenderer" />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/renderers/config_no_rendering_class.xml b/tests/resources/configs/renderers/config_no_rendering_class.xml
index 77b14c4..e649b87 100644
--- a/tests/resources/configs/renderers/config_no_rendering_class.xml
+++ b/tests/resources/configs/renderers/config_no_rendering_class.xml
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <renderer />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
\ No newline at end of file
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <renderer />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/resources/configs/renderers/config_not_existing_rendering_class.xml b/tests/resources/configs/renderers/config_not_existing_rendering_class.xml
index 467bd25..0a5502b 100644
--- a/tests/resources/configs/renderers/config_not_existing_rendering_class.xml
+++ b/tests/resources/configs/renderers/config_not_existing_rendering_class.xml
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<configuration xmlns="http://logging.apache.org/log4php">
- <appender name="foo" class="ConsoleAppender">
- <layout class="SimpleLayout"/>
- </appender>
-
- <renderer renderedClass="stdClass" renderingClass="DoesNotExistRenderer" />
-
- <root>
- <level value="DEBUG" />
- <appender_ref ref="foo" />
- </root>
-</configuration>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration xmlns="http://logging.apache.org/log4php">
+ <appender name="foo" class="ConsoleAppender">
+ <layout class="SimpleLayout"/>
+ </appender>
+
+ <renderer renderedClass="stdClass" renderingClass="DoesNotExistRenderer" />
+
+ <root>
+ <level value="DEBUG" />
+ <appender_ref ref="foo" />
+ </root>
+</configuration>
diff --git a/tests/src/AppenderPoolTest.php b/tests/src/AppenderPoolTest.php
index 86ba9d9..9ad8170 100644
--- a/tests/src/AppenderPoolTest.php
+++ b/tests/src/AppenderPoolTest.php
@@ -29,56 +29,58 @@
/**
* @group filters
*/
-class AppenderPoolTest extends \PHPUnit_Framework_TestCase {
+class AppenderPoolTest extends \PHPUnit_Framework_TestCase
+{
+ public function setUp()
+ {
+ AppenderPool::clear();
+ }
- public function setUp() {
- AppenderPool::clear();
- }
+ public function tearDown()
+ {
+ AppenderPool::clear();
+ }
- public function tearDown() {
- AppenderPool::clear();
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Cannot add unnamed appender to pool.
+ */
+ public function testAppenderHasNoName()
+ {
+ $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
+ ->shouldReceive('getName')->andReturn('')
+ ->shouldReceive('close')
+ ->mock();
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Cannot add unnamed appender to pool.
- */
- public function testAppenderHasNoName() {
+ AppenderPool::add($mockAppender);
+ }
- $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
- ->shouldReceive('getName')->andReturn('')
- ->shouldReceive('close')
- ->mock();
+ public function testAppenderIsAdded()
+ {
+ $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
+ ->shouldReceive('getName')->andReturn('foo')
+ ->shouldReceive('close')
+ ->mock();
- AppenderPool::add($mockAppender);
- }
+ AppenderPool::add($mockAppender);
- public function testAppenderIsAdded() {
+ $expected = 1;
+ $actual = count(AppenderPool::getAppenders());
+ $this->assertEquals($expected, $actual);
+ }
- $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
- ->shouldReceive('getName')->andReturn('foo')
- ->shouldReceive('close')
- ->mock();
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Appender [foo] already exists in pool. Overwriting existing appender.
+ */
+ public function testDuplicateAppenderName()
+ {
+ $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
+ ->shouldReceive('getName')->andReturn('foo')
+ ->shouldReceive('close')
+ ->mock();
- AppenderPool::add($mockAppender);
-
- $expected = 1;
- $actual = count(AppenderPool::getAppenders());
- $this->assertEquals($expected, $actual);
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Appender [foo] already exists in pool. Overwriting existing appender.
- */
- public function testDuplicateAppenderName() {
-
- $mockAppender = m::mock('Apache\\Log4php\\Appenders\\ConsoleAppender')
- ->shouldReceive('getName')->andReturn('foo')
- ->shouldReceive('close')
- ->mock();
-
- AppenderPool::add($mockAppender);
- AppenderPool::add($mockAppender);
- }
+ AppenderPool::add($mockAppender);
+ AppenderPool::add($mockAppender);
+ }
}
diff --git a/tests/src/AppenderTest.php b/tests/src/AppenderTest.php
index d1fe009..1e60a2a 100644
--- a/tests/src/AppenderTest.php
+++ b/tests/src/AppenderTest.php
@@ -34,148 +34,155 @@
/**
* @group appenders
*/
-class AppenderTest extends \PHPUnit_Framework_TestCase {
+class AppenderTest extends \PHPUnit_Framework_TestCase
+{
+ public function testThreshold()
+ {
+ $appender = new EchoAppender("LoggerAppenderTest");
- public function testThreshold() {
- $appender = new EchoAppender("LoggerAppenderTest");
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
+ $warn = Level::getLevelWarn();
+ $appender->setThreshold($warn);
+ $appender->activateOptions();
- $warn = Level::getLevelWarn();
- $appender->setThreshold($warn);
- $appender->activateOptions();
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelFatal(), "testmessage");
+ ob_start();
+ $appender->doAppend($event);
+ $v = ob_get_contents();
+ ob_end_clean();
+ $e = "FATAL - testmessage" . PHP_EOL;
+ self::assertEquals($e, $v);
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelFatal(), "testmessage");
- ob_start();
- $appender->doAppend($event);
- $v = ob_get_contents();
- ob_end_clean();
- $e = "FATAL - testmessage" . PHP_EOL;
- self::assertEquals($e, $v);
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ ob_start();
+ $appender->doAppend($event);
+ $v = ob_get_contents();
+ ob_end_clean();
+ $e = "ERROR - testmessage" . PHP_EOL;
+ self::assertEquals($e, $v);
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- ob_start();
- $appender->doAppend($event);
- $v = ob_get_contents();
- ob_end_clean();
- $e = "ERROR - testmessage" . PHP_EOL;
- self::assertEquals($e, $v);
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ ob_start();
+ $appender->doAppend($event);
+ $v = ob_get_contents();
+ ob_end_clean();
+ $e = "WARN - testmessage" . PHP_EOL;
+ self::assertEquals($e, $v);
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- ob_start();
- $appender->doAppend($event);
- $v = ob_get_contents();
- ob_end_clean();
- $e = "WARN - testmessage" . PHP_EOL;
- self::assertEquals($e, $v);
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelInfo(), "testmessage");
+ ob_start();
+ $appender->doAppend($event);
+ $v = ob_get_contents();
+ ob_end_clean();
+ $e = "";
+ self::assertEquals($e, $v);
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelInfo(), "testmessage");
- ob_start();
- $appender->doAppend($event);
- $v = ob_get_contents();
- ob_end_clean();
- $e = "";
- self::assertEquals($e, $v);
-
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
- ob_start();
- $appender->doAppend($event);
- $v = ob_get_contents();
- ob_end_clean();
- $e = "";
- self::assertEquals($e, $v);
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
+ ob_start();
+ $appender->doAppend($event);
+ $v = ob_get_contents();
+ ob_end_clean();
+ $e = "";
+ self::assertEquals($e, $v);
}
- public function testGetThreshold() {
- $appender = new EchoAppender("LoggerAppenderTest");
+ public function testGetThreshold()
+ {
+ $appender = new EchoAppender("LoggerAppenderTest");
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
- $warn = Level::getLevelWarn();
- $appender->setThreshold($warn);
+ $warn = Level::getLevelWarn();
+ $appender->setThreshold($warn);
- $a = $appender->getThreshold();
- self::assertEquals($warn, $a);
+ $a = $appender->getThreshold();
+ self::assertEquals($warn, $a);
}
- public function testSetStringThreshold() {
- $appender = new EchoAppender("LoggerAppenderTest");
+ public function testSetStringThreshold()
+ {
+ $appender = new EchoAppender("LoggerAppenderTest");
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
- $warn = Level::getLevelWarn();
- $appender->setThreshold('WARN');
- $a = $appender->getThreshold();
- self::assertEquals($warn, $a);
+ $warn = Level::getLevelWarn();
+ $appender->setThreshold('WARN');
+ $a = $appender->getThreshold();
+ self::assertEquals($warn, $a);
- $e = Level::getLevelFatal();
- $appender->setThreshold('FATAL');
- $a = $appender->getThreshold();
- self::assertEquals($e, $a);
+ $e = Level::getLevelFatal();
+ $appender->setThreshold('FATAL');
+ $a = $appender->getThreshold();
+ self::assertEquals($e, $a);
- $e = Level::getLevelError();
- $appender->setThreshold('ERROR');
- $a = $appender->getThreshold();
- self::assertEquals($e, $a);
+ $e = Level::getLevelError();
+ $appender->setThreshold('ERROR');
+ $a = $appender->getThreshold();
+ self::assertEquals($e, $a);
- $e = Level::getLevelDebug();
- $appender->setThreshold('DEBUG');
- $a = $appender->getThreshold();
- self::assertEquals($e, $a);
+ $e = Level::getLevelDebug();
+ $appender->setThreshold('DEBUG');
+ $a = $appender->getThreshold();
+ self::assertEquals($e, $a);
- $e = Level::getLevelInfo();
- $appender->setThreshold('INFO');
- $a = $appender->getThreshold();
- self::assertEquals($e, $a);
+ $e = Level::getLevelInfo();
+ $appender->setThreshold('INFO');
+ $a = $appender->getThreshold();
+ self::assertEquals($e, $a);
}
- public function testSetFilter() {
- $appender = new EchoAppender("LoggerAppenderTest");
+ public function testSetFilter()
+ {
+ $appender = new EchoAppender("LoggerAppenderTest");
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
- $filter = new DenyAllFilter();
- $appender->addFilter($filter);
+ $filter = new DenyAllFilter();
+ $appender->addFilter($filter);
- $filter2 = new LevelMatchFilter();
- $appender->addFilter($filter2);
+ $filter2 = new LevelMatchFilter();
+ $appender->addFilter($filter2);
- $first = $appender->getFilter();
- self::assertEquals($first, $filter);
+ $first = $appender->getFilter();
+ self::assertEquals($first, $filter);
- $next = $first->getNext();
- self::assertEquals($next, $filter2);
+ $next = $first->getNext();
+ self::assertEquals($next, $filter2);
- $appender->clearFilters();
- $nullfilter = $appender->getFilter();
- self::assertNull($nullfilter);
+ $appender->clearFilters();
+ $nullfilter = $appender->getFilter();
+ self::assertNull($nullfilter);
}
- public function testInstanciateWithLayout() {
- $appender = new EchoAppender("LoggerAppenderTest");
+ public function testInstanciateWithLayout()
+ {
+ $appender = new EchoAppender("LoggerAppenderTest");
- $expected = "Apache\\Log4php\\Layouts\\SimpleLayout";
- $actual = $appender->getLayout();
- $this->assertInstanceof($expected, $actual);
+ $expected = "Apache\\Log4php\\Layouts\\SimpleLayout";
+ $actual = $appender->getLayout();
+ $this->assertInstanceof($expected, $actual);
}
- public function testOverwriteLayout() {
- $layout = new SimpleLayout();
- $appender = new EchoAppender("LoggerAppenderTest");
- $appender->setLayout($layout);
+ public function testOverwriteLayout()
+ {
+ $layout = new SimpleLayout();
+ $appender = new EchoAppender("LoggerAppenderTest");
+ $appender->setLayout($layout);
- $actual = $appender->getLayout();
- $this->assertEquals($layout, $actual);
+ $actual = $appender->getLayout();
+ $this->assertEquals($layout, $actual);
}
- public function testRequiresNoLayout() {
- $appender = new NullAppender("LoggerAppenderTest");
+ public function testRequiresNoLayout()
+ {
+ $appender = new NullAppender("LoggerAppenderTest");
- $actual = $appender->getLayout();
- $this->assertNull($actual);
+ $actual = $appender->getLayout();
+ $this->assertNull($actual);
}
}
diff --git a/tests/src/Appenders/ConsoleAppenderTest.php b/tests/src/Appenders/ConsoleAppenderTest.php
index a99a407..39c75b0 100644
--- a/tests/src/Appenders/ConsoleAppenderTest.php
+++ b/tests/src/Appenders/ConsoleAppenderTest.php
@@ -28,64 +28,68 @@
/**
* @group appenders
*/
-class ConsoleAppenderTest extends \PHPUnit_Framework_TestCase {
+class ConsoleAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ private $config = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'ConsoleAppender',
+ 'layout' => array(
+ 'class' => 'PatternLayout',
+ 'params' => array(
+ // Intentionally blank so output doesn't clutter phpunit output
+ 'conversionPattern' => ''
+ )
+ ),
+ )
+ )
+ );
- private $config = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'ConsoleAppender',
- 'layout' => array(
- 'class' => 'PatternLayout',
- 'params' => array(
- // Intentionally blank so output doesn't clutter phpunit output
- 'conversionPattern' => ''
- )
- ),
- )
- )
- );
-
- public function testRequiresLayout() {
- $appender = new ConsoleAppender();
- self::assertTrue($appender->requiresLayout());
- }
-
- public function testAppendDefault() {
- Logger::configure($this->config);
- $log = Logger::getRootLogger();
-
- $expected = ConsoleAppender::STDOUT;
- $actual = $log->getAppender('default')->getTarget();
- $this->assertSame($expected, $actual);
-
- $log->info("hello");
+ public function testRequiresLayout()
+ {
+ $appender = new ConsoleAppender();
+ self::assertTrue($appender->requiresLayout());
}
- public function testAppendStdout() {
- $this->config['appenders']['default']['params']['target'] = 'stdout';
+ public function testAppendDefault()
+ {
+ Logger::configure($this->config);
+ $log = Logger::getRootLogger();
- Logger::configure($this->config);
- $log = Logger::getRootLogger();
+ $expected = ConsoleAppender::STDOUT;
+ $actual = $log->getAppender('default')->getTarget();
+ $this->assertSame($expected, $actual);
- $expected = ConsoleAppender::STDOUT;
- $actual = $log->getAppender('default')->getTarget();
- $this->assertSame($expected, $actual);
-
- $log->info("hello");
+ $log->info("hello");
}
- public function testAppendStderr() {
- $this->config['appenders']['default']['params']['target'] = 'stderr';
- Logger::configure($this->config);
- $log = Logger::getRootLogger();
- $expected = ConsoleAppender::STDERR;
+ public function testAppendStdout()
+ {
+ $this->config['appenders']['default']['params']['target'] = 'stdout';
- $actual = $log->getAppender('default')->getTarget();
- $this->assertSame($expected, $actual);
+ Logger::configure($this->config);
+ $log = Logger::getRootLogger();
- $log->info("hello");
+ $expected = ConsoleAppender::STDOUT;
+ $actual = $log->getAppender('default')->getTarget();
+ $this->assertSame($expected, $actual);
+
+ $log->info("hello");
+ }
+
+ public function testAppendStderr()
+ {
+ $this->config['appenders']['default']['params']['target'] = 'stderr';
+ Logger::configure($this->config);
+ $log = Logger::getRootLogger();
+ $expected = ConsoleAppender::STDERR;
+
+ $actual = $log->getAppender('default')->getTarget();
+ $this->assertSame($expected, $actual);
+
+ $log->info("hello");
}
}
diff --git a/tests/src/Appenders/DailyFileAppenderTest.php b/tests/src/Appenders/DailyFileAppenderTest.php
index e5f3acf..a9ad0cf 100644
--- a/tests/src/Appenders/DailyFileAppenderTest.php
+++ b/tests/src/Appenders/DailyFileAppenderTest.php
@@ -30,165 +30,175 @@
/**
* @group appenders
*/
-class DailyFileAppenderTest extends \PHPUnit_Framework_TestCase {
+class DailyFileAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ protected function setUp()
+ {
+ @unlink(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date('Ymd'));
+ @unlink(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date('Y'));
+ }
- protected function setUp() {
- @unlink(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date('Ymd'));
- @unlink(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date('Y'));
- }
+ public function testRequiresLayout()
+ {
+ $appender = new DailyFileAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new DailyFileAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testDefaultLayout()
+ {
+ $appender = new DailyFileAppender();
+ $actual = $appender->getLayout();
+ self::assertInstanceOf('Apache\\Log4php\\Layouts\\SimpleLayout', $actual);
+ }
- public function testDefaultLayout() {
- $appender = new DailyFileAppender();
- $actual = $appender->getLayout();
- self::assertInstanceOf('Apache\\Log4php\\Layouts\\SimpleLayout', $actual);
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Required parameter 'file' not set.
+ */
+ public function testRequiredParamWarning1()
+ {
+ $appender = new DailyFileAppender();
+ $appender->activateOptions();
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Required parameter 'file' not set.
- */
- public function testRequiredParamWarning1() {
- $appender = new DailyFileAppender();
- $appender->activateOptions();
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Required parameter 'datePattern' not set.
+ */
+ public function testRequiredParamWarning2()
+ {
+ $appender = new DailyFileAppender();
+ $appender->setFile('file.log');
+ $appender->setDatePattern('');
+ $appender->activateOptions();
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Required parameter 'datePattern' not set.
- */
- public function testRequiredParamWarning2() {
- $appender = new DailyFileAppender();
- $appender->setFile('file.log');
- $appender->setDatePattern('');
- $appender->activateOptions();
- }
+ public function testGetDatePattern()
+ {
+ $appender = new DailyFileAppender();
- public function testGetDatePattern() {
- $appender = new DailyFileAppender();
+ // Default pattern
+ $actual = $appender->getDatePattern();
+ self::assertEquals('Ymd', $actual);
- // Default pattern
- $actual = $appender->getDatePattern();
- self::assertEquals('Ymd', $actual);
+ // Custom pattern
+ $appender->setDatePattern('xyz');
+ $actual = $appender->getDatePattern();
+ self::assertEquals('xyz', $actual);
+ }
- // Custom pattern
- $appender->setDatePattern('xyz');
- $actual = $appender->getDatePattern();
- self::assertEquals('xyz', $actual);
- }
+ /**
+ * For greater code coverage!
+ * Override the warning so remaining code is reached.
+ */
+ public function testRequiredParamWarning3()
+ {
+ $appender = new DailyFileAppender();
+ $appender->setFile('file.log');
+ $appender->setDatePattern('');
+ @$appender->activateOptions();
+ }
- /**
- * For greater code coverage!
- * Override the warning so remaining code is reached.
- */
- public function testRequiredParamWarning3() {
- $appender = new DailyFileAppender();
- $appender->setFile('file.log');
- $appender->setDatePattern('');
- @$appender->activateOptions();
- }
+ public function testLazyFileOpen()
+ {
+ $event = TestHelper::getWarnEvent("my message");
+ $file = PHPUNIT_TEMP_DIR . '/lazy-file.%s.log';
+ $pattern = 'Y-m-d';
- public function testLazyFileOpen() {
- $event = TestHelper::getWarnEvent("my message");
- $file = PHPUNIT_TEMP_DIR . '/lazy-file.%s.log';
- $pattern = 'Y-m-d';
+ $date = date($pattern, $event->getTimeStamp());
+ $path = PHPUNIT_TEMP_DIR . "/lazy-file.$date.log";
- $date = date($pattern, $event->getTimeStamp());
- $path = PHPUNIT_TEMP_DIR . "/lazy-file.$date.log";
+ if (file_exists($path)) {
+ unlink($path);
+ }
- if (file_exists($path)) {
- unlink($path);
- }
+ $appender = new DailyFileAppender();
+ $appender->setFile($file);
+ $appender->setDatePattern('Y-m-d');
+ $appender->activateOptions();
- $appender = new DailyFileAppender();
- $appender->setFile($file);
- $appender->setDatePattern('Y-m-d');
- $appender->activateOptions();
+ // File should not exist before first append
+ self::assertFileNotExists($path);
+ $appender->append($event);
+ self::assertFileExists($path);
+ }
- // File should not exist before first append
- self::assertFileNotExists($path);
- $appender->append($event);
- self::assertFileExists($path);
- }
+ public function testRollover()
+ {
+ $message = uniqid();
+ $level = Level::getLevelDebug();
- public function testRollover()
- {
- $message = uniqid();
- $level = Level::getLevelDebug();
+ $file = PHPUNIT_TEMP_DIR . '/lazy-file.%s.log';
+ $pattern = 'Y-m-d';
- $file = PHPUNIT_TEMP_DIR . '/lazy-file.%s.log';
- $pattern = 'Y-m-d';
+ // Get some timestamps for events - different date for each
+ $ts1 = mktime(10, 0, 0, 7, 3, 1980);
+ $ts2 = mktime(10, 0, 0, 7, 4, 1980);
+ $ts3 = mktime(10, 0, 0, 7, 5, 1980);
- // Get some timestamps for events - different date for each
- $ts1 = mktime(10, 0, 0, 7, 3, 1980);
- $ts2 = mktime(10, 0, 0, 7, 4, 1980);
- $ts3 = mktime(10, 0, 0, 7, 5, 1980);
+ $e1 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts1);
+ $e2 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts2);
+ $e3 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts3);
- $e1 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts1);
- $e2 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts2);
- $e3 = new LoggingEvent(__CLASS__, 'test', $level, $message, $ts3);
+ // Expected paths
+ $path1 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-03.log';
+ $path2 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-04.log';
+ $path3 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-05.log';
- // Expected paths
- $path1 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-03.log';
- $path2 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-04.log';
- $path3 = PHPUNIT_TEMP_DIR . '/lazy-file.1980-07-05.log';
+ @unlink($path1);
+ @unlink($path2);
+ @unlink($path3);
- @unlink($path1);
- @unlink($path2);
- @unlink($path3);
+ $appender = new DailyFileAppender();
+ $appender->setFile($file);
+ $appender->setDatePattern('Y-m-d');
+ $appender->activateOptions();
- $appender = new DailyFileAppender();
- $appender->setFile($file);
- $appender->setDatePattern('Y-m-d');
- $appender->activateOptions();
+ $appender->append($e1);
+ $appender->append($e2);
+ $appender->append($e3);
- $appender->append($e1);
- $appender->append($e2);
- $appender->append($e3);
+ $actual1 = file_get_contents($path1);
+ $actual2 = file_get_contents($path2);
+ $actual3 = file_get_contents($path3);
- $actual1 = file_get_contents($path1);
- $actual2 = file_get_contents($path2);
- $actual3 = file_get_contents($path3);
+ $expected1 = "DEBUG - $message" . PHP_EOL;
+ $expected2 = "DEBUG - $message" . PHP_EOL;
+ $expected3 = "DEBUG - $message" . PHP_EOL;
- $expected1 = "DEBUG - $message" . PHP_EOL;
- $expected2 = "DEBUG - $message" . PHP_EOL;
- $expected3 = "DEBUG - $message" . PHP_EOL;
+ self::assertSame($expected1, $actual1);
+ self::assertSame($expected2, $actual2);
+ self::assertSame($expected3, $actual3);
+ }
- self::assertSame($expected1, $actual1);
- self::assertSame($expected2, $actual2);
- self::assertSame($expected3, $actual3);
- }
+ public function testSimpleLogging()
+ {
+ $event = TestHelper::getWarnEvent("my message");
- public function testSimpleLogging() {
- $event = TestHelper::getWarnEvent("my message");
+ $appender = new DailyFileAppender();
+ $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.%s');
+ $appender->activateOptions();
+ $appender->append($event);
+ $appender->close();
- $appender = new DailyFileAppender();
- $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.%s');
- $appender->activateOptions();
- $appender->append($event);
- $appender->close();
+ $actual = file_get_contents(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date("Ymd"));
+ $expected = "WARN - my message".PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
- $actual = file_get_contents(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date("Ymd"));
- $expected = "WARN - my message".PHP_EOL;
- self::assertEquals($expected, $actual);
- }
+ public function testChangedDateFormat()
+ {
+ $event = TestHelper::getWarnEvent("my message");
- public function testChangedDateFormat() {
- $event = TestHelper::getWarnEvent("my message");
+ $appender = new DailyFileAppender();
+ $appender->setDatePattern('Y');
+ $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.%s');
+ $appender->activateOptions();
+ $appender->append($event);
+ $appender->close();
- $appender = new DailyFileAppender();
- $appender->setDatePattern('Y');
- $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.%s');
- $appender->activateOptions();
- $appender->append($event);
- $appender->close();
-
- $actual = file_get_contents(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date("Y"));
- $expected = "WARN - my message".PHP_EOL;
- self::assertEquals($expected, $actual);
- }
+ $actual = file_get_contents(PHPUNIT_TEMP_DIR . '/TEST-daily.txt.' . date("Y"));
+ $expected = "WARN - my message".PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
}
diff --git a/tests/src/Appenders/EchoAppenderTest.php b/tests/src/Appenders/EchoAppenderTest.php
index 57f2c12..a2daf1f 100644
--- a/tests/src/Appenders/EchoAppenderTest.php
+++ b/tests/src/Appenders/EchoAppenderTest.php
@@ -31,140 +31,144 @@
/**
* @group appenders
*/
-class EchoAppenderTest extends \PHPUnit_Framework_TestCase {
+class EchoAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ private $config1 = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ )
+ )
+ );
- private $config1 = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- )
- )
- );
+ private $config2 = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ 'params' => array(
+ 'htmlLineBreaks' => true
+ )
+ )
+ )
+ );
- private $config2 = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- 'params' => array(
- 'htmlLineBreaks' => true
- )
- )
- )
- );
+ private $config3 = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ 'params' => array(
+ 'htmlLineBreaks' => 'foo'
+ )
+ )
+ )
+ );
- private $config3 = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- 'params' => array(
- 'htmlLineBreaks' => 'foo'
- )
- )
- )
- );
+ public function testAppend()
+ {
+ Logger::configure($this->config1);
+ $log = Logger::getRootLogger();
- public function testAppend() {
- Logger::configure($this->config1);
- $log = Logger::getRootLogger();
+ $hlb = $log->getAppender('default')->getHtmlLineBreaks();
+ $this->assertSame(false, $hlb);
- $hlb = $log->getAppender('default')->getHtmlLineBreaks();
- $this->assertSame(false, $hlb);
+ ob_start();
+ $log->info("This is a test");
+ $log->debug("And this too");
+ $actual = ob_get_clean();
+ $expected = "INFO - This is a test" . PHP_EOL . "DEBUG - And this too". PHP_EOL;
- ob_start();
- $log->info("This is a test");
- $log->debug("And this too");
- $actual = ob_get_clean();
- $expected = "INFO - This is a test" . PHP_EOL . "DEBUG - And this too". PHP_EOL;
+ $this->assertSame($expected, $actual);
+ }
- $this->assertSame($expected, $actual);
- }
+ public function testHtmlLineBreaks()
+ {
+ Logger::configure($this->config2);
+ $log = Logger::getRootLogger();
- public function testHtmlLineBreaks() {
- Logger::configure($this->config2);
- $log = Logger::getRootLogger();
+ $hlb = $log->getAppender('default')->getHtmlLineBreaks();
+ $this->assertSame(true, $hlb);
- $hlb = $log->getAppender('default')->getHtmlLineBreaks();
- $this->assertSame(true, $hlb);
+ ob_start();
+ $log->info("This is a test" . PHP_EOL . "With more than one line");
+ $log->debug("And this too");
+ $actual = ob_get_clean();
+ $expected = "INFO - This is a test<br />" . PHP_EOL . "With more than one line<br />" . PHP_EOL . "DEBUG - And this too<br />" . PHP_EOL;
- ob_start();
- $log->info("This is a test" . PHP_EOL . "With more than one line");
- $log->debug("And this too");
- $actual = ob_get_clean();
- $expected = "INFO - This is a test<br />" . PHP_EOL . "With more than one line<br />" . PHP_EOL . "DEBUG - And this too<br />" . PHP_EOL;
-
- $this->assertSame($expected, $actual);
- }
+ $this->assertSame($expected, $actual);
+ }
// public function testHtmlLineBreaksInvalidOption() {
// Logger::configure($this->config3);
// }
+ public function testEcho()
+ {
+ $appender = new EchoAppender("myname ");
- public function testEcho() {
- $appender = new EchoAppender("myname ");
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
+ $appender->activateOptions();
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
- $appender->activateOptions();
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $expected = "ERROR - testmessage" . PHP_EOL;
+ ob_start();
+ $appender->append($event);
+ $actual = ob_get_clean();
- $expected = "ERROR - testmessage" . PHP_EOL;
- ob_start();
- $appender->append($event);
- $actual = ob_get_clean();
+ self::assertEquals($expected, $actual);
+ }
- self::assertEquals($expected, $actual);
- }
+ public function testRequiresLayout()
+ {
+ $appender = new EchoAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new EchoAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testEchoHtml()
+ {
+ $appender = new EchoAppender("myname ");
+ $appender->setHtmlLineBreaks(true);
- public function testEchoHtml() {
- $appender = new EchoAppender("myname ");
- $appender->setHtmlLineBreaks(true);
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
+ $appender->activateOptions();
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
- $appender->activateOptions();
+ // Single line message
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- // Single line message
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $expected = "ERROR - testmessage<br />" . PHP_EOL;
+ ob_start();
+ $appender->append($event);
+ $actual = ob_get_clean();
+ self::assertEquals($expected, $actual);
- $expected = "ERROR - testmessage<br />" . PHP_EOL;
- ob_start();
- $appender->append($event);
- $actual = ob_get_clean();
- self::assertEquals($expected, $actual);
+ // Multi-line message
+ $msg = "This message\nis in several lines\r\nto test various line breaks.";
+ $expected = "ERROR - This message<br />\nis in several lines<br />\r\nto test various line breaks.<br />" . PHP_EOL;
- // Multi-line message
- $msg = "This message\nis in several lines\r\nto test various line breaks.";
- $expected = "ERROR - This message<br />\nis in several lines<br />\r\nto test various line breaks.<br />" . PHP_EOL;
-
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), $msg);
- ob_start();
- $appender->append($event);
- $actual = ob_get_clean();
- self::assertEquals($expected, $actual);
- }
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), $msg);
+ ob_start();
+ $appender->append($event);
+ $actual = ob_get_clean();
+ self::assertEquals($expected, $actual);
+ }
}
diff --git a/tests/src/Appenders/FileAppenderTest.php b/tests/src/Appenders/FileAppenderTest.php
index e8ed539..2a0021d 100644
--- a/tests/src/Appenders/FileAppenderTest.php
+++ b/tests/src/Appenders/FileAppenderTest.php
@@ -30,110 +30,118 @@
/**
* @group appenders
*/
-class FileAppenderTest extends \PHPUnit_Framework_TestCase {
+class FileAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ private $config1 = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'FileAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ 'params' => array()
+ )
+ )
+ );
- private $config1 = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'FileAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- 'params' => array()
- )
- )
- );
+ private $testPath;
- private $testPath;
+ public function __construct()
+ {
+ $this->testPath = PHPUNIT_TEMP_DIR . '/TEST.txt';
+ }
- public function __construct() {
- $this->testPath = PHPUNIT_TEMP_DIR . '/TEST.txt';
- }
+ public function setUp()
+ {
+ Logger::resetConfiguration();
+ if (file_exists($this->testPath)) {
+ unlink($this->testPath);
+ }
+ }
- public function setUp() {
- Logger::resetConfiguration();
- if(file_exists($this->testPath)) {
- unlink($this->testPath);
- }
- }
+ public function tearDown()
+ {
+ Logger::resetConfiguration();
+ if (file_exists($this->testPath)) {
+ unlink($this->testPath);
+ }
+ }
- public function tearDown() {
- Logger::resetConfiguration();
- if(file_exists($this->testPath)) {
- unlink($this->testPath);
- }
- }
+ public function testRequiresLayout()
+ {
+ $appender = new FileAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new FileAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testActivationDoesNotCreateTheFile()
+ {
+ $path = PHPUNIT_TEMP_DIR . "/doesnotexisthopefully.log";
+ @unlink($path);
+ $appender = new FileAppender();
+ $appender->setFile($path);
+ $appender->activateOptions();
- public function testActivationDoesNotCreateTheFile() {
- $path = PHPUNIT_TEMP_DIR . "/doesnotexisthopefully.log";
- @unlink($path);
- $appender = new FileAppender();
- $appender->setFile($path);
- $appender->activateOptions();
+ self::assertFalse(file_exists($path));
- self::assertFalse(file_exists($path));
+ $event = TestHelper::getInfoEvent('bla');
+ $appender->append($event);
- $event = TestHelper::getInfoEvent('bla');
- $appender->append($event);
+ self::assertTrue(file_exists($path));
+ }
- self::assertTrue(file_exists($path));
- }
+ public function testSimpleLogging()
+ {
+ $config = $this->config1;
+ $config['appenders']['default']['params']['file'] = $this->testPath;
- public function testSimpleLogging() {
- $config = $this->config1;
- $config['appenders']['default']['params']['file'] = $this->testPath;
+ Logger::configure($config);
- Logger::configure($config);
+ $logger = Logger::getRootLogger();
+ $logger->info('This is a test');
- $logger = Logger::getRootLogger();
- $logger->info('This is a test');
+ $expected = "INFO - This is a test" . PHP_EOL;
+ $actual = file_get_contents($this->testPath);
+ $this->assertSame($expected, $actual);
+ }
- $expected = "INFO - This is a test" . PHP_EOL;
- $actual = file_get_contents($this->testPath);
- $this->assertSame($expected, $actual);
- }
+ public function testAppendFlagTrue()
+ {
+ $config = $this->config1;
+ $config['appenders']['default']['params']['file'] = $this->testPath;
+ $config['appenders']['default']['params']['append'] = true;
- public function testAppendFlagTrue() {
- $config = $this->config1;
- $config['appenders']['default']['params']['file'] = $this->testPath;
- $config['appenders']['default']['params']['append'] = true;
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
+ $logger->info('This is a test');
- Logger::configure($config);
- $logger = Logger::getRootLogger();
- $logger->info('This is a test');
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
+ $logger->info('This is a test');
- Logger::configure($config);
- $logger = Logger::getRootLogger();
- $logger->info('This is a test');
+ $expected = "INFO - This is a test" . PHP_EOL . "INFO - This is a test" . PHP_EOL;
+ $actual = file_get_contents($this->testPath);
+ $this->assertSame($expected, $actual);
+ }
- $expected = "INFO - This is a test" . PHP_EOL . "INFO - This is a test" . PHP_EOL;
- $actual = file_get_contents($this->testPath);
- $this->assertSame($expected, $actual);
- }
+ public function testAppendFlagFalse()
+ {
+ $config = $this->config1;
+ $config['appenders']['default']['params']['file'] = $this->testPath;
+ $config['appenders']['default']['params']['append'] = false;
- public function testAppendFlagFalse() {
- $config = $this->config1;
- $config['appenders']['default']['params']['file'] = $this->testPath;
- $config['appenders']['default']['params']['append'] = false;
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
+ $logger->info('This is a test');
- Logger::configure($config);
- $logger = Logger::getRootLogger();
- $logger->info('This is a test');
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
+ $logger->info('This is a test');
- Logger::configure($config);
- $logger = Logger::getRootLogger();
- $logger->info('This is a test');
-
- $expected = "INFO - This is a test" . PHP_EOL;
- $actual = file_get_contents($this->testPath);
- $this->assertSame($expected, $actual);
- }
+ $expected = "INFO - This is a test" . PHP_EOL;
+ $actual = file_get_contents($this->testPath);
+ $this->assertSame($expected, $actual);
+ }
}
diff --git a/tests/src/Appenders/MailAppenderTest.php b/tests/src/Appenders/MailAppenderTest.php
index 73c7e83..c317b66 100644
--- a/tests/src/Appenders/MailAppenderTest.php
+++ b/tests/src/Appenders/MailAppenderTest.php
@@ -31,34 +31,36 @@
/**
* @group appenders
*/
-class MailAppenderTest extends \PHPUnit_Framework_TestCase {
+class MailAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ public function testRequiresLayout()
+ {
+ $appender = new MailAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new MailAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testMail()
+ {
+ $appender = new MailAppender("myname ");
- public function testMail() {
- $appender = new MailAppender("myname ");
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
+ $appender->setDry(true);
+ $appender->setTo('test@example.com');
+ $appender->setFrom('Testsender');
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
- $appender->setDry(true);
- $appender->setTo('test@example.com');
- $appender->setFrom('Testsender');
+ $appender->activateOptions();
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $event2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage2");
- $appender->activateOptions();
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $event2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage2");
+ ob_start();
+ $appender->append($event);
+ $appender->append($event2);
+ $appender->close();
+ $v = ob_get_contents();
+ ob_end_clean();
- ob_start();
- $appender->append($event);
- $appender->append($event2);
- $appender->close();
- $v = ob_get_contents();
- ob_end_clean();
-
- $e = "DRY MODE OF MAIL APP.: Send mail to: test@example.com with content: ERROR - testmessage".PHP_EOL."ERROR - testmessage2".PHP_EOL;
- self::assertEquals($e, $v);
+ $e = "DRY MODE OF MAIL APP.: Send mail to: test@example.com with content: ERROR - testmessage".PHP_EOL."ERROR - testmessage2".PHP_EOL;
+ self::assertEquals($e, $v);
}
}
diff --git a/tests/src/Appenders/MailEventAppenderTest.php b/tests/src/Appenders/MailEventAppenderTest.php
index 2199f83..51f1957 100644
--- a/tests/src/Appenders/MailEventAppenderTest.php
+++ b/tests/src/Appenders/MailEventAppenderTest.php
@@ -31,56 +31,60 @@
/**
* @group appenders
*/
-class MailEventAppenderTest extends \PHPUnit_Framework_TestCase {
+class MailEventAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ public function testRequiresLayout()
+ {
+ $appender = new MailEventAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new MailEventAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testMail()
+ {
+ $appender = new MailEventAppender("myname");
- public function testMail() {
- $appender = new MailEventAppender("myname");
+ $layout = new SimpleLayout();
+ $appender->setLayout($layout);
+ $appender->setDry(true);
+ $appender->setTo('test@example.com');
+ $appender->setFrom('Testsender');
- $layout = new SimpleLayout();
- $appender->setLayout($layout);
- $appender->setDry(true);
- $appender->setTo('test@example.com');
- $appender->setFrom('Testsender');
+ $appender->activateOptions();
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $appender->activateOptions();
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ ob_start();
+ $appender->append($event);
+ $v = ob_get_contents();
+ ob_end_clean();
- ob_start();
- $appender->append($event);
- $v = ob_get_contents();
- ob_end_clean();
+ $e = "DRY MODE OF MAIL APP.: Send mail to: test@example.com with additional headers 'From: Testsender' and content: ERROR - testmessage".PHP_EOL;
+ self::assertEquals($e, $v);
+ $appender->close();
+ }
- $e = "DRY MODE OF MAIL APP.: Send mail to: test@example.com with additional headers 'From: Testsender' and content: ERROR - testmessage".PHP_EOL;
- self::assertEquals($e, $v);
- $appender->close();
- }
+ /**
+ * Check an error is reported if 'to' is not set.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Required parameter 'to' not set.
+ */
+ public function testEmptyTo()
+ {
+ $appender = new MailEventAppender("myname");
+ $appender->setLayout(new SimpleLayout());
+ $appender->setFrom('info@example.com');
+ $appender->activateOptions();
+ }
- /**
- * Check an error is reported if 'to' is not set.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Required parameter 'to' not set.
- */
- public function testEmptyTo() {
- $appender = new MailEventAppender("myname");
- $appender->setLayout(new SimpleLayout());
- $appender->setFrom('info@example.com');
- $appender->activateOptions();
- }
-
- /**
- * Check an error is reported if 'from' is not set.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Required parameter 'from' not set.
- */
- public function testEmptyFrom() {
- $appender = new MailEventAppender("myname");
- $appender->setLayout(new SimpleLayout());
- $appender->setTo('info@example.com');
- $appender->activateOptions();
- }
+ /**
+ * Check an error is reported if 'from' is not set.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Required parameter 'from' not set.
+ */
+ public function testEmptyFrom()
+ {
+ $appender = new MailEventAppender("myname");
+ $appender->setLayout(new SimpleLayout());
+ $appender->setTo('info@example.com');
+ $appender->activateOptions();
+ }
}
diff --git a/tests/src/Appenders/MongoDBAppenderTest.php b/tests/src/Appenders/MongoDBAppenderTest.php
index e4622dd..6194ff0 100644
--- a/tests/src/Appenders/MongoDBAppenderTest.php
+++ b/tests/src/Appenders/MongoDBAppenderTest.php
@@ -36,178 +36,192 @@
*
* @group appenders
*/
-class MongoDBAppenderTest extends \PHPUnit_Framework_TestCase {
+class MongoDBAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ protected $appender;
+ protected $event;
- protected $appender;
- protected $event;
+ protected function setUp()
+ {
+ if (!extension_loaded('mongo')) {
+ $this->markTestSkipped(
+ 'The Mongo extension is not available.'
+ );
+ } else {
+ $this->appender = new MongoDBAppender('mongo_appender');
+ $this->event = TestHelper::getErrorEvent('mongo logging event', 'test_mongo');
+ }
+ }
- protected function setUp() {
- if (!extension_loaded('mongo')) {
- $this->markTestSkipped(
- 'The Mongo extension is not available.'
- );
- } else {
- $this->appender = new MongoDBAppender('mongo_appender');
- $this->event = TestHelper::getErrorEvent('mongo logging event', 'test_mongo');
- }
- }
+ protected function tearDown()
+ {
+ unset($this->appender);
+ }
- protected function tearDown() {
- unset($this->appender);
- }
+ public function testHost()
+ {
+ $expected = 'mongodb://localhost';
+ $this->appender->setHost($expected);
+ $result = $this->appender->getHost();
+ $this->assertEquals($expected, $result);
+ }
- public function testHost() {
- $expected = 'mongodb://localhost';
- $this->appender->setHost($expected);
- $result = $this->appender->getHost();
- $this->assertEquals($expected, $result);
- }
+ public function testPort()
+ {
+ $expected = 27017;
+ $this->appender->setPort($expected);
+ $result = $this->appender->getPort();
+ $this->assertEquals($expected, $result);
+ }
- public function testPort() {
- $expected = 27017;
- $this->appender->setPort($expected);
- $result = $this->appender->getPort();
- $this->assertEquals($expected, $result);
- }
+ public function testDatabaseName()
+ {
+ $expected = 'log4php_mongodb';
+ $this->appender->setDatabaseName($expected);
+ $result = $this->appender->getDatabaseName();
+ $this->assertEquals($expected, $result);
+ }
- public function testDatabaseName() {
- $expected = 'log4php_mongodb';
- $this->appender->setDatabaseName($expected);
- $result = $this->appender->getDatabaseName();
- $this->assertEquals($expected, $result);
- }
+ public function testCollectionName()
+ {
+ $expected = 'logs';
+ $this->appender->setCollectionName($expected);
+ $result = $this->appender->getCollectionName();
+ $this->assertEquals($expected, $result);
+ }
- public function testCollectionName() {
- $expected = 'logs';
- $this->appender->setCollectionName($expected);
- $result = $this->appender->getCollectionName();
- $this->assertEquals($expected, $result);
- }
+ public function testUserName()
+ {
+ $expected = 'char0n';
+ $this->appender->setUserName($expected);
+ $result = $this->appender->getUserName();
+ $this->assertEquals($expected, $result);
+ }
- public function testUserName() {
- $expected = 'char0n';
- $this->appender->setUserName($expected);
- $result = $this->appender->getUserName();
- $this->assertEquals($expected, $result);
- }
+ public function testPassword()
+ {
+ $expected = 'secret pass';
+ $this->appender->setPassword($expected);
+ $result = $this->appender->getPassword();
+ $this->assertEquals($expected, $result);
+ }
- public function testPassword() {
- $expected = 'secret pass';
- $this->appender->setPassword($expected);
- $result = $this->appender->getPassword();
- $this->assertEquals($expected, $result);
- }
+ public function testTimeout()
+ {
+ $expected = 4000;
+ $this->appender->setTimeout($expected);
+ $result = $this->appender->getTimeout();
+ $this->assertEquals($expected, $result);
+ }
- public function testTimeout() {
- $expected = 4000;
- $this->appender->setTimeout($expected);
- $result = $this->appender->getTimeout();
- $this->assertEquals($expected, $result);
- }
+ public function testActivateOptions()
+ {
+ $this->appender->activateOptions();
+ $this->assertInstanceOf('Mongo', $this->appender->getConnection());
+ $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
+ }
- public function testActivateOptions() {
- $this->appender->activateOptions();
- $this->assertInstanceOf('Mongo', $this->appender->getConnection());
- $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
- }
+ public function testActivateOptionsNoCredentials()
+ {
+ $this->appender->setUserName(null);
+ $this->appender->setPassword(null);
+ $this->appender->activateOptions();
+ $this->assertInstanceOf('Mongo', $this->appender->getConnection());
+ $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
+ }
- public function testActivateOptionsNoCredentials() {
- $this->appender->setUserName(null);
- $this->appender->setPassword(null);
- $this->appender->activateOptions();
- $this->assertInstanceOf('Mongo', $this->appender->getConnection());
- $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
- }
+ public function testFormat()
+ {
+ $this->appender->activateOptions();
+ $record = $this->logOne($this->event);
- public function testFormat() {
- $this->appender->activateOptions();
- $record = $this->logOne($this->event);
+ $this->assertEquals('ERROR', $record['level']);
+ $this->assertEquals('mongo logging event', $record['message']);
+ $this->assertEquals('test_mongo', $record['loggerName']);
- $this->assertEquals('ERROR', $record['level']);
- $this->assertEquals('mongo logging event', $record['message']);
- $this->assertEquals('test_mongo', $record['loggerName']);
+ $this->assertEquals('NA', $record['fileName']);
+ $this->assertEquals('getLocationInformation', $record['method']);
+ $this->assertEquals('NA', $record['lineNumber']);
+ $this->assertEquals('Apache\\Log4php\\LoggingEvent', $record['className']);
- $this->assertEquals('NA', $record['fileName']);
- $this->assertEquals('getLocationInformation', $record['method']);
- $this->assertEquals('NA', $record['lineNumber']);
- $this->assertEquals('Apache\\Log4php\\LoggingEvent', $record['className']);
+ $this->assertTrue(is_int($record['thread']));
+ $this->assertSame(getmypid(), $record['thread']);
+ $this->assertTrue(is_int($record['lineNumber']) || $record['lineNumber'] == 'NA');
+ }
- $this->assertTrue(is_int($record['thread']));
- $this->assertSame(getmypid(), $record['thread']);
- $this->assertTrue(is_int($record['lineNumber']) || $record['lineNumber'] == 'NA');
- }
+ public function testFormatThrowableInfo()
+ {
+ $this->appender->activateOptions();
+ $event = new LoggingEvent(
+ 'testFqcn',
+ new Logger('test.Logger'),
+ Level::getLevelWarn(),
+ 'test message',
+ microtime(true),
+ new \Exception('test exception', 1)
+ );
- public function testFormatThrowableInfo() {
- $this->appender->activateOptions();
- $event = new LoggingEvent(
- 'testFqcn',
- new Logger('test.Logger'),
- Level::getLevelWarn(),
- 'test message',
- microtime(true),
- new \Exception('test exception', 1)
- );
+ $record = $this->logOne($event);
- $record = $this->logOne($event);
+ $this->assertArrayHasKey('exception', $record);
+ $this->assertEquals(1, $record['exception']['code']);
+ $this->assertEquals('test exception', $record['exception']['message']);
- $this->assertArrayHasKey('exception', $record);
- $this->assertEquals(1, $record['exception']['code']);
- $this->assertEquals('test exception', $record['exception']['message']);
+ $this->assertContains('[internal function]: ' . __CLASS__, $record['exception']['stackTrace']);
+ }
- $this->assertContains('[internal function]: ' . __CLASS__, $record['exception']['stackTrace']);
- }
+ public function testFormatThrowableInfoWithInnerException()
+ {
+ // Skip test if PHP version is lower than 5.3.0 (no inner exception support)
+ if (version_compare(PHP_VERSION, '5.3.0') < 0) {
+ $this->markTestSkipped();
+ }
- public function testFormatThrowableInfoWithInnerException() {
+ $this->appender->activateOptions();
+ $event = new LoggingEvent(
+ 'testFqcn',
+ new Logger('test.Logger'),
+ Level::getLevelWarn(),
+ 'test message',
+ microtime(true),
+ new \Exception('test exception', 1, new \Exception('test exception inner', 2))
+ );
- // Skip test if PHP version is lower than 5.3.0 (no inner exception support)
- if (version_compare(PHP_VERSION, '5.3.0') < 0) {
- $this->markTestSkipped();
- }
+ $record = $this->logOne($event);
- $this->appender->activateOptions();
- $event = new LoggingEvent(
- 'testFqcn',
- new Logger('test.Logger'),
- Level::getLevelWarn(),
- 'test message',
- microtime(true),
- new \Exception('test exception', 1, new \Exception('test exception inner', 2))
- );
+ $this->assertArrayHasKey('exception', $record);
+ $this->assertEquals(1, $record['exception']['code']);
+ $this->assertEquals('test exception', $record['exception']['message']);
+ $this->assertContains('[internal function]: ' . __CLASS__, $record['exception']['stackTrace']);
- $record = $this->logOne($event);
+ $this->assertArrayHasKey('innerException', $record['exception']);
+ $this->assertEquals(2, $record['exception']['innerException']['code']);
+ $this->assertEquals('test exception inner', $record['exception']['innerException']['message']);
+ }
- $this->assertArrayHasKey('exception', $record);
- $this->assertEquals(1, $record['exception']['code']);
- $this->assertEquals('test exception', $record['exception']['message']);
- $this->assertContains('[internal function]: ' . __CLASS__, $record['exception']['stackTrace']);
+ public function testClose()
+ {
+ $this->appender->activateOptions();
+ $this->assertInstanceOf('Mongo', $this->appender->getConnection());
+ $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
+ $this->appender->close();
+ $this->assertNull($this->appender->getConnection());
+ $this->assertNull($this->appender->getCollection());
+ }
- $this->assertArrayHasKey('innerException', $record['exception']);
- $this->assertEquals(2, $record['exception']['innerException']['code']);
- $this->assertEquals('test exception inner', $record['exception']['innerException']['message']);
- }
+ /**
+ * Logs the event and returns the record from the database.
+ * @param LoggingEvent $event
+ * @return array
+ */
+ private function logOne($event)
+ {
+ $collection = $this->appender->getCollection();
+ $collection->drop();
+ $this->appender->append($event);
+ $record = $collection->findOne();
+ $this->assertNotNull($record, 'Could not read the record from the database.');
-
- public function testClose() {
- $this->appender->activateOptions();
- $this->assertInstanceOf('Mongo', $this->appender->getConnection());
- $this->assertInstanceOf('MongoCollection', $this->appender->getCollection());
- $this->appender->close();
- $this->assertNull($this->appender->getConnection());
- $this->assertNull($this->appender->getCollection());
- }
-
- /**
- * Logs the event and returns the record from the database.
- * @param LoggingEvent $event
- * @return array
- */
- private function logOne($event)
- {
- $collection = $this->appender->getCollection();
- $collection->drop();
- $this->appender->append($event);
- $record = $collection->findOne();
- $this->assertNotNull($record, 'Could not read the record from the database.');
- return $record;
- }
+ return $record;
+ }
}
diff --git a/tests/src/Appenders/NullAppenderTest.php b/tests/src/Appenders/NullAppenderTest.php
index 5c7a96e..dfde21f 100644
--- a/tests/src/Appenders/NullAppenderTest.php
+++ b/tests/src/Appenders/NullAppenderTest.php
@@ -30,22 +30,25 @@
/**
* @group appenders
*/
-class NullAppenderTest extends \PHPUnit_Framework_TestCase {
- /**
- * The Null appender does nothing - nothing to assert.
- * Just here for the sake of completness and a good testing ratio :-)
- */
- public function testActivateOptions() {
+class NullAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * The Null appender does nothing - nothing to assert.
+ * Just here for the sake of completness and a good testing ratio :-)
+ */
+ public function testActivateOptions()
+ {
$event = new LoggingEvent("LoggerAppenderNullTest", new Logger("TEST"), Level::getLevelInfo(), "testmessage");
- $appender = new NullAppender("TEST");
- $appender->activateOptions();
- $appender->append($event);
- $appender->close();
+ $appender = new NullAppender("TEST");
+ $appender->activateOptions();
+ $appender->append($event);
+ $appender->close();
}
- public function testRequiresLayout() {
- $appender = new NullAppender();
- self::assertFalse($appender->requiresLayout());
- }
+ public function testRequiresLayout()
+ {
+ $appender = new NullAppender();
+ self::assertFalse($appender->requiresLayout());
+ }
}
diff --git a/tests/src/Appenders/PDOAppenderTest.php b/tests/src/Appenders/PDOAppenderTest.php
index b325e04..2f82ee6 100644
--- a/tests/src/Appenders/PDOAppenderTest.php
+++ b/tests/src/Appenders/PDOAppenderTest.php
@@ -32,139 +32,144 @@
/**
* @group appenders
*/
-class PDOAppenderTest extends \PHPUnit_Framework_TestCase {
+class PDOAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ const FILENAME = 'pdotest.sqlite';
+ private static $dsn;
+ private static $file;
- const FILENAME = 'pdotest.sqlite';
- private static $dsn;
- private static $file;
+ public static function setUpBeforeClass()
+ {
+ self::$file = PHPUNIT_TEMP_DIR . '/' . self::FILENAME;
+ self::$dsn = 'sqlite:' . self::$file;
- public static function setUpBeforeClass() {
+ if (extension_loaded('pdo_sqlite')) {
+ $drop = 'DROP TABLE IF EXISTS log4php_log;';
+ $create = 'CREATE TABLE log4php_log (
+ timestamp VARCHAR(256),
+ logger VARCHAR(256),
+ level VARCHAR(32),
+ message VARCHAR(4000),
+ thread INTEGER,
+ file VARCHAR(255),
+ line VARCHAR(10)
+ );';
- self::$file = PHPUNIT_TEMP_DIR . '/' . self::FILENAME;
- self::$dsn = 'sqlite:' . self::$file;
+ $pdo = new PDO(self::$dsn);
+ $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ $pdo->exec($drop);
+ $pdo->exec($create);
+ }
+ }
- if(extension_loaded('pdo_sqlite')) {
- $drop = 'DROP TABLE IF EXISTS log4php_log;';
- $create = 'CREATE TABLE log4php_log (
- timestamp VARCHAR(256),
- logger VARCHAR(256),
- level VARCHAR(32),
- message VARCHAR(4000),
- thread INTEGER,
- file VARCHAR(255),
- line VARCHAR(10)
- );';
+ /** To start with an empty database for each single test. */
+ public function setUp()
+ {
+ if (!extension_loaded('pdo_sqlite')) {
+ self::markTestSkipped("Please install 'pdo_sqlite' in order to run this test");
+ }
+ }
- $pdo = new PDO(self::$dsn);
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $pdo->exec($drop);
- $pdo->exec($create);
- }
- }
+ /** Clean up after the last test was run. */
+ public static function tearDownAfterClass()
+ {
+ @unlink(self::$file);
+ }
- /** To start with an empty database for each single test. */
- public function setUp() {
- if(!extension_loaded('pdo_sqlite')) {
- self::markTestSkipped("Please install 'pdo_sqlite' in order to run this test");
- }
- }
+ public function testRequiresLayout()
+ {
+ $appender = new PDOAppender();
+ self::assertFalse($appender->requiresLayout());
+ }
- /** Clean up after the last test was run. */
- public static function tearDownAfterClass() {
- @unlink(self::$file);
- }
+ /** Tests new-style logging using prepared statements and the default SQL definition. */
+ public function testSimpleWithDefaults()
+ {
+ // Log event
+ $event = new LoggingEvent("LoggerAppenderPDOTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $appender = new PDOAppender("myname");
+ $appender->setDSN(self::$dsn);
+ $appender->activateOptions();
+ $appender->append($event);
+ $appender->close();
- public function testRequiresLayout() {
- $appender = new PDOAppender();
- self::assertFalse($appender->requiresLayout());
- }
+ // Test the default pattern
+ $db = new PDO(self::$dsn);
+ $query = "SELECT * FROM log4php_log";
+ $sth = $db->query($query);
+ $row = $sth->fetch(PDO::FETCH_NUM);
- /** Tests new-style logging using prepared statements and the default SQL definition. */
- public function testSimpleWithDefaults() {
- // Log event
- $event = new LoggingEvent("LoggerAppenderPDOTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $appender = new PDOAppender("myname");
- $appender->setDSN(self::$dsn);
- $appender->activateOptions();
- $appender->append($event);
- $appender->close();
+ self::assertTrue(is_array($row), "No rows found.");
+ self::assertEquals(7, count($row));
+ self::assertEquals(1, preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $row[0])); // datetime
+ self::assertEquals('TEST', $row[1]); // logger name
+ self::assertEquals('ERROR', $row[2]); // level
+ self::assertEquals('testmessage', $row[3]); // message
+ if (function_exists('posix_getpid')) {
+ self::assertEquals(posix_getpid(), $row[4]); // process id
+ }
+ self::assertEquals('NA', $row[5]); // file, NA due to phpunit magic
+ self::assertEquals('NA', $row[6]); // line, NA due to phpunit magic
+ }
- // Test the default pattern
- $db = new PDO(self::$dsn);
- $query = "SELECT * FROM log4php_log";
- $sth = $db->query($query);
- $row = $sth->fetch(PDO::FETCH_NUM);
+ /** Tests new style prepared statment logging with customized SQL. */
+ public function testCustomizedSql()
+ {
+ $dateFormat = "Y-m-d H:i:s";
- self::assertTrue(is_array($row), "No rows found.");
- self::assertEquals(7, count($row));
- self::assertEquals(1, preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $row[0])); // datetime
- self::assertEquals('TEST', $row[1]); // logger name
- self::assertEquals('ERROR', $row[2]); // level
- self::assertEquals('testmessage', $row[3]); // message
- if (function_exists('posix_getpid')) {
- self::assertEquals(posix_getpid(), $row[4]); // process id
- }
- self::assertEquals('NA', $row[5]); // file, NA due to phpunit magic
- self::assertEquals('NA', $row[6]); // line, NA due to phpunit magic
- }
+ // Prepare appender
+ $appender = new PDOAppender("myname");
+ $appender->setDSN(self::$dsn);
+ $appender->setInsertSql("INSERT INTO log4php_log (file, line, thread, timestamp, logger, level, message) VALUES (?,?,?,?,?,?,?)");
+ $appender->setInsertPattern("%F,%L,%t,%d\{$dateFormat\},%c,%p,%m");
+ $appender->activateOptions();
+ // Action!
+ $event = new LoggingEvent("LoggerAppenderPDOTest2", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $appender->append($event);
- /** Tests new style prepared statment logging with customized SQL. */
- public function testCustomizedSql() {
+ // Check
+ $db = new PDO(self::$dsn);
+ $result = $db->query("SELECT * FROM log4php_log");
+ $row = $result->fetch(PDO::FETCH_OBJ);
+ self::assertTrue(is_object($row));
+ self::assertEquals("NA", $row->file); // "NA" due to phpunit magic
+ self::assertEquals("NA", $row->line); // "NA" due to phpunit magic
+ if (function_exists('posix_getpid')) {
+ self::assertEquals(posix_getpid(), $row->thread);
+ }
+ self::assertEquals(1, preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $row->timestamp));
+ self::assertEquals('TEST', $row->logger);
+ self::assertEquals('ERROR', $row->level);
+ self::assertEquals('testmessage', $row->message);
+ }
- $dateFormat = "Y-m-d H:i:s";
+ /**
+ * Tests a warning is shown when connecting to invalid dns.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage invalid data source name
+ */
+ public function testException()
+ {
+ $dsn = 'doenotexist';
+ $appender = new PDOAppender("myname");
+ $appender->setDSN($dsn);
+ $appender->activateOptions();
+ }
- // Prepare appender
- $appender = new PDOAppender("myname");
- $appender->setDSN(self::$dsn);
- $appender->setInsertSql("INSERT INTO log4php_log (file, line, thread, timestamp, logger, level, message) VALUES (?,?,?,?,?,?,?)");
- $appender->setInsertPattern("%F,%L,%t,%d\{$dateFormat\},%c,%p,%m");
- $appender->activateOptions();
+ /**
+ * Check whether close() actually closes the database connection.
+ */
+ public function testClose()
+ {
+ $event = new LoggingEvent("LoggerAppenderPDOTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- // Action!
- $event = new LoggingEvent("LoggerAppenderPDOTest2", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $appender->append($event);
+ $appender = new PDOAppender("myname");
+ $appender->setDSN(self::$dsn);
+ $appender->activateOptions();
+ $appender->append($event);
+ $appender->close();
- // Check
- $db = new PDO(self::$dsn);
- $result = $db->query("SELECT * FROM log4php_log");
- $row = $result->fetch(PDO::FETCH_OBJ);
- self::assertTrue(is_object($row));
- self::assertEquals("NA", $row->file); // "NA" due to phpunit magic
- self::assertEquals("NA", $row->line); // "NA" due to phpunit magic
- if (function_exists('posix_getpid')) {
- self::assertEquals(posix_getpid(), $row->thread);
- }
- self::assertEquals(1, preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $row->timestamp));
- self::assertEquals('TEST', $row->logger);
- self::assertEquals('ERROR', $row->level);
- self::assertEquals('testmessage', $row->message);
- }
-
- /**
- * Tests a warning is shown when connecting to invalid dns.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage invalid data source name
- */
- public function testException() {
- $dsn = 'doenotexist';
- $appender = new PDOAppender("myname");
- $appender->setDSN($dsn);
- $appender->activateOptions();
- }
-
- /**
- * Check whether close() actually closes the database connection.
- */
- public function testClose() {
- $event = new LoggingEvent("LoggerAppenderPDOTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
-
- $appender = new PDOAppender("myname");
- $appender->setDSN(self::$dsn);
- $appender->activateOptions();
- $appender->append($event);
- $appender->close();
-
- self::assertNull($appender->getDatabaseHandle());
- }
+ self::assertNull($appender->getDatabaseHandle());
+ }
}
diff --git a/tests/src/Appenders/PhpAppenderTest.php b/tests/src/Appenders/PhpAppenderTest.php
index 0653f65..7fb0ddc 100644
--- a/tests/src/Appenders/PhpAppenderTest.php
+++ b/tests/src/Appenders/PhpAppenderTest.php
@@ -28,71 +28,74 @@
/**
* @group appenders
*/
-class PhpAppenderTest extends \PHPUnit_Framework_TestCase {
+class PhpAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ public static $expectedMessage;
- public static $expectedMessage;
+ public static $expectedError;
- public static $expectedError;
+ private $config = array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ 'level' => 'trace'
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'PhpAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ )
+ )
+ );
- private $config = array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- 'level' => 'trace'
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'PhpAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- )
- )
- );
-
- protected function setUp() {
- $that = $this; // hack for PHP 5.3
- set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($that) {
- $that::assertEquals($that::$expectedError, $errno);
- $that::assertEquals($that::$expectedMessage, $errstr);
- });
- }
-
- public function testRequiresLayout() {
- $appender = new PhpAppender();
- $this->assertTrue($appender->requiresLayout());
- }
-
- public function testPhp() {
- Logger::configure($this->config);
- $logger = Logger::getRootLogger();
-
-
- self::$expectedError = E_USER_ERROR;
- self::$expectedMessage = "FATAL - This is a test" . PHP_EOL;
- $logger->fatal("This is a test");
-
- self::$expectedError = E_USER_ERROR;
- self::$expectedMessage = "ERROR - This is a test" . PHP_EOL;
- $logger->error("This is a test");
-
- self::$expectedError = E_USER_WARNING;
- self::$expectedMessage = "WARN - This is a test" . PHP_EOL;
- $logger->warn("This is a test");
-
- self::$expectedError = E_USER_NOTICE;
- self::$expectedMessage = "INFO - This is a test" . PHP_EOL;
- $logger->info("This is a test");
-
- self::$expectedError = E_USER_NOTICE;
- self::$expectedMessage = "DEBUG - This is a test" . PHP_EOL;
- $logger->debug("This is a test");
-
- self::$expectedError = E_USER_NOTICE;
- self::$expectedMessage = "TRACE - This is a test" . PHP_EOL;
- $logger->trace("This is a test");
+ protected function setUp()
+ {
+ $that = $this; // hack for PHP 5.3
+ set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($that) {
+ $that::assertEquals($that::$expectedError, $errno);
+ $that::assertEquals($that::$expectedMessage, $errstr);
+ });
}
- protected function tearDown() {
- restore_error_handler();
- }
+ public function testRequiresLayout()
+ {
+ $appender = new PhpAppender();
+ $this->assertTrue($appender->requiresLayout());
+ }
+
+ public function testPhp()
+ {
+ Logger::configure($this->config);
+ $logger = Logger::getRootLogger();
+
+ self::$expectedError = E_USER_ERROR;
+ self::$expectedMessage = "FATAL - This is a test" . PHP_EOL;
+ $logger->fatal("This is a test");
+
+ self::$expectedError = E_USER_ERROR;
+ self::$expectedMessage = "ERROR - This is a test" . PHP_EOL;
+ $logger->error("This is a test");
+
+ self::$expectedError = E_USER_WARNING;
+ self::$expectedMessage = "WARN - This is a test" . PHP_EOL;
+ $logger->warn("This is a test");
+
+ self::$expectedError = E_USER_NOTICE;
+ self::$expectedMessage = "INFO - This is a test" . PHP_EOL;
+ $logger->info("This is a test");
+
+ self::$expectedError = E_USER_NOTICE;
+ self::$expectedMessage = "DEBUG - This is a test" . PHP_EOL;
+ $logger->debug("This is a test");
+
+ self::$expectedError = E_USER_NOTICE;
+ self::$expectedMessage = "TRACE - This is a test" . PHP_EOL;
+ $logger->trace("This is a test");
+ }
+
+ protected function tearDown()
+ {
+ restore_error_handler();
+ }
}
diff --git a/tests/src/Appenders/RollingFileAppenderTest.php b/tests/src/Appenders/RollingFileAppenderTest.php
index d284f3c..725abc8 100644
--- a/tests/src/Appenders/RollingFileAppenderTest.php
+++ b/tests/src/Appenders/RollingFileAppenderTest.php
@@ -25,188 +25,196 @@
use Apache\Log4php\Appenders\RollingFileAppender;
use Apache\Log4php\Layouts\SimpleLayout;
use Apache\Log4php\Tests\TestHelper;
-use Apache\Log4php\LoggingEvent;
use Apache\Log4php\Logger;
-use Apache\Log4php\Level;
/**
* @group appenders
*/
-class RollingFileAppenderTest extends \PHPUnit_Framework_TestCase {
+class RollingFileAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ const WARNING_MASSAGE = 'WARN - my messageXYZ';
- const WARNING_MASSAGE = 'WARN - my messageXYZ';
+ protected function setUp()
+ {
+ @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt');
+ @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1');
+ @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2');
+ }
- protected function setUp() {
- @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt');
- @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1');
- @unlink(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2');
- }
+ public function testRequiresLayout()
+ {
+ $appender = new RollingFileAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new RollingFileAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testMaxFileSize()
+ {
+ $appender = new RollingFileAppender("mylogger");
- public function testMaxFileSize() {
- $appender = new RollingFileAppender("mylogger");
+ $appender->setMaxFileSize('1KB');
+ self::assertEquals(1024, $appender->getMaxFileSize());
- $appender->setMaxFileSize('1KB');
- self::assertEquals(1024, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('2KB');
+ self::assertEquals(2048, $appender->getMaxFileSize());
- $appender->setMaxFileSize('2KB');
- self::assertEquals(2048, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('1MB');
+ self::assertEquals(1048576, $appender->getMaxFileSize());
- $appender->setMaxFileSize('1MB');
- self::assertEquals(1048576, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('3MB');
+ self::assertEquals(3145728, $appender->getMaxFileSize());
- $appender->setMaxFileSize('3MB');
- self::assertEquals(3145728, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('1GB');
+ self::assertEquals(1073741824, $appender->getMaxFileSize());
- $appender->setMaxFileSize('1GB');
- self::assertEquals(1073741824, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('10000');
+ self::assertEquals(10000, $appender->getMaxFileSize());
- $appender->setMaxFileSize('10000');
- self::assertEquals(10000, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('100.5');
+ self::assertEquals(100, $appender->getMaxFileSize());
- $appender->setMaxFileSize('100.5');
- self::assertEquals(100, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('1000.6');
+ self::assertEquals(1000, $appender->getMaxFileSize());
- $appender->setMaxFileSize('1000.6');
- self::assertEquals(1000, $appender->getMaxFileSize());
+ $appender->setMaxFileSize('1.5MB');
+ self::assertEquals(1572864, $appender->getMaxFileSize());
+ }
- $appender->setMaxFileSize('1.5MB');
- self::assertEquals(1572864, $appender->getMaxFileSize());
- }
+ /**
+ * @return RollingFileAppender
+ */
+ private function createRolloverAppender()
+ {
+ $layout = new SimpleLayout();
- /**
- * @return RollingFileAppender
- */
- private function createRolloverAppender() {
- $layout = new SimpleLayout();
+ $appender = new RollingFileAppender("mylogger");
+ $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt');
+ $appender->setLayout($layout);
+ $appender->setMaxFileSize('1KB');
+ $appender->setMaxBackupIndex(2);
+ $appender->activateOptions();
- $appender = new RollingFileAppender("mylogger");
- $appender->setFile(PHPUNIT_TEMP_DIR . '/TEST-rolling.txt');
- $appender->setLayout($layout);
- $appender->setMaxFileSize('1KB');
- $appender->setMaxBackupIndex(2);
- $appender->activateOptions();
+ return $appender;
+ }
- return $appender;
- }
+ public function testSimpleLogging()
+ {
+ $appender = $this->createRolloverAppender();
- public function testSimpleLogging() {
- $appender = $this->createRolloverAppender();
+ $event = TestHelper::getWarnEvent("my message123");
- $event = TestHelper::getWarnEvent("my message123");
+ for ($i = 0; $i < 1000; $i++) {
+ $appender->append($event);
+ }
- for($i = 0; $i < 1000; $i++) {
- $appender->append($event);
- }
+ $appender->append(TestHelper::getWarnEvent("my messageXYZ"));
- $appender->append(TestHelper::getWarnEvent("my messageXYZ"));
+ $appender->close();
- $appender->close();
+ $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt';
+ $data = file($file);
+ $line = $data[count($data)-1];
+ $e = "WARN - my messageXYZ".PHP_EOL;
+ self::assertEquals($e, $line);
- $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt';
- $data = file($file);
- $line = $data[count($data)-1];
- $e = "WARN - my messageXYZ".PHP_EOL;
- self::assertEquals($e, $line);
+ $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1';
+ $this->checkFileContent($file);
- $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1';
- $this->checkFileContent($file);
+ $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2';
+ $this->checkFileContent($file);
- $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2';
- $this->checkFileContent($file);
+ // Should not roll over three times
+ $this->assertFalse(file_exists(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.3'));
+ }
- // Should not roll over three times
- $this->assertFalse(file_exists(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.3'));
- }
+ public function testLoggingViaLogger()
+ {
+ $logger = Logger::getLogger('mycat');
+ $logger->setAdditivity(false);
- public function testLoggingViaLogger() {
- $logger = Logger::getLogger('mycat');
- $logger->setAdditivity(false);
+ $appender = $this->createRolloverAppender();
- $appender = $this->createRolloverAppender();
+ $logger->addAppender($appender);
- $logger->addAppender($appender);
+ for ($i = 0; $i < 1000; $i++) {
+ $logger->warn("my message123");
+ }
- for($i = 0; $i < 1000; $i++) {
- $logger->warn("my message123");
- }
+ $logger->warn("my messageXYZ");
- $logger->warn("my messageXYZ");
+ $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt';
+ $data = file($file);
- $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt';
- $data = file($file);
+ $line = $data[count($data)-1];
+ $e = "WARN - my messageXYZ".PHP_EOL;
+ self::assertEquals($e, $line);
- $line = $data[count($data)-1];
- $e = "WARN - my messageXYZ".PHP_EOL;
- self::assertEquals($e, $line);
+ $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1';
+ $this->checkFileContent($file);
- $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1';
- $this->checkFileContent($file);
+ $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2';
+ $this->checkFileContent($file);
- $file = PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2';
- $this->checkFileContent($file);
+ $this->assertFalse(file_exists(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.3'), 'should not roll over three times');
+ }
- $this->assertFalse(file_exists(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.3'), 'should not roll over three times');
- }
+ public function testRolloverWithCompression()
+ {
+ $logger = Logger::getLogger('mycat');
+ $logger->setAdditivity(false);
- public function testRolloverWithCompression() {
- $logger = Logger::getLogger('mycat');
- $logger->setAdditivity(false);
+ $appender = $this->createRolloverAppender();
+ $appender->setCompress(true);
- $appender = $this->createRolloverAppender();
- $appender->setCompress(true);
+ $logger->addAppender($appender);
- $logger->addAppender($appender);
+ for ($i = 0; $i < 1000; $i++) {
+ $logger->warn(self::WARNING_MASSAGE. $i);
+ }
- for($i = 0; $i < 1000; $i++) {
- $logger->warn(self::WARNING_MASSAGE. $i);
- }
+ $logger->warn("my messageXYZ");
- $logger->warn("my messageXYZ");
+ $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt';
+ $data = file($file);
- $file = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt';
- $data = file($file);
+ $line = $data[count($data)-1];
+ $e = self::WARNING_MASSAGE.PHP_EOL;
+ self::assertEquals($e, $line);
- $line = $data[count($data)-1];
- $e = self::WARNING_MASSAGE.PHP_EOL;
- self::assertEquals($e, $line);
+ $firstCompressedRollingFile = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1.gz';
+ $this->assertTrue(file_exists($firstCompressedRollingFile),'TEST-rolling.txt.1.gz not found');
- $firstCompressedRollingFile = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1.gz';
- $this->assertTrue(file_exists($firstCompressedRollingFile),'TEST-rolling.txt.1.gz not found');
+ $firstUncompressedRollingField = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1';
+ $this->assertFalse(file_exists($firstUncompressedRollingField),'TEST-rolling.txt.1 should be replaced by compressed');
- $firstUncompressedRollingField = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.1';
- $this->assertFalse(file_exists($firstUncompressedRollingField),'TEST-rolling.txt.1 should be replaced by compressed');
+ $secondCompressedRollingFile = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2.gz';
+ $this->assertTrue(file_exists($secondCompressedRollingFile), 'TEST-rolling.txt.2.gz not found');
- $secondCompressedRollingFile = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2.gz';
- $this->assertTrue(file_exists($secondCompressedRollingFile), 'TEST-rolling.txt.2.gz not found');
+ $secondUncompressedRollingField = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2';
+ $this->assertFalse(file_exists($secondUncompressedRollingField),'TEST-rolling.txt.2 should be replaced by compressed');
- $secondUncompressedRollingField = PHPUNIT_TEMP_DIR . '/TEST-rolling.txt.2';
- $this->assertFalse(file_exists($secondUncompressedRollingField),'TEST-rolling.txt.2 should be replaced by compressed');
+ }
- }
+ private function checkFileContent($file)
+ {
+ $data = file($file);
+ $this->checkText($data);
+ }
- private function checkFileContent($file) {
- $data = file($file);
- $this->checkText($data);
- }
+ private function checkText($text)
+ {
+ $line = $text[count($text)-1];
+ $e = "WARN - my message123".PHP_EOL;
+ foreach ($text as $r) {
+ self::assertEquals($e, $r);
+ }
+ }
- private function checkText($text) {
- $line = $text[count($text)-1];
- $e = "WARN - my message123".PHP_EOL;
- foreach($text as $r) {
- self::assertEquals($e, $r);
- }
- }
-
- protected function tearDown() {
- @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt');
- @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1');
- @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2');
- @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1.gz');
- @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2.gz');
- }
+ protected function tearDown()
+ {
+ @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt');
+ @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1');
+ @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2');
+ @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.1.gz');
+ @unlink(PHPUNIT_TEMP_DIR.'/TEST-rolling.txt.2.gz');
+ }
}
diff --git a/tests/src/Appenders/SocketAppenderTest.php b/tests/src/Appenders/SocketAppenderTest.php
index 9cd1482..27c9ef1 100644
--- a/tests/src/Appenders/SocketAppenderTest.php
+++ b/tests/src/Appenders/SocketAppenderTest.php
@@ -28,124 +28,132 @@
/**
* @group appenders
*/
-class SocketAppenderTest extends \PHPUnit_Framework_TestCase {
+class SocketAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ /** Port on which the socket server will run. */
+ const SOCKET_PORT = 12345;
- /** Port on which the socket server will run. */
- const SOCKET_PORT = 12345;
+ /** The socket server process resource. */
+ private $server;
- /** The socket server process resource. */
- private $server;
+ /** The pipes array for the server process. */
+ private $pipes;
- /** The pipes array for the server process. */
- private $pipes;
+ public function setUp()
+ {
+ Logger::clear();
+ }
- public function setUp() {
- Logger::clear();
- }
+ public function tearDown()
+ {
+ Logger::clear();
+ }
- public function tearDown() {
- Logger::clear();
- }
+ public function testRequiresLayout()
+ {
+ $appender = new SocketAppender();
+ self::assertTrue($appender->requiresLayout());
+ }
- public function testRequiresLayout() {
- $appender = new SocketAppender();
- self::assertTrue($appender->requiresLayout());
- }
+ public function testLogging()
+ {
+ Logger::configure(array(
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'SocketAppender',
+ 'params' => array(
+ 'remoteHost' => 'localhost',
+ 'port' => self::SOCKET_PORT
+ ),
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ )
+ ),
+ ),
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ ));
- public function testLogging()
- {
- Logger::configure(array(
- 'appenders' => array(
- 'default' => array(
- 'class' => 'SocketAppender',
- 'params' => array(
- 'remoteHost' => 'localhost',
- 'port' => self::SOCKET_PORT
- ),
- 'layout' => array(
- 'class' => 'SimpleLayout'
- )
- ),
- ),
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- ));
+ $this->startServer();
- $this->startServer();
+ $logger = Logger::getLogger("myLogger");
+ $logger->trace("This message is a test");
+ $logger->debug("This message is a test");
+ $logger->info("This message is a test");
+ $logger->warn("This message is a test");
+ $logger->error("This message is a test");
+ $logger->fatal("This message is a test");
- $logger = Logger::getLogger("myLogger");
- $logger->trace("This message is a test");
- $logger->debug("This message is a test");
- $logger->info("This message is a test");
- $logger->warn("This message is a test");
- $logger->error("This message is a test");
- $logger->fatal("This message is a test");
+ $actual = $this->getPlayback();
+ $this->stopServer();
- $actual = $this->getPlayback();
- $this->stopServer();
+ $expected = "DEBUG - This message is a test" .
+ "INFO - This message is a test" .
+ "WARN - This message is a test" .
+ "ERROR - This message is a test" .
+ "FATAL - This message is a test";
- $expected = "DEBUG - This message is a test" .
- "INFO - This message is a test" .
- "WARN - This message is a test" .
- "ERROR - This message is a test" .
- "FATAL - This message is a test";
+ $this->assertEquals($expected, $actual);
+ }
- $this->assertEquals($expected, $actual);
- }
+ /** Starts a socket server in a separate process. */
+ private function startServer()
+ {
+ $serverLog = PHPUNIT_TEMP_DIR . '/socketServer.log';
+ $descriptorspec = array(
+ 0 => array("pipe", "r"), // stdin
+ 1 => array("file", $serverLog, "a"),// stdout
+ 2 => array("file", $serverLog, "a") // stderr
+ );
- /** Starts a socket server in a separate process. */
- private function startServer() {
- $serverLog = PHPUNIT_TEMP_DIR . '/socketServer.log';
- $descriptorspec = array(
- 0 => array("pipe", "r"), // stdin
- 1 => array("file", $serverLog, "a"),// stdout
- 2 => array("file", $serverLog, "a") // stderr
- );
+ $cmd = "php " . dirname(__FILE__) . '/socketServer.php';
+ $this->server = proc_open($cmd, $descriptorspec, $this->pipes);
+ if ($this->server === false) {
+ throw new Exception("Failed starting the socket server process.");
+ }
- $cmd = "php " . dirname(__FILE__) . '/socketServer.php';
- $this->server = proc_open($cmd, $descriptorspec, $this->pipes);
- if ($this->server === false) {
- throw new Exception("Failed starting the socket server process.");
- }
+ // Sleep a bit to allow server to start
+ usleep(200000);
- // Sleep a bit to allow server to start
- usleep(200000);
+ // Verify the server is running
+ $status = proc_get_status($this->server);
+ if (!$status['running']) {
+ throw new Exception("Socket server process failed to start. Check the log at [$serverLog].");
+ }
+ }
- // Verify the server is running
- $status = proc_get_status($this->server);
- if (!$status['running']) {
- throw new Exception("Socket server process failed to start. Check the log at [$serverLog].");
- }
- }
+ /** Sends a message to the socket server and returns the reply. */
+ private function socketSend($msg)
+ {
+ $sock = fsockopen('localhost', self::SOCKET_PORT, $errno, $errstr);
+ if ($sock === false) {
+ throw new Exception("Unable to open socket. Error: [$errno] $errstr");
+ }
- /** Sends a message to the socket server and returns the reply. */
- private function socketSend($msg) {
- $sock = fsockopen('localhost', self::SOCKET_PORT, $errno, $errstr);
- if ($sock === false) {
- throw new Exception("Unable to open socket. Error: [$errno] $errstr");
- }
+ fputs($sock, "$msg\n");
+ $reply = '';
+ while (!feof($sock)) {
+ $reply .= fgets($sock);
+ }
+ fclose($sock);
- fputs($sock, "$msg\n");
- $reply = '';
- while(!feof($sock)) {
- $reply .= fgets($sock);
- }
- fclose($sock);
- return trim($reply);
- }
+ return trim($reply);
+ }
- /** Retrieves a playback of all sent messages from the socket server. */
- private function getPlayback() {
- return $this->socketSend('playback');
- }
+ /** Retrieves a playback of all sent messages from the socket server. */
+ private function getPlayback()
+ {
+ return $this->socketSend('playback');
+ }
- /** Stops the socket server and closes the process. */
- private function stopServer() {
- $this->socketSend('shutdown');
- foreach($this->pipes as $pipe) {
- fclose($pipe);
- }
- proc_close($this->server);
- }
+ /** Stops the socket server and closes the process. */
+ private function stopServer()
+ {
+ $this->socketSend('shutdown');
+ foreach ($this->pipes as $pipe) {
+ fclose($pipe);
+ }
+ proc_close($this->server);
+ }
}
diff --git a/tests/src/Appenders/SyslogAppenderTest.php b/tests/src/Appenders/SyslogAppenderTest.php
index 91b1568..0d13108 100644
--- a/tests/src/Appenders/SyslogAppenderTest.php
+++ b/tests/src/Appenders/SyslogAppenderTest.php
@@ -38,216 +38,224 @@
*
* @group appenders
*/
-class SyslogAppenderTest extends \PHPUnit_Framework_TestCase {
+class SyslogAppenderTest extends \PHPUnit_Framework_TestCase
+{
+ public function testSettersGetters()
+ {
+ // Setters should accept any value, without validation
+ $expected = "Random string value";
- public function testSettersGetters() {
+ $appender = new SyslogAppender();
+ $appender->setIdent($expected);
+ $appender->setFacility($expected);
+ $appender->setOverridePriority($expected);
+ $appender->setPriority($expected);
+ $appender->setOption($expected);
- // Setters should accept any value, without validation
- $expected = "Random string value";
+ $actuals = array(
+ $appender->getIdent(),
+ $appender->getFacility(),
+ $appender->getOverridePriority(),
+ $appender->getPriority(),
+ $appender->getOption()
+ );
- $appender = new SyslogAppender();
- $appender->setIdent($expected);
- $appender->setFacility($expected);
- $appender->setOverridePriority($expected);
- $appender->setPriority($expected);
- $appender->setOption($expected);
+ foreach ($actuals as $actual) {
+ $this->assertSame($expected, $actual);
+ }
+ }
- $actuals = array(
- $appender->getIdent(),
- $appender->getFacility(),
- $appender->getOverridePriority(),
- $appender->getPriority(),
- $appender->getOption()
- );
+ public function testRequiresLayout()
+ {
+ $appender = new SyslogAppender();
+ $this->assertTrue($appender->requiresLayout());
+ }
- foreach($actuals as $actual) {
- $this->assertSame($expected, $actual);
- }
- }
+ public function testLogging()
+ {
+ $appender = new SyslogAppender("myname");
+ $appender->setLayout(new SimpleLayout());
+ $appender->activateOptions();
- public function testRequiresLayout() {
- $appender = new SyslogAppender();
- $this->assertTrue($appender->requiresLayout());
- }
+ $event = new LoggingEvent(__CLASS__, new Logger("TestLogger"), Level::getLevelError(), "testmessage");
+ $appender->append($event);
+ }
- public function testLogging() {
- $appender = new SyslogAppender("myname");
- $appender->setLayout(new SimpleLayout());
- $appender->activateOptions();
+ /** Tests parsing of "option" parameter. */
+ public function testOption()
+ {
+ $options = array(
+ 'CONS' => LOG_CONS,
+ 'NDELAY' => LOG_NDELAY,
+ 'ODELAY' => LOG_ODELAY,
+ 'PERROR' => LOG_PERROR,
+ 'PID' => LOG_PID,
- $event = new LoggingEvent(__CLASS__, new Logger("TestLogger"), Level::getLevelError(), "testmessage");
- $appender->append($event);
- }
+ // test some combinations
+ 'CONS|NDELAY' => LOG_CONS | LOG_NDELAY,
+ 'PID|PERROR' => LOG_PID | LOG_PERROR,
+ 'CONS|PID|NDELAY' => LOG_CONS | LOG_PID | LOG_NDELAY
+ );
- /** Tests parsing of "option" parameter. */
- public function testOption() {
- $options = array(
- 'CONS' => LOG_CONS,
- 'NDELAY' => LOG_NDELAY,
- 'ODELAY' => LOG_ODELAY,
- 'PERROR' => LOG_PERROR,
- 'PID' => LOG_PID,
+ // Defaults
+ $defaultStr = "PID|CONS";
+ $default = LOG_PID | LOG_CONS;
- // test some combinations
- 'CONS|NDELAY' => LOG_CONS | LOG_NDELAY,
- 'PID|PERROR' => LOG_PID | LOG_PERROR,
- 'CONS|PID|NDELAY' => LOG_CONS | LOG_PID | LOG_NDELAY
- );
+ // This makes reading of a private property possible
+ $property = new \ReflectionProperty('Apache\\Log4php\Appenders\\SyslogAppender', 'intOption');
+ $property->setAccessible(true);
- // Defaults
- $defaultStr = "PID|CONS";
- $default = LOG_PID | LOG_CONS;
+ // Check default value first
+ $appender = new SyslogAppender();
+ $appender->activateOptions();
+ $actual = $property->getValue($appender);
+ $this->assertSame($default, $actual, "Failed setting default option [$defaultStr]");
- // This makes reading of a private property possible
- $property = new \ReflectionProperty('Apache\\Log4php\Appenders\\SyslogAppender', 'intOption');
- $property->setAccessible(true);
+ foreach ($options as $option => $expected) {
+ $appender = new SyslogAppender();
+ $appender->setOption($option);
+ $appender->activateOptions();
- // Check default value first
- $appender = new SyslogAppender();
- $appender->activateOptions();
- $actual = $property->getValue($appender);
- $this->assertSame($default, $actual, "Failed setting default option [$defaultStr]");
+ $actual = $property->getValue($appender);
+ $this->assertSame($expected, $actual, "Failed setting option [$option].");
+ }
+ }
- foreach($options as $option => $expected) {
- $appender = new SyslogAppender();
- $appender->setOption($option);
- $appender->activateOptions();
+ /** Tests parsing of "priority" parameter. */
+ public function testPriority()
+ {
+ $default = null;
+ $defaultStr = 'null';
- $actual = $property->getValue($appender);
- $this->assertSame($expected, $actual, "Failed setting option [$option].");
- }
- }
+ $priorities = array(
+ 'EMERG' => LOG_EMERG,
+ 'ALERT' => LOG_ALERT,
+ 'CRIT' => LOG_CRIT,
+ 'ERR' => LOG_ERR,
+ 'WARNING' => LOG_WARNING,
+ 'NOTICE' => LOG_NOTICE,
+ 'INFO' => LOG_INFO,
+ 'DEBUG' => LOG_DEBUG
+ );
- /** Tests parsing of "priority" parameter. */
- public function testPriority() {
- $default = null;
- $defaultStr = 'null';
+ // This makes reading of a private property possible
+ $property = new \ReflectionProperty('Apache\\Log4php\\Appenders\\SyslogAppender', 'intPriority');
+ $property->setAccessible(true);
- $priorities = array(
- 'EMERG' => LOG_EMERG,
- 'ALERT' => LOG_ALERT,
- 'CRIT' => LOG_CRIT,
- 'ERR' => LOG_ERR,
- 'WARNING' => LOG_WARNING,
- 'NOTICE' => LOG_NOTICE,
- 'INFO' => LOG_INFO,
- 'DEBUG' => LOG_DEBUG
- );
+ // Check default value first
+ $appender = new SyslogAppender();
+ $appender->activateOptions();
+ $actual = $property->getValue($appender);
+ $this->assertSame($default, $actual, "Failed setting default priority [$defaultStr].");
- // This makes reading of a private property possible
- $property = new \ReflectionProperty('Apache\\Log4php\\Appenders\\SyslogAppender', 'intPriority');
- $property->setAccessible(true);
+ foreach ($priorities as $priority => $expected) {
+ $appender = new SyslogAppender();
+ $appender->setPriority($priority);
+ $appender->activateOptions();
- // Check default value first
- $appender = new SyslogAppender();
- $appender->activateOptions();
- $actual = $property->getValue($appender);
- $this->assertSame($default, $actual, "Failed setting default priority [$defaultStr].");
+ $actual = $property->getValue($appender);
+ $this->assertSame($expected, $actual, "Failed setting priority [$priority].");
+ }
+ }
- foreach($priorities as $priority => $expected) {
- $appender = new SyslogAppender();
- $appender->setPriority($priority);
- $appender->activateOptions();
+ /** Tests parsing of "facility" parameter. */
+ public function testFacility()
+ {
+ // Default value is the same on all OSs
+ $default = LOG_USER;
+ $defaultStr = 'USER';
- $actual = $property->getValue($appender);
- $this->assertSame($expected, $actual, "Failed setting priority [$priority].");
- }
- }
+ // All possible facility strings (some of which might not exist depending on the OS)
+ $strings = array(
+ 'KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH',
+ 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CRON', 'AUTHPRIV',
+ 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4',
+ 'LOCAL5', 'LOCAL6', 'LOCAL7',
+ );
- /** Tests parsing of "facility" parameter. */
- public function testFacility() {
- // Default value is the same on all OSs
- $default = LOG_USER;
- $defaultStr = 'USER';
+ // Only test facilities which exist on this OS
+ $facilities = array();
+ foreach ($strings as $string) {
+ $const = "LOG_$string";
+ if (defined($const)) {
+ $facilities[$string] = constant($const);
+ }
+ }
- // All possible facility strings (some of which might not exist depending on the OS)
- $strings = array(
- 'KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH',
- 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CRON', 'AUTHPRIV',
- 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4',
- 'LOCAL5', 'LOCAL6', 'LOCAL7',
- );
+ // This makes reading of a private property possible
+ $property = new \ReflectionProperty('Apache\\Log4php\\Appenders\\SyslogAppender', 'intFacility');
+ $property->setAccessible(true);
- // Only test facilities which exist on this OS
- $facilities = array();
- foreach($strings as $string) {
- $const = "LOG_$string";
- if (defined($const)) {
- $facilities[$string] = constant($const);
- }
- }
+ // Check default value first
+ $appender = new SyslogAppender();
+ $appender->activateOptions();
+ $actual = $property->getValue($appender);
+ $this->assertSame($default, $default, "Failed setting default facility [$defaultStr].");
- // This makes reading of a private property possible
- $property = new \ReflectionProperty('Apache\\Log4php\\Appenders\\SyslogAppender', 'intFacility');
- $property->setAccessible(true);
+ foreach ($facilities as $facility => $expected) {
+ $appender = new SyslogAppender();
+ $appender->setFacility($facility);
+ $appender->activateOptions();
- // Check default value first
- $appender = new SyslogAppender();
- $appender->activateOptions();
- $actual = $property->getValue($appender);
- $this->assertSame($default, $default, "Failed setting default facility [$defaultStr].");
+ $actual = $property->getValue($appender);
+ $this->assertSame($expected, $actual, "Failed setting priority [$facility].");
+ }
+ }
- foreach($facilities as $facility => $expected) {
- $appender = new SyslogAppender();
- $appender->setFacility($facility);
- $appender->activateOptions();
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInvalidOption()
+ {
+ $appender = new SyslogAppender();
+ $appender->setOption('CONS|XYZ');
+ $appender->activateOptions();
+ }
- $actual = $property->getValue($appender);
- $this->assertSame($expected, $actual, "Failed setting priority [$facility].");
- }
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInvalidPriority()
+ {
+ $appender = new SyslogAppender();
+ $appender->setPriority('XYZ');
+ $appender->activateOptions();
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInvalidOption() {
- $appender = new SyslogAppender();
- $appender->setOption('CONS|XYZ');
- $appender->activateOptions();
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInvalidFacility()
+ {
+ $appender = new SyslogAppender();
+ $appender->setFacility('XYZ');
+ $appender->activateOptions();
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInvalidPriority() {
- $appender = new SyslogAppender();
- $appender->setPriority('XYZ');
- $appender->activateOptions();
- }
+ public function testPriorityOverride()
+ {
+ $appender = new SyslogAppender();
+ $appender->setPriority('EMERG');
+ $appender->setOverridePriority(true);
+ $appender->activateOptions();
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInvalidFacility() {
- $appender = new SyslogAppender();
- $appender->setFacility('XYZ');
- $appender->activateOptions();
- }
+ $levels = array(
+ Level::getLevelTrace(),
+ Level::getLevelDebug(),
+ Level::getLevelInfo(),
+ Level::getLevelWarn(),
+ Level::getLevelError(),
+ Level::getLevelFatal(),
+ );
+ $expected = LOG_EMERG;
- public function testPriorityOverride() {
- $appender = new SyslogAppender();
- $appender->setPriority('EMERG');
- $appender->setOverridePriority(true);
- $appender->activateOptions();
+ $method = new \ReflectionMethod('Apache\\Log4php\\Appenders\\SyslogAppender', 'getSyslogPriority');
+ $method->setAccessible(true);
- $levels = array(
- Level::getLevelTrace(),
- Level::getLevelDebug(),
- Level::getLevelInfo(),
- Level::getLevelWarn(),
- Level::getLevelError(),
- Level::getLevelFatal(),
- );
-
- $expected = LOG_EMERG;
-
- $method = new \ReflectionMethod('Apache\\Log4php\\Appenders\\SyslogAppender', 'getSyslogPriority');
- $method->setAccessible(true);
-
- foreach($levels as $level) {
- $actual = $method->invoke($appender, $level);
- $this->assertSame($expected, $actual);
- }
- }
+ foreach ($levels as $level) {
+ $actual = $method->invoke($appender, $level);
+ $this->assertSame($expected, $actual);
+ }
+ }
}
diff --git a/tests/src/Appenders/socketServer.php b/tests/src/Appenders/socketServer.php
index 19a7b7c..07c464e 100644
--- a/tests/src/Appenders/socketServer.php
+++ b/tests/src/Appenders/socketServer.php
@@ -32,19 +32,19 @@
// Create a socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($sock === false) {
- die("Failed creating socket: " . socket_strerror(socket_last_error()));
+ die("Failed creating socket: " . socket_strerror(socket_last_error()));
}
if (socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1) === false) {
- die("Failed setting socket options: " . socket_strerror(socket_last_error()));
+ die("Failed setting socket options: " . socket_strerror(socket_last_error()));
}
if (socket_bind($sock, 'localhost', SERVER_PORT) === false) {
- die("Failed binding socket: " . socket_strerror(socket_last_error()));
+ die("Failed binding socket: " . socket_strerror(socket_last_error()));
}
if (socket_listen($sock, 100) === false) {
- die("Failed binding socket: " . socket_strerror(socket_last_error()));
+ die("Failed binding socket: " . socket_strerror(socket_last_error()));
}
socket_getsockname($sock, $addr, $port);
@@ -53,43 +53,42 @@
// Buffer which will store incoming messages
$playback = "";
-while(true) {
- myLog("Waiting for incoming connections...");
+while (true) {
+ myLog("Waiting for incoming connections...");
- $msgsock = socket_accept($sock);
- if ($msgsock === false) {
- myLog("Failed accepting a connection: " . socket_strerror(socket_last_error()));
- break;
- }
+ $msgsock = socket_accept($sock);
+ if ($msgsock === false) {
+ myLog("Failed accepting a connection: " . socket_strerror(socket_last_error()));
+ break;
+ }
- $buf = socket_read($msgsock, 2048, PHP_NORMAL_READ);
+ $buf = socket_read($msgsock, 2048, PHP_NORMAL_READ);
- myLog('Received: "' . trim($buf) . '"');
+ myLog('Received: "' . trim($buf) . '"');
- // Shutdown command
- if (trim($buf) == 'shutdown') {
- myLog("Shutting down.");
- socket_close($msgsock);
- break;
- }
- // Playback command
- else if (trim($buf) == 'playback') {
- myLog("Returning playback: \"$playback\"");
- socket_write($msgsock, $playback);
- }
- // Default: add to playback buffer
- else {
- $playback .= trim($buf);
- }
+ // Shutdown command
+ if (trim($buf) == 'shutdown') {
+ myLog("Shutting down.");
+ socket_close($msgsock);
+ break;
+ }
+ // Playback command
+ else if (trim($buf) == 'playback') {
+ myLog("Returning playback: \"$playback\"");
+ socket_write($msgsock, $playback);
+ }
+ // Default: add to playback buffer
+ else {
+ $playback .= trim($buf);
+ }
- socket_close($msgsock);
+ socket_close($msgsock);
}
myLog("Closing socket.");
socket_close($sock);
-function myLog($msg) {
- echo date("Y-m-d H:i:s") . " $msg\n";
+function myLog($msg)
+{
+ echo date("Y-m-d H:i:s") . " $msg\n";
}
-
-?>
diff --git a/tests/src/ConfiguratorTest.php b/tests/src/ConfiguratorTest.php
index b6fb802..d38cc0c 100644
--- a/tests/src/ConfiguratorTest.php
+++ b/tests/src/ConfiguratorTest.php
@@ -30,8 +30,9 @@
use Mockery as m;
-class CostumDefaultRenderer implements RendererInterface {
- public function render($o) { }
+class CostumDefaultRenderer implements RendererInterface
+{
+ public function render($o) { }
}
/**
@@ -39,68 +40,74 @@
*/
class ConfiguratorTest extends \PHPUnit_Framework_TestCase
{
- /** Reset configuration after each test. */
- public function setUp() {
- Logger::resetConfiguration();
- }
- /** Reset configuration after each test. */
- public function tearDown() {
- Logger::resetConfiguration();
- }
+ /** Reset configuration after each test. */
+ public function setUp()
+ {
+ Logger::resetConfiguration();
+ }
+ /** Reset configuration after each test. */
+ public function tearDown()
+ {
+ Logger::resetConfiguration();
+ }
- /** Check default setup. */
- public function testDefaultConfig() {
- Logger::configure();
+ /** Check default setup. */
+ public function testDefaultConfig()
+ {
+ Logger::configure();
- $actual = Logger::getCurrentLoggers();
- $expected = array();
- $this->assertSame($expected, $actual);
+ $actual = Logger::getCurrentLoggers();
+ $expected = array();
+ $this->assertSame($expected, $actual);
- $appenders = Logger::getRootLogger()->getAllAppenders();
- $this->assertInternalType('array', $appenders);
- $this->assertEquals(count($appenders), 1);
+ $appenders = Logger::getRootLogger()->getAllAppenders();
+ $this->assertInternalType('array', $appenders);
+ $this->assertEquals(count($appenders), 1);
- $names = array_keys($appenders);
- $this->assertSame('default', $names[0]);
+ $names = array_keys($appenders);
+ $this->assertSame('default', $names[0]);
- $appender = array_shift($appenders);
- $this->assertInstanceOf('Apache\\Log4php\\Appenders\\EchoAppender', $appender);
- $this->assertSame('default', $appender->getName());
+ $appender = array_shift($appenders);
+ $this->assertInstanceOf('Apache\\Log4php\\Appenders\\EchoAppender', $appender);
+ $this->assertSame('default', $appender->getName());
- $layout = $appender->getLayout();
- $this->assertInstanceOf('Apache\\Log4php\\Layouts\\SimpleLayout', $layout);
+ $layout = $appender->getLayout();
+ $this->assertInstanceOf('Apache\\Log4php\\Layouts\\SimpleLayout', $layout);
- $root = Logger::getRootLogger();
- $appenders = $root->getAllAppenders();
- $this->assertInternalType('array', $appenders);
- $this->assertEquals(count($appenders), 1);
+ $root = Logger::getRootLogger();
+ $appenders = $root->getAllAppenders();
+ $this->assertInternalType('array', $appenders);
+ $this->assertEquals(count($appenders), 1);
- $actual = $root->getLevel();
- $expected = Level::getLevelDebug();
- $this->assertEquals($expected, $actual);
- }
+ $actual = $root->getLevel();
+ $expected = Level::getLevelDebug();
+ $this->assertEquals($expected, $actual);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid configuration param given. Reverting to default configuration.
- */
- public function testInputIsInteger() {
- Logger::configure(12345);
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid configuration param given. Reverting to default configuration.
+ */
+ public function testInputIsInteger()
+ {
+ Logger::configure(12345);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Configuration failed. Unsupported configuration file extension: yml
- */
- public function testYAMLFile() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/config.yml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Configuration failed. Unsupported configuration file extension: yml
+ */
+ public function testYAMLFile()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/config.yml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid configuration provided for appender
- */
- public function testAppenderConfigNotArray() {
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid configuration provided for appender
+ */
+ public function testAppenderConfigNotArray()
+ {
$config = array(
'appenders' => array(
'default',
@@ -110,344 +117,362 @@
$hierachyMock = m::mock("Apache\\Log4php\\Hierarchy");
$configurator = new DefaultConfigurator();
$configurator->configure($hierachyMock, $config);
- }
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage No class given for appender
- */
- public function testNoAppenderClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_no_class.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage No class given for appender
+ */
+ public function testNoAppenderClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_no_class.xml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid class [unknownClass] given for appender [foo]. Class does not exist. Skipping appender definition.
- */
- public function testNotExistingAppenderClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_class.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid class [unknownClass] given for appender [foo]. Class does not exist. Skipping appender definition.
+ */
+ public function testNotExistingAppenderClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_class.xml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid class [stdClass] given for appender [foo]. Not a valid Appender class. Skipping appender definition.
- */
- public function testInvalidAppenderClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_appender_class.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid class [stdClass] given for appender [foo]. Not a valid Appender class. Skipping appender definition.
+ */
+ public function testInvalidAppenderClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_appender_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Nonexistant filter class [Foo] specified on appender [foo]. Skipping filter definition.
- */
- public function testNotExistingAppenderFilterClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_filter_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Nonexistant filter class [Foo] specified on appender [foo]. Skipping filter definition.
+ */
+ public function testNotExistingAppenderFilterClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_filter_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Nonexistant option [fooParameter] specified on [Apache\Log4php\Filters\StringMatchFilter]. Skipping.
- */
- public function testInvalidAppenderFilterParamter() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_filter_parameters.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Nonexistant option [fooParameter] specified on [Apache\Log4php\Filters\StringMatchFilter]. Skipping.
+ */
+ public function testInvalidAppenderFilterParamter()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_filter_parameters.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid filter class [stdClass] sepcified on appender [foo]. Skipping filter definition.
- */
- public function testInvalidAppenderFilterClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_filter_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid filter class [stdClass] sepcified on appender [foo]. Skipping filter definition.
+ */
+ public function testInvalidAppenderFilterClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_filter_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Nonexistant layout class [Foo] specified for appender [foo]. Reverting to default layout.
- */
- public function testNotExistingAppenderLayoutClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_layout_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Nonexistant layout class [Foo] specified for appender [foo]. Reverting to default layout.
+ */
+ public function testNotExistingAppenderLayoutClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_not_existing_layout_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid layout class [stdClass] sepcified for appender [foo]. Reverting to default layout.
- */
- public function testInvalidAppenderLayoutClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_layout_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid layout class [stdClass] sepcified for appender [foo]. Reverting to default layout.
+ */
+ public function testInvalidAppenderLayoutClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_invalid_layout_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Layout class not specified for appender [foo]. Reverting to default layout.
- */
- public function testNoAppenderLayoutClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_no_layout_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Layout class not specified for appender [foo]. Reverting to default layout.
+ */
+ public function testNoAppenderLayoutClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/appenders/config_no_layout_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed adding renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
- */
- public function testInvalidRenderingClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_invalid_rendering_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed adding renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
+ */
+ public function testInvalidRenderingClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_invalid_rendering_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Rendering class not specified. Skipping renderer definition.
- */
- public function testNoRenderingClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_no_rendering_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Rendering class not specified. Skipping renderer definition.
+ */
+ public function testNoRenderingClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_no_rendering_class.xml');
+ }
/**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Rendered class not specified. Skipping renderer definition.
- */
- public function testNoRenderedClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_no_rendered_class.xml');
- }
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Rendered class not specified. Skipping renderer definition.
+ */
+ public function testNoRenderedClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_no_rendered_class.xml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed adding renderer. Rendering class [DoesNotExistRenderer] not found.
- */
- public function testNotExistingRenderingClassSet() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_not_existing_rendering_class.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed adding renderer. Rendering class [DoesNotExistRenderer] not found.
+ */
+ public function testNotExistingRenderingClassSet()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_not_existing_rendering_class.xml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid additivity value [4711] specified for logger [myLogger].
- */
- public function testInvalidLoggerAddivity() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/loggers/config_invalid_additivity.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid additivity value [4711] specified for logger [myLogger].
+ */
+ public function testInvalidLoggerAddivity()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/loggers/config_invalid_additivity.xml');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Nonexistnant appender [unknownAppender] linked to logger [myLogger].
- */
- public function testNotExistingLoggerAppendersClass() {
- Logger::configure(PHPUNIT_CONFIG_DIR . '/loggers/config_not_existing_appenders.xml');
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Nonexistnant appender [unknownAppender] linked to logger [myLogger].
+ */
+ public function testNotExistingLoggerAppendersClass()
+ {
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/loggers/config_not_existing_appenders.xml');
+ }
- /**
- * Test that an error is reported when config file is not found.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Configuration failed. File not found
- */
- public function testNonexistantFile() {
- Logger::configure('hopefully/this/path/doesnt/exist/config.xml');
+ /**
+ * Test that an error is reported when config file is not found.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Configuration failed. File not found
+ */
+ public function testNonexistantFile()
+ {
+ Logger::configure('hopefully/this/path/doesnt/exist/config.xml');
- }
+ }
- /** Test correct fallback to the default configuration. */
- public function testNonexistantFileFallback() {
- @Logger::configure('hopefully/this/path/doesnt/exist/config.xml');
- $this->testDefaultConfig();
- }
+ /** Test correct fallback to the default configuration. */
+ public function testNonexistantFileFallback()
+ {
+ @Logger::configure('hopefully/this/path/doesnt/exist/config.xml');
+ $this->testDefaultConfig();
+ }
- public function testAppendersWithLayout() {
- $config = Logger::configure(array(
- 'rootLogger' => array(
- 'appenders' => array('app1', 'app2')
- ),
- 'loggers' => array(
- 'myLogger' => array(
- 'appenders' => array('app1'),
- 'additivity'=> true
- )
- ),
- 'renderers' => array(
- array('renderedClass' => 'stdClass', 'renderingClass' => 'DefaultRenderer')
- ),
- 'appenders' => array(
- 'app1' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- ),
- 'params' => array(
- 'htmlLineBreaks' => false
- )
- ),
- 'app2' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'PatternLayout',
- 'params' => array(
- 'conversionPattern' => 'message: %m%n'
- )
- ),
- 'filters' => array(
- array(
- 'class' => 'StringMatchFilter',
- 'params'=> array(
- 'stringToMatch' => 'foo',
- 'acceptOnMatch' => false
- )
- )
- )
- ),
- )
- ));
+ public function testAppendersWithLayout()
+ {
+ $config = Logger::configure(array(
+ 'rootLogger' => array(
+ 'appenders' => array('app1', 'app2')
+ ),
+ 'loggers' => array(
+ 'myLogger' => array(
+ 'appenders' => array('app1'),
+ 'additivity'=> true
+ )
+ ),
+ 'renderers' => array(
+ array('renderedClass' => 'stdClass', 'renderingClass' => 'DefaultRenderer')
+ ),
+ 'appenders' => array(
+ 'app1' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ ),
+ 'params' => array(
+ 'htmlLineBreaks' => false
+ )
+ ),
+ 'app2' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'PatternLayout',
+ 'params' => array(
+ 'conversionPattern' => 'message: %m%n'
+ )
+ ),
+ 'filters' => array(
+ array(
+ 'class' => 'StringMatchFilter',
+ 'params'=> array(
+ 'stringToMatch' => 'foo',
+ 'acceptOnMatch' => false
+ )
+ )
+ )
+ ),
+ )
+ ));
- ob_start();
- Logger::getRootLogger()->info('info');
- $actual = ob_get_contents();
- ob_end_clean();
+ ob_start();
+ Logger::getRootLogger()->info('info');
+ $actual = ob_get_contents();
+ ob_end_clean();
- $expected = "INFO - info" . PHP_EOL . "message: info" . PHP_EOL;
- $this->assertSame($expected, $actual);
- }
+ $expected = "INFO - info" . PHP_EOL . "message: info" . PHP_EOL;
+ $this->assertSame($expected, $actual);
+ }
- public function testThreshold()
- {
- Logger::configure(array(
- 'threshold' => 'WARN',
- 'rootLogger' => array(
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- ),
- )
- ));
+ public function testThreshold()
+ {
+ Logger::configure(array(
+ 'threshold' => 'WARN',
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ ),
+ )
+ ));
- $actual = Logger::getHierarchy()->getThreshold();
- $expected = Level::getLevelWarn();
+ $actual = Logger::getHierarchy()->getThreshold();
+ $expected = Level::getLevelWarn();
- self::assertSame($expected, $actual);
- }
+ self::assertSame($expected, $actual);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid threshold value [FOO] specified. Ignoring threshold definition.
- */
- public function testInvalidThreshold()
- {
- Logger::configure(array(
- 'threshold' => 'FOO',
- 'rootLogger' => array(
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- ),
- )
- ));
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid threshold value [FOO] specified. Ignoring threshold definition.
+ */
+ public function testInvalidThreshold()
+ {
+ Logger::configure(array(
+ 'threshold' => 'FOO',
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ ),
+ )
+ ));
+ }
- public function testAppenderThreshold()
- {
- Logger::configure(array(
- 'rootLogger' => array(
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'threshold' => 'INFO'
- ),
- )
- ));
+ public function testAppenderThreshold()
+ {
+ Logger::configure(array(
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'threshold' => 'INFO'
+ ),
+ )
+ ));
- $actual = Logger::getRootLogger()->getAppender('default')->getThreshold();
- $expected = Level::getLevelInfo();
+ $actual = Logger::getRootLogger()->getAppender('default')->getThreshold();
+ $expected = Level::getLevelInfo();
- self::assertSame($expected, $actual);
- }
+ self::assertSame($expected, $actual);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid threshold value [FOO] specified for appender [default]. Ignoring threshold definition.
- */
- public function testAppenderInvalidThreshold()
- {
- Logger::configure(array(
- 'rootLogger' => array(
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'threshold' => 'FOO'
- ),
- )
- ));
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid threshold value [FOO] specified for appender [default]. Ignoring threshold definition.
+ */
+ public function testAppenderInvalidThreshold()
+ {
+ Logger::configure(array(
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'threshold' => 'FOO'
+ ),
+ )
+ ));
+ }
- public function testLoggerThreshold()
- {
- Logger::configure(array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- 'level' => 'ERROR'
- ),
- 'loggers' => array(
- 'default' => array(
- 'appenders' => array('default'),
- 'level' => 'WARN'
- )
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- ),
- )
- ));
+ public function testLoggerThreshold()
+ {
+ Logger::configure(array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ 'level' => 'ERROR'
+ ),
+ 'loggers' => array(
+ 'default' => array(
+ 'appenders' => array('default'),
+ 'level' => 'WARN'
+ )
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ ),
+ )
+ ));
- // Check root logger
- $actual = Logger::getRootLogger()->getLevel();
- $expected = Level::getLevelError();
- self::assertSame($expected, $actual);
+ // Check root logger
+ $actual = Logger::getRootLogger()->getLevel();
+ $expected = Level::getLevelError();
+ self::assertSame($expected, $actual);
- // Check default logger
- $actual = Logger::getLogger('default')->getLevel();
- $expected = Level::getLevelWarn();
- self::assertSame($expected, $actual);
- }
+ // Check default logger
+ $actual = Logger::getLogger('default')->getLevel();
+ $expected = Level::getLevelWarn();
+ self::assertSame($expected, $actual);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid level value [FOO] specified for logger [default]. Ignoring level definition.
- */
- public function testInvalidLoggerThreshold()
- {
- Logger::configure(array(
- 'loggers' => array(
- 'default' => array(
- 'appenders' => array('default'),
- 'level' => 'FOO'
- )
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- ),
- )
- ));
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid level value [FOO] specified for logger [default]. Ignoring level definition.
+ */
+ public function testInvalidLoggerThreshold()
+ {
+ Logger::configure(array(
+ 'loggers' => array(
+ 'default' => array(
+ 'appenders' => array('default'),
+ 'level' => 'FOO'
+ )
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ ),
+ )
+ ));
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid level value [FOO] specified for logger [root]. Ignoring level definition.
- */
- public function testInvalidRootLoggerThreshold()
- {
- Logger::configure(array(
- 'rootLogger' => array(
- 'appenders' => array('default'),
- 'level' => 'FOO'
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- ),
- )
- ));
- }
- }
\ No newline at end of file
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid level value [FOO] specified for logger [root]. Ignoring level definition.
+ */
+ public function testInvalidRootLoggerThreshold()
+ {
+ Logger::configure(array(
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ 'level' => 'FOO'
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ ),
+ )
+ ));
+ }
+ }
diff --git a/tests/src/Configurators/INIAdapterTest.php b/tests/src/Configurators/INIAdapterTest.php
index 92d2380..5b950e4 100644
--- a/tests/src/Configurators/INIAdapterTest.php
+++ b/tests/src/Configurators/INIAdapterTest.php
@@ -30,148 +30,152 @@
/**
* @group configuration
*/
-class INIAdapterTest extends \PHPUnit_Framework_TestCase {
+class INIAdapterTest extends \PHPUnit_Framework_TestCase
+{
+ /** Expected output of parsing config1.ini. */
+ private $expected1 = array(
+ 'threshold' => 'debug',
+ 'rootLogger' => array(
+ 'level' => 'DEBUG',
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'LoggerLayoutTTCC',
+ ),
+ ),
+ 'file' => array(
+ 'class' => 'DailyFileAppender',
+ 'layout' => array(
+ 'class' => 'PatternLayout',
+ 'params' => array(
+ 'conversionPattern' => '%d{ISO8601} [%p] %c: %m (at %F line %L)%n',
+ ),
+ ),
+ 'params' => array(
+ 'datePattern' => 'Ymd',
+ 'file' => 'target/examples/daily_%s.log',
+ ),
+ 'threshold' => 'warn'
+ ),
+ ),
+ 'loggers' => array(
+ 'foo' => array(
+ 'level' => 'warn',
+ 'appenders' => array('default'),
+ ),
+ 'foo.bar' => array(
+ 'level' => 'debug',
+ 'appenders' => array('file'),
+ 'additivity' => 'true',
+ ),
+ 'foo.bar.baz' => array(
+ 'level' => 'trace',
+ 'appenders' => array('default', 'file'),
+ 'additivity' => 'false',
+ ),
+ ),
+ 'renderers' => array(
+ array(
+ 'renderedClass' => 'Fruit',
+ 'renderingClass' => 'FruitRenderer',
+ ),
+ array(
+ 'renderedClass' => 'Beer',
+ 'renderingClass' => 'BeerRenderer',
+ ),
+ ),
+ );
- /** Expected output of parsing config1.ini. */
- private $expected1 = array(
- 'threshold' => 'debug',
- 'rootLogger' => array(
- 'level' => 'DEBUG',
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'LoggerLayoutTTCC',
- ),
- ),
- 'file' => array(
- 'class' => 'DailyFileAppender',
- 'layout' => array(
- 'class' => 'PatternLayout',
- 'params' => array(
- 'conversionPattern' => '%d{ISO8601} [%p] %c: %m (at %F line %L)%n',
- ),
- ),
- 'params' => array(
- 'datePattern' => 'Ymd',
- 'file' => 'target/examples/daily_%s.log',
- ),
- 'threshold' => 'warn'
- ),
- ),
- 'loggers' => array(
- 'foo' => array(
- 'level' => 'warn',
- 'appenders' => array('default'),
- ),
- 'foo.bar' => array(
- 'level' => 'debug',
- 'appenders' => array('file'),
- 'additivity' => 'true',
- ),
- 'foo.bar.baz' => array(
- 'level' => 'trace',
- 'appenders' => array('default', 'file'),
- 'additivity' => 'false',
- ),
- ),
- 'renderers' => array(
- array(
- 'renderedClass' => 'Fruit',
- 'renderingClass' => 'FruitRenderer',
- ),
- array(
- 'renderedClass' => 'Beer',
- 'renderingClass' => 'BeerRenderer',
- ),
- ),
- );
+ public function testConfig()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_valid.ini';
+ $adapter = new IniAdapter();
+ $actual = $adapter->convert($url);
- public function testConfig() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_valid.ini';
- $adapter = new IniAdapter();
- $actual = $adapter->convert($url);
+ $this->assertSame($this->expected1, $actual);
+ }
- $this->assertSame($this->expected1, $actual);
- }
+ /**
+ * Test exception is thrown when file cannot be found.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage File [you/will/never/find/me.ini] does not exist.
+ */
+ public function testNonExistantFileException()
+ {
+ $adapter = new IniAdapter();
+ $adapter->convert('you/will/never/find/me.ini');
+ }
- /**
- * Test exception is thrown when file cannot be found.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage File [you/will/never/find/me.ini] does not exist.
- */
- public function testNonExistantFileException() {
- $adapter = new IniAdapter();
- $adapter->convert('you/will/never/find/me.ini');
- }
+ /**
+ * Test exception is thrown when file is not a valid ini file.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Error parsing configuration file
+ */
+ public function testInvalidFileException()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_syntax.ini';
+ $adapter = new IniAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test exception is thrown when file is not a valid ini file.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Error parsing configuration file
- */
- public function testInvalidFileException() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_syntax.ini';
- $adapter = new IniAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test a warning is triggered when configurator doesn't understand a line.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Don't know how to parse the following line: "log4php.appender.default.layout.param.bla = LoggerLayoutTTCC". Skipping.
+ */
+ public function testInvalidLineWarning1()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_appender_declaration_1.ini';
+ $adapter = new IniAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test a warning is triggered when configurator doesn't understand a line.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Don't know how to parse the following line: "log4php.appender.default.layout.param.bla = LoggerLayoutTTCC". Skipping.
- */
- public function testInvalidLineWarning1() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_appender_declaration_1.ini';
- $adapter = new IniAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test a warning is triggered when configurator doesn't understand a line.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Don't know how to parse the following line: "log4php.appender.default.not-layout.param = LoggerLayoutTTCC". Skipping.
+ */
+ public function testInvalidLineWarning2()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_appender_declaration_2.ini';
+ $adapter = new IniAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test a warning is triggered when configurator doesn't understand a line.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Don't know how to parse the following line: "log4php.appender.default.not-layout.param = LoggerLayoutTTCC". Skipping.
- */
- public function testInvalidLineWarning2() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/ini/config_invalid_appender_declaration_2.ini';
- $adapter = new IniAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Check that various boolean equivalents from ini file convert properly
+ * to boolean.
+ */
+ public function testBooleanValues()
+ {
+ $values = parse_ini_file(PHPUNIT_CONFIG_DIR . '/adapters/ini/values.ini');
- /**
- * Check that various boolean equivalents from ini file convert properly
- * to boolean.
- */
- public function testBooleanValues() {
- $values = parse_ini_file(PHPUNIT_CONFIG_DIR . '/adapters/ini/values.ini');
+ $actual = OptionConverter::toBooleanEx($values['unquoted_true']);
+ self::assertTrue($actual);
- $actual = OptionConverter::toBooleanEx($values['unquoted_true']);
- self::assertTrue($actual);
+ $actual = OptionConverter::toBooleanEx($values['unquoted_yes']);
+ self::assertTrue($actual);
- $actual = OptionConverter::toBooleanEx($values['unquoted_yes']);
- self::assertTrue($actual);
+ $actual = OptionConverter::toBooleanEx($values['unquoted_false']);
+ self::assertFalse($actual);
- $actual = OptionConverter::toBooleanEx($values['unquoted_false']);
- self::assertFalse($actual);
+ $actual = OptionConverter::toBooleanEx($values['unquoted_no']);
+ self::assertFalse($actual);
- $actual = OptionConverter::toBooleanEx($values['unquoted_no']);
- self::assertFalse($actual);
+ $actual = OptionConverter::toBooleanEx($values['quoted_true']);
+ self::assertTrue($actual);
- $actual = OptionConverter::toBooleanEx($values['quoted_true']);
- self::assertTrue($actual);
+ $actual = OptionConverter::toBooleanEx($values['quoted_false']);
+ self::assertFalse($actual);
- $actual = OptionConverter::toBooleanEx($values['quoted_false']);
- self::assertFalse($actual);
+ $actual = OptionConverter::toBooleanEx($values['unquoted_one']);
+ self::assertTrue($actual);
- $actual = OptionConverter::toBooleanEx($values['unquoted_one']);
- self::assertTrue($actual);
-
- $actual = OptionConverter::toBooleanEx($values['unquoted_zero']);
- self::assertFalse($actual);
- }
+ $actual = OptionConverter::toBooleanEx($values['unquoted_zero']);
+ self::assertFalse($actual);
+ }
}
-
-?>
\ No newline at end of file
diff --git a/tests/src/Configurators/PHPAdapterTest.php b/tests/src/Configurators/PHPAdapterTest.php
index 2b79826..dbcf2c2 100644
--- a/tests/src/Configurators/PHPAdapterTest.php
+++ b/tests/src/Configurators/PHPAdapterTest.php
@@ -29,73 +29,76 @@
/**
* @group configuration
*/
-class PHPAdapterTest extends \PHPUnit_Framework_TestCase {
+class PHPAdapterTest extends \PHPUnit_Framework_TestCase
+{
+ private $expected1 = array(
+ 'rootLogger' => array(
+ 'level' => 'info',
+ 'appenders' => array('default')
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout'
+ )
+ )
+ )
+ );
- private $expected1 = array(
- 'rootLogger' => array(
- 'level' => 'info',
- 'appenders' => array('default')
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout'
- )
- )
- )
- );
+ public function testConfig()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_valid.php';
+ $adapter = new PhpAdapter();
+ $actual = $adapter->convert($url);
- public function testConfig() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_valid.php';
- $adapter = new PhpAdapter();
- $actual = $adapter->convert($url);
+ $this->assertSame($this->expected1, $actual);
+ }
- $this->assertSame($this->expected1, $actual);
- }
+ /**
+ * Test exception is thrown when file cannot be found.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage File [you/will/never/find/me.conf] does not exist.
+ */
+ public function testNonExistantFileWarning()
+ {
+ $adapter = new PhpAdapter();
+ $adapter->convert('you/will/never/find/me.conf');
+ }
- /**
- * Test exception is thrown when file cannot be found.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage File [you/will/never/find/me.conf] does not exist.
- */
- public function testNonExistantFileWarning() {
- $adapter = new PhpAdapter();
- $adapter->convert('you/will/never/find/me.conf');
- }
+ /**
+ * Test exception is thrown when file is not valid.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Error parsing configuration: syntax error
+ */
+ public function testInvalidFileWarning()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_invalid_syntax.php';
+ $adapter = new PhpAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test exception is thrown when file is not valid.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Error parsing configuration: syntax error
- */
- public function testInvalidFileWarning() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_invalid_syntax.php';
- $adapter = new PhpAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test exception is thrown when the configuration is empty.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Invalid configuration: empty configuration array.
+ */
+ public function testEmptyConfigWarning()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_empty.php';
+ $adapter = new PhpAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test exception is thrown when the configuration is empty.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Invalid configuration: empty configuration array.
- */
- public function testEmptyConfigWarning() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_empty.php';
- $adapter = new PhpAdapter();
- $adapter->convert($url);
- }
-
- /**
- * Test exception is thrown when the configuration does not contain an array.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Invalid configuration: not an array.
- */
- public function testInvalidConfigWarning() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_not_an_array.php';
- $adapter = new PhpAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test exception is thrown when the configuration does not contain an array.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Invalid configuration: not an array.
+ */
+ public function testInvalidConfigWarning()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/php/config_not_an_array.php';
+ $adapter = new PhpAdapter();
+ $adapter->convert($url);
+ }
}
-
-?>
\ No newline at end of file
diff --git a/tests/src/Configurators/XMLAdapterTest.php b/tests/src/Configurators/XMLAdapterTest.php
index 3c4dbe2..6adee8f 100644
--- a/tests/src/Configurators/XMLAdapterTest.php
+++ b/tests/src/Configurators/XMLAdapterTest.php
@@ -30,149 +30,154 @@
/**
* @group configuration
*/
-class XMLAdapterTest extends \PHPUnit_Framework_TestCase {
+class XMLAdapterTest extends \PHPUnit_Framework_TestCase
+{
+ /** Expected output of parsing config1.xml.*/
+ private $expected1 = array(
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'LoggerLayoutTTCC',
+ ),
+ 'filters' => array(
+ array(
+ 'class' => 'LevelRangeFilter',
+ 'params' => array(
+ 'levelMin' => 'ERROR',
+ 'levelMax' => 'FATAL',
+ 'acceptOnMatch' => 'false',
+ ),
+ ),
+ array(
+ 'class' => 'DenyAllFilter',
+ ),
+ ),
+ ),
+ 'file' => array(
+ 'class' => 'DailyFileAppender',
+ 'layout' => array(
+ 'class' => 'PatternLayout',
+ 'params' => array(
+ 'conversionPattern' => '%d{ISO8601} [%p] %c: %m (at %F line %L)%n',
+ ),
+ ),
+ 'params' => array(
+ 'datePattern' => 'Ymd',
+ 'file' => 'target/examples/daily_%s.log',
+ ),
+ 'threshold' => 'warn'
+ ),
+ ),
+ 'loggers' => array(
+ 'foo.bar.baz' => array(
+ 'level' => 'trace',
+ 'additivity' => 'false',
+ 'appenders' => array('default'),
+ ),
+ 'foo.bar' => array(
+ 'level' => 'debug',
+ 'additivity' => 'true',
+ 'appenders' => array('file'),
+ ),
+ 'foo' => array(
+ 'level' => 'warn',
+ 'appenders' => array('default', 'file'),
+ ),
+ ),
+ 'renderers' => array(
+ array(
+ 'renderedClass' => 'Fruit',
+ 'renderingClass' => 'FruitRenderer',
+ ),
+ array(
+ 'renderedClass' => 'Beer',
+ 'renderingClass' => 'BeerRenderer',
+ ),
+ ),
+ 'threshold' => 'debug',
+ 'rootLogger' => array(
+ 'level' => 'DEBUG',
+ 'appenders' => array('default'),
+ ),
+ );
- /** Expected output of parsing config1.xml.*/
- private $expected1 = array(
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'LoggerLayoutTTCC',
- ),
- 'filters' => array(
- array(
- 'class' => 'LevelRangeFilter',
- 'params' => array(
- 'levelMin' => 'ERROR',
- 'levelMax' => 'FATAL',
- 'acceptOnMatch' => 'false',
- ),
- ),
- array(
- 'class' => 'DenyAllFilter',
- ),
- ),
- ),
- 'file' => array(
- 'class' => 'DailyFileAppender',
- 'layout' => array(
- 'class' => 'PatternLayout',
- 'params' => array(
- 'conversionPattern' => '%d{ISO8601} [%p] %c: %m (at %F line %L)%n',
- ),
- ),
- 'params' => array(
- 'datePattern' => 'Ymd',
- 'file' => 'target/examples/daily_%s.log',
- ),
- 'threshold' => 'warn'
- ),
- ),
- 'loggers' => array(
- 'foo.bar.baz' => array(
- 'level' => 'trace',
- 'additivity' => 'false',
- 'appenders' => array('default'),
- ),
- 'foo.bar' => array(
- 'level' => 'debug',
- 'additivity' => 'true',
- 'appenders' => array('file'),
- ),
- 'foo' => array(
- 'level' => 'warn',
- 'appenders' => array('default', 'file'),
- ),
- ),
- 'renderers' => array(
- array(
- 'renderedClass' => 'Fruit',
- 'renderingClass' => 'FruitRenderer',
- ),
- array(
- 'renderedClass' => 'Beer',
- 'renderingClass' => 'BeerRenderer',
- ),
- ),
- 'threshold' => 'debug',
- 'rootLogger' => array(
- 'level' => 'DEBUG',
- 'appenders' => array('default'),
- ),
- );
+ public function setUp()
+ {
+ Logger::resetConfiguration();
+ }
- public function setUp() {
- Logger::resetConfiguration();
- }
+ public function tearDown()
+ {
+ Logger::resetConfiguration();
+ }
- public function tearDown() {
- Logger::resetConfiguration();
- }
+ public function testConversion()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_valid.xml';
+ $adapter = new XmlAdapter();
+ $actual = $adapter->convert($url);
+ $this->assertEquals($this->expected1, $actual);
+ }
- public function testConversion() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_valid.xml';
- $adapter = new XmlAdapter();
- $actual = $adapter->convert($url);
- $this->assertEquals($this->expected1, $actual);
- }
+ public function testConversion2()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_valid_underscore.xml';
+ $adapter = new XmlAdapter();
+ $actual = $adapter->convert($url);
- public function testConversion2() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_valid_underscore.xml';
- $adapter = new XmlAdapter();
- $actual = $adapter->convert($url);
+ $this->assertEquals($this->expected1, $actual);
+ }
- $this->assertEquals($this->expected1, $actual);
- }
+ /**
+ * Test exception is thrown when file cannot be found.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage File [you/will/never/find/me.conf] does not exist.
+ */
+ public function testNonExistantFile()
+ {
+ $adapter = new XmlAdapter();
+ $adapter->convert('you/will/never/find/me.conf');
+ }
- /**
- * Test exception is thrown when file cannot be found.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage File [you/will/never/find/me.conf] does not exist.
- */
- public function testNonExistantFile() {
- $adapter = new XmlAdapter();
- $adapter->convert('you/will/never/find/me.conf');
- }
+ /**
+ * Test exception is thrown when file contains invalid XML.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Error loading configuration file: Premature end of data in tag configuration line
+ */
+ public function testInvalidXMLFile()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_invalid_syntax.xml';
+ $adapter = new XmlAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test exception is thrown when file contains invalid XML.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Error loading configuration file: Premature end of data in tag configuration line
- */
- public function testInvalidXMLFile() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_invalid_syntax.xml';
- $adapter = new XmlAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test that a warning is triggered when two loggers with the same name
+ * are defined.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Duplicate logger definition [foo]. Overwriting
+ */
+ public function testDuplicateLoggerWarning()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_duplicate_logger.xml';
+ $adapter = new XmlAdapter();
+ $adapter->convert($url);
+ }
- /**
- * Test that a warning is triggered when two loggers with the same name
- * are defined.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Duplicate logger definition [foo]. Overwriting
- */
- public function testDuplicateLoggerWarning() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_duplicate_logger.xml';
- $adapter = new XmlAdapter();
- $adapter->convert($url);
- }
+ /**
+ * Test that when two loggers with the same name are defined, the second
+ * one will overwrite the first.
+ */
+ public function testDuplicateLoggerConfig()
+ {
+ $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_duplicate_logger.xml';
+ $adapter = new XmlAdapter();
+ // Supress the warning so that test can continue
+ $config = @$adapter->convert($url);
- /**
- * Test that when two loggers with the same name are defined, the second
- * one will overwrite the first.
- */
- public function testDuplicateLoggerConfig() {
- $url = PHPUNIT_CONFIG_DIR . '/adapters/xml/config_duplicate_logger.xml';
- $adapter = new XmlAdapter();
-
- // Supress the warning so that test can continue
- $config = @$adapter->convert($url);
-
- // Second definition of foo has level set to warn (the first to info)
- $this->assertEquals('warn', $config['loggers']['foo']['level']);
- }
+ // Second definition of foo has level set to warn (the first to info)
+ $this->assertEquals('warn', $config['loggers']['foo']['level']);
+ }
}
-
-?>
\ No newline at end of file
diff --git a/tests/src/ExceptionTest.php b/tests/src/ExceptionTest.php
index 5b56f9e..e36c194 100644
--- a/tests/src/ExceptionTest.php
+++ b/tests/src/ExceptionTest.php
@@ -27,16 +27,18 @@
/**
* @group main
*/
-class ExceptionTest extends \PHPUnit_Framework_TestCase {
- /**
- * @expectedException Apache\Log4php\LoggerException
- */
- public function testMessage() {
- try {
- throw new LoggerException("TEST");
- } catch (LoggerException $e) {
- self::assertEquals("TEST", $e->getMessage());
- throw $e;
- }
- }
+class ExceptionTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @expectedException Apache\Log4php\LoggerException
+ */
+ public function testMessage()
+ {
+ try {
+ throw new LoggerException("TEST");
+ } catch (LoggerException $e) {
+ self::assertEquals("TEST", $e->getMessage());
+ throw $e;
+ }
+ }
}
diff --git a/tests/src/FilterTest.php b/tests/src/FilterTest.php
index e54d01b..4448853 100644
--- a/tests/src/FilterTest.php
+++ b/tests/src/FilterTest.php
@@ -32,23 +32,24 @@
/**
* @group filters
*/
-class FilterTest extends \PHPUnit_Framework_TestCase {
+class FilterTest extends \PHPUnit_Framework_TestCase
+{
+ public function testDecide()
+ {
+ $filter = new MyFilter();
+ // activateOptions is empty, but should at least throw no exeception
+ $filter->activateOptions();
+ $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
+ $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- public function testDecide() {
- $filter = new MyFilter();
- // activateOptions is empty, but should at least throw no exeception
- $filter->activateOptions();
- $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
- $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ $result = $filter->decide($eventError);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventError);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventDebug);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventDebug);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
-
- $result = $filter->decide($eventWarn);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventWarn);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
}
}
diff --git a/tests/src/Filters/FilterDenyAllTest.php b/tests/src/Filters/FilterDenyAllTest.php
index ac41f3b..7109c9c 100644
--- a/tests/src/Filters/FilterDenyAllTest.php
+++ b/tests/src/Filters/FilterDenyAllTest.php
@@ -30,46 +30,48 @@
/**
* @group filters
*/
-class FilterDenyAllTest extends \PHPUnit_Framework_TestCase {
+class FilterDenyAllTest extends \PHPUnit_Framework_TestCase
+{
+ public function testDecide()
+ {
+ $filter = new DenyAllFilter();
- public function testDecide() {
- $filter = new DenyAllFilter();
+ $events = array(
+ TestHelper::getTraceEvent(),
+ TestHelper::getDebugEvent(),
+ TestHelper::getInfoEvent(),
+ TestHelper::getWarnEvent(),
+ TestHelper::getErrorEvent(),
+ TestHelper::getFatalEvent(),
+ );
- $events = array(
- TestHelper::getTraceEvent(),
- TestHelper::getDebugEvent(),
- TestHelper::getInfoEvent(),
- TestHelper::getWarnEvent(),
- TestHelper::getErrorEvent(),
- TestHelper::getFatalEvent(),
- );
-
- foreach($events as $event) {
- $actual = $filter->decide($event);
- self::assertEquals(AbstractFilter::DENY, $actual);
- }
+ foreach ($events as $event) {
+ $actual = $filter->decide($event);
+ self::assertEquals(AbstractFilter::DENY, $actual);
+ }
}
- public function testConfiguration() {
- $config = DefaultConfigurator::getDefaultConfiguration();
- $config['appenders']['default']['filters'] = array(
- array(
- 'class' => 'DenyAllFilter'
- )
- );
+ public function testConfiguration()
+ {
+ $config = DefaultConfigurator::getDefaultConfiguration();
+ $config['appenders']['default']['filters'] = array(
+ array(
+ 'class' => 'DenyAllFilter'
+ )
+ );
- Logger::configure($config);
- $logger = Logger::getRootLogger();
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
- ob_start();
- $logger->trace('Test');
- $logger->debug('Test');
- $logger->info('Test');
- $logger->warn('Test');
- $logger->error('Test');
- $logger->fatal('Test');
- $actual = ob_get_clean();
+ ob_start();
+ $logger->trace('Test');
+ $logger->debug('Test');
+ $logger->info('Test');
+ $logger->warn('Test');
+ $logger->error('Test');
+ $logger->fatal('Test');
+ $actual = ob_get_clean();
- $this->assertEmpty($actual);
+ $this->assertEmpty($actual);
}
}
diff --git a/tests/src/Filters/FilterLevelMatchTest.php b/tests/src/Filters/FilterLevelMatchTest.php
index 28f5601..9eddd68 100644
--- a/tests/src/Filters/FilterLevelMatchTest.php
+++ b/tests/src/Filters/FilterLevelMatchTest.php
@@ -29,156 +29,160 @@
/**
* @group filters
*/
-class FilterLevelMatchTest extends \PHPUnit_Framework_TestCase {
+class FilterLevelMatchTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * Tests all possible combinations of event level and filter levelToMatch
+ * option, with acceptOnMatch set to TRUE.
+ */
+ public function testDecideAccept()
+ {
+ $filter = new LevelMatchFilter();
+ $filter->setAcceptOnMatch("true");
- /**
- * Tests all possible combinations of event level and filter levelToMatch
- * option, with acceptOnMatch set to TRUE.
- */
- public function testDecideAccept() {
- $filter = new LevelMatchFilter();
- $filter->setAcceptOnMatch("true");
+ $levels = TestHelper::getAllLevels();
+ $events = TestHelper::getAllEvents();
- $levels = TestHelper::getAllLevels();
- $events = TestHelper::getAllEvents();
+ foreach ($levels as $level) {
+ $filter->setLevelToMatch($level);
- foreach($levels as $level) {
- $filter->setLevelToMatch($level);
+ foreach ($events as $event) {
+ // Expecting given level to be accepted, neutral for others
+ $expected = ($event->getLevel() == $level) ? AbstractFilter::ACCEPT : AbstractFilter::NEUTRAL;
+ $actual = $filter->decide($event);
- foreach($events as $event) {
- // Expecting given level to be accepted, neutral for others
- $expected = ($event->getLevel() == $level) ? AbstractFilter::ACCEPT : AbstractFilter::NEUTRAL;
- $actual = $filter->decide($event);
+ // Get string represenations for logging
+ $sExpected = TestHelper::decisionToString($expected);
+ $sActual = TestHelper::decisionToString($actual);
- // Get string represenations for logging
- $sExpected = TestHelper::decisionToString($expected);
- $sActual = TestHelper::decisionToString($actual);
+ $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
+ }
+ }
+ }
- $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
- }
- }
- }
+ /**
+ * Tests all possible combinations of event level and filter levelToMatch
+ * option, with acceptOnMatch set to TRUE.
+ */
+ public function testDecideDeny()
+ {
+ $filter = new LevelMatchFilter();
+ $filter->setAcceptOnMatch("false");
- /**
- * Tests all possible combinations of event level and filter levelToMatch
- * option, with acceptOnMatch set to TRUE.
- */
- public function testDecideDeny() {
- $filter = new LevelMatchFilter();
- $filter->setAcceptOnMatch("false");
+ $levels = TestHelper::getAllLevels();
+ $events = TestHelper::getAllEvents();
- $levels = TestHelper::getAllLevels();
- $events = TestHelper::getAllEvents();
+ foreach ($levels as $level) {
+ $filter->setLevelToMatch($level);
- foreach($levels as $level) {
- $filter->setLevelToMatch($level);
+ foreach ($events as $event) {
+ // Expecting given level to be denied, neutral for others
+ $expected = ($event->getLevel() == $level) ? AbstractFilter::DENY : AbstractFilter::NEUTRAL;
+ $actual = $filter->decide($event);
- foreach($events as $event) {
- // Expecting given level to be denied, neutral for others
- $expected = ($event->getLevel() == $level) ? AbstractFilter::DENY : AbstractFilter::NEUTRAL;
- $actual = $filter->decide($event);
+ // Get string represenations for logging
+ $sExpected = TestHelper::decisionToString($expected);
+ $sActual = TestHelper::decisionToString($actual);
- // Get string represenations for logging
- $sExpected = TestHelper::decisionToString($expected);
- $sActual = TestHelper::decisionToString($actual);
+ $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
+ }
+ }
+ }
- $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
- }
- }
- }
+ /** Test that filter always decides NEUTRAL when levelToMatch is not set. */
+ public function testDecideNull()
+ {
+ $filter = new LevelMatchFilter();
+ $events = TestHelper::getAllEvents();
- /** Test that filter always decides NEUTRAL when levelToMatch is not set. */
- public function testDecideNull() {
- $filter = new LevelMatchFilter();
- $events = TestHelper::getAllEvents();
+ foreach ($events as $event) {
+ $expected = AbstractFilter::NEUTRAL;
+ $actual = $filter->decide($event);
- foreach($events as $event) {
- $expected = AbstractFilter::NEUTRAL;
- $actual = $filter->decide($event);
+ // Get string represenations for logging
+ $sExpected = TestHelper::decisionToString($expected);
+ $sActual = TestHelper::decisionToString($actual);
+ $level = $event->getLevel();
- // Get string represenations for logging
- $sExpected = TestHelper::decisionToString($expected);
- $sActual = TestHelper::decisionToString($actual);
- $level = $event->getLevel();
+ $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
+ }
+ }
- $this->assertSame($expected, $actual, "Failed asserting filter decision for event level <$level>. Expected <$sExpected>, found <$sActual>.");
- }
- }
+ /** Test logger configuration. */
+ public function testAcceptConfig()
+ {
+ $config = TestHelper::getEchoConfig();
- /** Test logger configuration. */
- public function testAcceptConfig() {
- $config = TestHelper::getEchoConfig();
+ // Add filters to default appender
+ $config['appenders']['default']['filters'] = array(
- // Add filters to default appender
- $config['appenders']['default']['filters'] = array(
+ // Accepts only INFO events
+ array(
+ 'class' => 'LevelMatchFilter',
+ 'params' => array(
+ 'levelToMatch' => 'info',
+ 'acceptOnMatch' => true
+ )
+ ),
- // Accepts only INFO events
- array(
- 'class' => 'LevelMatchFilter',
- 'params' => array(
- 'levelToMatch' => 'info',
- 'acceptOnMatch' => true
- )
- ),
+ // Denies all events not accepted by first filter
+ array(
+ 'class' => 'DenyAllFilter',
+ )
+ );
- // Denies all events not accepted by first filter
- array(
- 'class' => 'DenyAllFilter',
- )
- );
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
- Logger::configure($config);
- $logger = Logger::getRootLogger();
+ ob_start();
+ $logger->trace('Test');
+ $logger->debug('Test');
+ $logger->info('Test');
+ $logger->warn('Test');
+ $logger->error('Test');
+ $logger->fatal('Test');
- ob_start();
- $logger->trace('Test');
- $logger->debug('Test');
- $logger->info('Test');
- $logger->warn('Test');
- $logger->error('Test');
- $logger->fatal('Test');
+ $actual = ob_get_clean();
- $actual = ob_get_clean();
+ $expected = "INFO - Test" . PHP_EOL;
+ }
+ public function testDenyConfig()
+ {
+ $config = TestHelper::getEchoConfig();
- $expected = "INFO - Test" . PHP_EOL;
- }
+ // Add filter which denies INFO events
+ $config['appenders']['default']['filters'] = array(
+ array(
+ 'class' => 'LevelMatchFilter',
+ 'params' => array(
+ 'levelToMatch' => 'info',
+ 'acceptOnMatch' => false
+ )
+ )
+ );
- public function testDenyConfig() {
- $config = TestHelper::getEchoConfig();
+ Logger::configure($config);
+ $logger = Logger::getRootLogger();
- // Add filter which denies INFO events
- $config['appenders']['default']['filters'] = array(
- array(
- 'class' => 'LevelMatchFilter',
- 'params' => array(
- 'levelToMatch' => 'info',
- 'acceptOnMatch' => false
- )
- )
- );
+ ob_start();
+ $logger->trace('Test');
+ $logger->debug('Test');
+ $logger->info('Test');
+ $logger->warn('Test');
+ $logger->error('Test');
+ $logger->fatal('Test');
- Logger::configure($config);
- $logger = Logger::getRootLogger();
+ $actual = ob_get_clean();
- ob_start();
- $logger->trace('Test');
- $logger->debug('Test');
- $logger->info('Test');
- $logger->warn('Test');
- $logger->error('Test');
- $logger->fatal('Test');
+ // Should log all except info
+ $expected =
+ "TRACE - Test" . PHP_EOL .
+ "DEBUG - Test" . PHP_EOL .
+ "WARN - Test" . PHP_EOL .
+ "ERROR - Test" . PHP_EOL .
+ "FATAL - Test" . PHP_EOL;
- $actual = ob_get_clean();
-
- // Should log all except info
- $expected =
- "TRACE - Test" . PHP_EOL .
- "DEBUG - Test" . PHP_EOL .
- "WARN - Test" . PHP_EOL .
- "ERROR - Test" . PHP_EOL .
- "FATAL - Test" . PHP_EOL;
-
- $this->assertSame($expected, $actual);
- }
+ $this->assertSame($expected, $actual);
+ }
}
diff --git a/tests/src/Filters/FilterLevelRangeTest.php b/tests/src/Filters/FilterLevelRangeTest.php
index 31999eb..171517b 100644
--- a/tests/src/Filters/FilterLevelRangeTest.php
+++ b/tests/src/Filters/FilterLevelRangeTest.php
@@ -31,45 +31,47 @@
/**
* @group filters
*/
-class FilterLevelRangeTest extends \PHPUnit_Framework_TestCase {
+class FilterLevelRangeTest extends \PHPUnit_Framework_TestCase
+{
+ public function testDecide()
+ {
+ $filter = new LevelRangeFilter();
+ $filter->setAcceptOnMatch("true");
+ $filter->setLevelMin(Level::getLevelWarn());
+ $filter->setLevelMax(Level::getLevelError());
- public function testDecide() {
- $filter = new LevelRangeFilter();
- $filter->setAcceptOnMatch("true");
- $filter->setLevelMin(Level::getLevelWarn());
- $filter->setLevelMax(Level::getLevelError());
+ $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
+ $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
- $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ $result = $filter->decide($eventError);
+ self::assertEquals($result, AbstractFilter::ACCEPT);
- $result = $filter->decide($eventError);
- self::assertEquals($result, AbstractFilter::ACCEPT);
+ $result = $filter->decide($eventDebug);
+ self::assertEquals($result, AbstractFilter::DENY);
- $result = $filter->decide($eventDebug);
- self::assertEquals($result, AbstractFilter::DENY);
-
- $result = $filter->decide($eventWarn);
- self::assertEquals($result, AbstractFilter::ACCEPT);
+ $result = $filter->decide($eventWarn);
+ self::assertEquals($result, AbstractFilter::ACCEPT);
}
- public function testDecideAcceptFalse() {
- $filter = new LevelRangeFilter();
- $filter->setAcceptOnMatch("false");
- $filter->setLevelMin(Level::getLevelWarn());
- $filter->setLevelMax(Level::getLevelError());
+ public function testDecideAcceptFalse()
+ {
+ $filter = new LevelRangeFilter();
+ $filter->setAcceptOnMatch("false");
+ $filter->setLevelMin(Level::getLevelWarn());
+ $filter->setLevelMax(Level::getLevelError());
- $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
- $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "testmessage");
+ $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- $result = $filter->decide($eventError);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventError);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventDebug);
- self::assertEquals($result, AbstractFilter::DENY);
+ $result = $filter->decide($eventDebug);
+ self::assertEquals($result, AbstractFilter::DENY);
- $result = $filter->decide($eventWarn);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventWarn);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
}
}
diff --git a/tests/src/Filters/FilterStringMatchTest.php b/tests/src/Filters/FilterStringMatchTest.php
index 5618412..dc07e08 100644
--- a/tests/src/Filters/FilterStringMatchTest.php
+++ b/tests/src/Filters/FilterStringMatchTest.php
@@ -31,88 +31,92 @@
/**
* @group filters
*/
-class FilterStringMatchTest extends \PHPUnit_Framework_TestCase {
+class FilterStringMatchTest extends \PHPUnit_Framework_TestCase
+{
+ public function testDecideAccept()
+ {
+ $filter = new StringMatchFilter();
+ $filter->setAcceptOnMatch("true");
+ $filter->setStringToMatch("testmessage");
- public function testDecideAccept() {
- $filter = new StringMatchFilter();
- $filter->setAcceptOnMatch("true");
- $filter->setStringToMatch("testmessage");
+ $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventError2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "xyz");
+ $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventDebug2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "xyz");
+ $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ $eventWarn2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "xyz");
- $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventError2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "xyz");
- $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventDebug2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "xyz");
- $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- $eventWarn2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "xyz");
+ $result = $filter->decide($eventError);
+ self::assertEquals($result, AbstractFilter::ACCEPT);
- $result = $filter->decide($eventError);
- self::assertEquals($result, AbstractFilter::ACCEPT);
+ $result = $filter->decide($eventError2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventError2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventDebug);
+ self::assertEquals($result, AbstractFilter::ACCEPT);
- $result = $filter->decide($eventDebug);
- self::assertEquals($result, AbstractFilter::ACCEPT);
+ $result = $filter->decide($eventDebug2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventDebug2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventWarn);
+ self::assertEquals($result, AbstractFilter::ACCEPT);
- $result = $filter->decide($eventWarn);
- self::assertEquals($result, AbstractFilter::ACCEPT);
+ $result = $filter->decide($eventWarn2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
+ }
- $result = $filter->decide($eventWarn2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
- }
+ public function testDecideDeny()
+ {
+ $filter = new StringMatchFilter();
+ $filter->setAcceptOnMatch("false");
+ $filter->setStringToMatch("testmessage");
- public function testDecideDeny() {
- $filter = new StringMatchFilter();
- $filter->setAcceptOnMatch("false");
- $filter->setStringToMatch("testmessage");
+ $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventError2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "xyz");
+ $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $eventDebug2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "xyz");
+ $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ $eventWarn2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "xyz");
- $eventError = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventError2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "xyz");
- $eventDebug = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $eventDebug2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelDebug(), "xyz");
- $eventWarn = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- $eventWarn2 = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelWarn(), "xyz");
+ $result = $filter->decide($eventError);
+ self::assertEquals($result, AbstractFilter::DENY);
- $result = $filter->decide($eventError);
- self::assertEquals($result, AbstractFilter::DENY);
+ $result = $filter->decide($eventError2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventError2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventDebug);
+ self::assertEquals($result, AbstractFilter::DENY);
- $result = $filter->decide($eventDebug);
- self::assertEquals($result, AbstractFilter::DENY);
+ $result = $filter->decide($eventDebug2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
- $result = $filter->decide($eventDebug2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
+ $result = $filter->decide($eventWarn);
+ self::assertEquals($result, AbstractFilter::DENY);
- $result = $filter->decide($eventWarn);
- self::assertEquals($result, AbstractFilter::DENY);
+ $result = $filter->decide($eventWarn2);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
+ }
- $result = $filter->decide($eventWarn2);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
- }
+ public function testDecideNullMessage()
+ {
+ $filter = new StringMatchFilter();
+ $filter->setAcceptOnMatch("false");
+ $filter->setStringToMatch("testmessage");
- public function testDecideNullMessage() {
- $filter = new StringMatchFilter();
- $filter->setAcceptOnMatch("false");
- $filter->setStringToMatch("testmessage");
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), null);
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), null);
+ $result = $filter->decide($event);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
+ }
- $result = $filter->decide($event);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
- }
+ public function testDecideNullMatch()
+ {
+ $filter = new StringMatchFilter();
+ $filter->setAcceptOnMatch("false");
- public function testDecideNullMatch() {
- $filter = new StringMatchFilter();
- $filter->setAcceptOnMatch("false");
+ $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- $event = new LoggingEvent("LoggerAppenderEchoTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
-
- $result = $filter->decide($event);
- self::assertEquals($result, AbstractFilter::NEUTRAL);
- }
+ $result = $filter->decide($event);
+ self::assertEquals($result, AbstractFilter::NEUTRAL);
+ }
}
diff --git a/tests/src/Helpers/OptionConverterTest.php b/tests/src/Helpers/OptionConverterTest.php
index 6c00e43..e2ee509 100644
--- a/tests/src/Helpers/OptionConverterTest.php
+++ b/tests/src/Helpers/OptionConverterTest.php
@@ -31,9 +31,10 @@
/**
* @group helpers
*/
-class OptionConverterTest extends \PHPUnit_Framework_TestCase {
-
- public function testToBoolean() {
+class OptionConverterTest extends \PHPUnit_Framework_TestCase
+{
+ public function testToBoolean()
+ {
self::assertTrue(OptionConverter::toBooleanEx(1));
self::assertTrue(OptionConverter::toBooleanEx("1"));
self::assertTrue(OptionConverter::toBooleanEx(true));
@@ -51,11 +52,12 @@
/**
* Test fail on NULL.
- * @expectedException Apache\Log4php\LoggerException
- * @expectedExceptionMessage Given value [NULL] cannot be converted to boolean.
+ * @expectedException Apache\Log4php\LoggerException
+ * @expectedExceptionMessage Given value [NULL] cannot be converted to boolean.
*/
- public function testToBooleanFailure1() {
- OptionConverter::toBooleanEx(null);
+ public function testToBooleanFailure1()
+ {
+ OptionConverter::toBooleanEx(null);
}
/**
@@ -63,17 +65,19 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value ['foo'] cannot be converted to boolean.
*/
- public function testToBooleanFailure2() {
- OptionConverter::toBooleanEx('foo');
+ public function testToBooleanFailure2()
+ {
+ OptionConverter::toBooleanEx('foo');
}
- public function testToInteger() {
- self::assertSame(1, OptionConverter::toIntegerEx('1'));
- self::assertSame(1, OptionConverter::toIntegerEx(1));
- self::assertSame(0, OptionConverter::toIntegerEx('0'));
- self::assertSame(0, OptionConverter::toIntegerEx(0));
- self::assertSame(-1, OptionConverter::toIntegerEx('-1'));
- self::assertSame(-1, OptionConverter::toIntegerEx(-1));
+ public function testToInteger()
+ {
+ self::assertSame(1, OptionConverter::toIntegerEx('1'));
+ self::assertSame(1, OptionConverter::toIntegerEx(1));
+ self::assertSame(0, OptionConverter::toIntegerEx('0'));
+ self::assertSame(0, OptionConverter::toIntegerEx(0));
+ self::assertSame(-1, OptionConverter::toIntegerEx('-1'));
+ self::assertSame(-1, OptionConverter::toIntegerEx(-1));
}
/**
@@ -81,8 +85,9 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value [NULL] cannot be converted to integer.
*/
- public function testToIntegerFailure1() {
- OptionConverter::toIntegerEx(null);
+ public function testToIntegerFailure1()
+ {
+ OptionConverter::toIntegerEx(null);
}
/**
@@ -90,8 +95,9 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value [''] cannot be converted to integer.
*/
- public function testToIntegerFailure2() {
- OptionConverter::toIntegerEx('');
+ public function testToIntegerFailure2()
+ {
+ OptionConverter::toIntegerEx('');
}
/**
@@ -99,8 +105,9 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value ['foo'] cannot be converted to integer.
*/
- public function testToIntegerFailure3() {
- OptionConverter::toIntegerEx('foo');
+ public function testToIntegerFailure3()
+ {
+ OptionConverter::toIntegerEx('foo');
}
/**
@@ -108,8 +115,9 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value [true] cannot be converted to integer.
*/
- public function testToIntegerFailure4() {
- OptionConverter::toIntegerEx(true);
+ public function testToIntegerFailure4()
+ {
+ OptionConverter::toIntegerEx(true);
}
/**
@@ -117,14 +125,16 @@
* @expectedException Apache\Log4php\LoggerException
* @expectedExceptionMessage Given value [false] cannot be converted to integer.
*/
- public function testToIntegerFailure5() {
- OptionConverter::toIntegerEx(false);
+ public function testToIntegerFailure5()
+ {
+ OptionConverter::toIntegerEx(false);
}
- public function testSubstituteConstants() {
- define('OTHER_CONSTANT', 'OTHER');
- define('MY_CONSTANT', 'TEST');
- define('NEXT_CONSTANT', 'NEXT');
+ public function testSubstituteConstants()
+ {
+ define('OTHER_CONSTANT', 'OTHER');
+ define('MY_CONSTANT', 'TEST');
+ define('NEXT_CONSTANT', 'NEXT');
$result = OptionConverter::substConstants('Value of key is ${MY_CONSTANT}.');
self::assertEquals('Value of key is TEST.', $result);
@@ -139,11 +149,12 @@
self::assertEquals('Value of key is DEFINE or DEFINE_OTHER.', $result);
}
- public function testActualSubstituteConstants() {
- $a = new FileAppender();
- $a->setFile('${PHPUNIT_TEMP_DIR}/log.txt');
- $actual = $a->getFile();
- $expected = PHPUNIT_TEMP_DIR . '/log.txt';
- self::assertSame($expected, $actual);
+ public function testActualSubstituteConstants()
+ {
+ $a = new FileAppender();
+ $a->setFile('${PHPUNIT_TEMP_DIR}/log.txt');
+ $actual = $a->getFile();
+ $expected = PHPUNIT_TEMP_DIR . '/log.txt';
+ self::assertSame($expected, $actual);
}
-}
\ No newline at end of file
+}
diff --git a/tests/src/Helpers/PatternParserTest.php b/tests/src/Helpers/PatternParserTest.php
index f849c2d..7005722 100644
--- a/tests/src/Helpers/PatternParserTest.php
+++ b/tests/src/Helpers/PatternParserTest.php
@@ -27,9 +27,10 @@
*
* TODO: Should also test complex patterns like: "%d{Y-m-d H:i:s} %-5p %c %X{username}: %m in %F at %L%n"
*/
-class LoggerPatternParserTest extends \PHPUnit_Framework_TestCase {
-
- public function testErrorLayout() {
+class LoggerPatternParserTest extends \PHPUnit_Framework_TestCase
+{
+ public function testErrorLayout()
+ {
// $event = new LoggingEvent("XmlLayout", new Logger("TEST"), Level::getLevelError(), "testmessage");
// $expected = 'ERROR TEST : testmessage in NA at NA'.PHP_EOL;
@@ -42,7 +43,8 @@
}
- public function testClassname() {
+ public function testClassname()
+ {
// $event = new LoggingEvent("MyClass", new Logger("TEST"), Level::getLevelError(), "testmessage");
// $expected = 'MyClass';
// $patternParser = new PatternParser("%C");
diff --git a/tests/src/Helpers/UtilsTest.php b/tests/src/Helpers/UtilsTest.php
index 38ac597..b9f816b 100644
--- a/tests/src/Helpers/UtilsTest.php
+++ b/tests/src/Helpers/UtilsTest.php
@@ -27,63 +27,65 @@
/**
* @group helpers
*/
-class LoggerUtilsTest extends \PHPUnit_Framework_TestCase {
+class LoggerUtilsTest extends \PHPUnit_Framework_TestCase
+{
+ public function testShorten()
+ {
+ $name = 'org\\apache\\logging\\log4php\\Foo';
- public function testShorten() {
- $name = 'org\\apache\\logging\\log4php\\Foo';
+ $actual = Utils::shortenClassName($name, null);
+ self::assertSame($name, $actual);
- $actual = Utils::shortenClassName($name, null);
- self::assertSame($name, $actual);
+ $actual = Utils::shortenClassName($name, 0);
+ self::assertSame('Foo', $actual);
- $actual = Utils::shortenClassName($name, 0);
- self::assertSame('Foo', $actual);
+ $actual = Utils::shortenClassName($name, 5);
+ self::assertSame('o\\a\\l\\l\\Foo', $actual);
- $actual = Utils::shortenClassName($name, 5);
- self::assertSame('o\\a\\l\\l\\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 16);
+ self::assertSame('o\\a\\l\\l\\Foo', $actual);
- $actual = Utils::shortenClassName($name, 16);
- self::assertSame('o\\a\\l\\l\\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 17);
+ self::assertSame('o\\a\\l\\log4php\\Foo', $actual);
- $actual = Utils::shortenClassName($name, 17);
- self::assertSame('o\\a\\l\\log4php\\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 25);
+ self::assertSame('o\\a\\logging\\log4php\\Foo', $actual);
- $actual = Utils::shortenClassName($name, 25);
- self::assertSame('o\\a\\logging\\log4php\\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 28);
+ self::assertSame('o\\apache\\logging\\log4php\\Foo', $actual);
- $actual = Utils::shortenClassName($name, 28);
- self::assertSame('o\\apache\\logging\\log4php\\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 30);
+ self::assertSame('org\\apache\\logging\\log4php\\Foo', $actual);
+ }
- $actual = Utils::shortenClassName($name, 30);
- self::assertSame('org\\apache\\logging\\log4php\\Foo', $actual);
- }
+ /** Dot separated notation must be supported for legacy reasons. */
+ public function testShortenWithDots()
+ {
+ $name = 'org.apache.logging.log4php.Foo';
- /** Dot separated notation must be supported for legacy reasons. */
- public function testShortenWithDots() {
- $name = 'org.apache.logging.log4php.Foo';
+ $actual = Utils::shortenClassName($name, null);
+ self::assertSame($name, $actual);
- $actual = Utils::shortenClassName($name, null);
- self::assertSame($name, $actual);
+ $actual = Utils::shortenClassName($name, 0);
+ self::assertSame('Foo', $actual);
- $actual = Utils::shortenClassName($name, 0);
- self::assertSame('Foo', $actual);
+ $actual = Utils::shortenClassName($name, 5);
+ self::assertSame('o\a\l\l\Foo', $actual);
- $actual = Utils::shortenClassName($name, 5);
- self::assertSame('o\a\l\l\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 16);
+ self::assertSame('o\a\l\l\Foo', $actual);
- $actual = Utils::shortenClassName($name, 16);
- self::assertSame('o\a\l\l\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 17);
+ self::assertSame('o\a\l\log4php\Foo', $actual);
- $actual = Utils::shortenClassName($name, 17);
- self::assertSame('o\a\l\log4php\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 25);
+ self::assertSame('o\a\logging\log4php\Foo', $actual);
- $actual = Utils::shortenClassName($name, 25);
- self::assertSame('o\a\logging\log4php\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 28);
+ self::assertSame('o\apache\logging\log4php\Foo', $actual);
- $actual = Utils::shortenClassName($name, 28);
- self::assertSame('o\apache\logging\log4php\Foo', $actual);
+ $actual = Utils::shortenClassName($name, 30);
+ self::assertSame('org\apache\logging\log4php\Foo', $actual);
+ }
- $actual = Utils::shortenClassName($name, 30);
- self::assertSame('org\apache\logging\log4php\Foo', $actual);
- }
-
-}
\ No newline at end of file
+}
diff --git a/tests/src/HierarchyTest.php b/tests/src/HierarchyTest.php
index d9f5b49..183c75a 100644
--- a/tests/src/HierarchyTest.php
+++ b/tests/src/HierarchyTest.php
@@ -30,76 +30,81 @@
/**
* @group main
*/
-class HierarchyTest extends \PHPUnit_Framework_TestCase {
+class HierarchyTest extends \PHPUnit_Framework_TestCase
+{
+ private $hierarchy;
- private $hierarchy;
+ protected function setUp()
+ {
+ $this->hierarchy = new Hierarchy(new RootLogger());
+ }
- protected function setUp() {
- $this->hierarchy = new Hierarchy(new RootLogger());
- }
+ public function testResetConfiguration()
+ {
+ $root = $this->hierarchy->getRootLogger();
+ $appender = new ConsoleAppender('A1');
+ $root->addAppender($appender);
- public function testResetConfiguration() {
- $root = $this->hierarchy->getRootLogger();
- $appender = new ConsoleAppender('A1');
- $root->addAppender($appender);
+ $logger = $this->hierarchy->getLogger('test');
+ self::assertEquals(1, count($this->hierarchy->getCurrentLoggers()));
- $logger = $this->hierarchy->getLogger('test');
- self::assertEquals(1, count($this->hierarchy->getCurrentLoggers()));
+ $this->hierarchy->resetConfiguration();
+ self::assertEquals(Level::getLevelDebug(), $root->getLevel());
+ self::assertEquals(Level::getLevelAll(), $this->hierarchy->getThreshold());
+ self::assertEquals(1, count($this->hierarchy->getCurrentLoggers()));
- $this->hierarchy->resetConfiguration();
- self::assertEquals(Level::getLevelDebug(), $root->getLevel());
- self::assertEquals(Level::getLevelAll(), $this->hierarchy->getThreshold());
- self::assertEquals(1, count($this->hierarchy->getCurrentLoggers()));
+ foreach ($this->hierarchy->getCurrentLoggers() as $logger) {
+ self::assertNull($logger->getLevel());
+ self::assertTrue($logger->getAdditivity());
+ self::assertEquals(0, count($logger->getAllAppenders()), 0);
+ }
+ }
- foreach($this->hierarchy->getCurrentLoggers() as $logger) {
- self::assertNull($logger->getLevel());
- self::assertTrue($logger->getAdditivity());
- self::assertEquals(0, count($logger->getAllAppenders()), 0);
- }
- }
+ public function testSettingParents()
+ {
+ $hierarchy = $this->hierarchy;
+ $loggerDE = $hierarchy->getLogger("de");
+ $root = $loggerDE->getParent();
+ self::assertEquals('root', $root->getName());
- public function testSettingParents() {
- $hierarchy = $this->hierarchy;
- $loggerDE = $hierarchy->getLogger("de");
- $root = $loggerDE->getParent();
- self::assertEquals('root', $root->getName());
+ $loggerDEBLUB = $hierarchy->getLogger("de.blub");
+ self::assertEquals('de.blub', $loggerDEBLUB->getName());
+ $p = $loggerDEBLUB->getParent();
+ self::assertEquals('de', $p->getName());
- $loggerDEBLUB = $hierarchy->getLogger("de.blub");
- self::assertEquals('de.blub', $loggerDEBLUB->getName());
- $p = $loggerDEBLUB->getParent();
- self::assertEquals('de', $p->getName());
+ $loggerDEBLA = $hierarchy->getLogger("de.bla");
+ $p = $loggerDEBLA->getParent();
+ self::assertEquals('de', $p->getName());
- $loggerDEBLA = $hierarchy->getLogger("de.bla");
- $p = $loggerDEBLA->getParent();
- self::assertEquals('de', $p->getName());
+ $logger3 = $hierarchy->getLogger("de.bla.third");
+ $p = $logger3->getParent();
+ self::assertEquals('de.bla', $p->getName());
- $logger3 = $hierarchy->getLogger("de.bla.third");
- $p = $logger3->getParent();
- self::assertEquals('de.bla', $p->getName());
+ $p = $p->getParent();
+ self::assertEquals('de', $p->getName());
+ }
- $p = $p->getParent();
- self::assertEquals('de', $p->getName());
- }
+ public function testExists()
+ {
+ $hierarchy = $this->hierarchy;
+ $logger = $hierarchy->getLogger("de");
- public function testExists() {
- $hierarchy = $this->hierarchy;
- $logger = $hierarchy->getLogger("de");
+ self::assertTrue($hierarchy->exists("de"));
- self::assertTrue($hierarchy->exists("de"));
+ $logger = $hierarchy->getLogger("de.blub");
+ self::assertTrue($hierarchy->exists("de.blub"));
+ self::assertTrue($hierarchy->exists("de"));
- $logger = $hierarchy->getLogger("de.blub");
- self::assertTrue($hierarchy->exists("de.blub"));
- self::assertTrue($hierarchy->exists("de"));
+ $logger = $hierarchy->getLogger("de.de");
+ self::assertTrue($hierarchy->exists("de.de"));
+ }
- $logger = $hierarchy->getLogger("de.de");
- self::assertTrue($hierarchy->exists("de.de"));
- }
-
- public function testClear() {
- $hierarchy = $this->hierarchy;
- $logger = $hierarchy->getLogger("de");
- self::assertTrue($hierarchy->exists("de"));
- $hierarchy->clear();
- self::assertFalse($hierarchy->exists("de"));
- }
+ public function testClear()
+ {
+ $hierarchy = $this->hierarchy;
+ $logger = $hierarchy->getLogger("de");
+ self::assertTrue($hierarchy->exists("de"));
+ $hierarchy->clear();
+ self::assertFalse($hierarchy->exists("de"));
+ }
}
diff --git a/tests/src/Layouts/HtmlLayoutTest.php b/tests/src/Layouts/HtmlLayoutTest.php
index 902d3fc..b909328 100644
--- a/tests/src/Layouts/HtmlLayoutTest.php
+++ b/tests/src/Layouts/HtmlLayoutTest.php
@@ -30,50 +30,54 @@
/**
* @group layouts
*/
-class HtmlLayoutTest extends \PHPUnit_Framework_TestCase {
+class HtmlLayoutTest extends \PHPUnit_Framework_TestCase
+{
+ public function testErrorLayout()
+ {
+ $event = new LoggingEvent("HtmlLayoutTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- public function testErrorLayout() {
- $event = new LoggingEvent("HtmlLayoutTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
+ $layout = new HtmlLayout();
+ $v = $layout->format($event);
- $layout = new HtmlLayout();
- $v = $layout->format($event);
+ $e = PHP_EOL."<tr>".PHP_EOL.
+ "<td>".round(1000*$event->getRelativeTime())."</td>".PHP_EOL.
+ "<td title=\"".$event->getThreadName()." thread\">".$event->getThreadName()."</td>".PHP_EOL.
+ "<td title=\"Level\">ERROR</td>".PHP_EOL.
+ "<td title=\"TEST category\">TEST</td>".PHP_EOL.
+ "<td title=\"Message\">testmessage</td>".PHP_EOL.
+ "</tr>".PHP_EOL;
- $e = PHP_EOL."<tr>".PHP_EOL.
- "<td>".round(1000*$event->getRelativeTime())."</td>".PHP_EOL.
- "<td title=\"".$event->getThreadName()." thread\">".$event->getThreadName()."</td>".PHP_EOL.
- "<td title=\"Level\">ERROR</td>".PHP_EOL.
- "<td title=\"TEST category\">TEST</td>".PHP_EOL.
- "<td title=\"Message\">testmessage</td>".PHP_EOL.
- "</tr>".PHP_EOL;
-
- self::assertEquals($v, $e);
+ self::assertEquals($v, $e);
}
- public function testWarnLayout() {
- $event = new LoggingEvent("HtmlLayoutTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
+ public function testWarnLayout()
+ {
+ $event = new LoggingEvent("HtmlLayoutTest", new Logger("TEST"), Level::getLevelWarn(), "testmessage");
- $layout = new HtmlLayout();
- $v = $layout->format($event);
+ $layout = new HtmlLayout();
+ $v = $layout->format($event);
- $e = PHP_EOL."<tr>".PHP_EOL.
- "<td>".round(1000*$event->getRelativeTime())."</td>".PHP_EOL.
- "<td title=\"".$event->getThreadName()." thread\">".$event->getThreadName()."</td>".PHP_EOL.
- "<td title=\"Level\"><font color=\"#993300\"><strong>WARN</strong></font></td>".PHP_EOL.
- "<td title=\"TEST category\">TEST</td>".PHP_EOL.
- "<td title=\"Message\">testmessage</td>".PHP_EOL.
- "</tr>".PHP_EOL;
+ $e = PHP_EOL."<tr>".PHP_EOL.
+ "<td>".round(1000*$event->getRelativeTime())."</td>".PHP_EOL.
+ "<td title=\"".$event->getThreadName()." thread\">".$event->getThreadName()."</td>".PHP_EOL.
+ "<td title=\"Level\"><font color=\"#993300\"><strong>WARN</strong></font></td>".PHP_EOL.
+ "<td title=\"TEST category\">TEST</td>".PHP_EOL.
+ "<td title=\"Message\">testmessage</td>".PHP_EOL.
+ "</tr>".PHP_EOL;
- self::assertEquals($v, $e);
+ self::assertEquals($v, $e);
}
- public function testContentType() {
+ public function testContentType()
+ {
$layout = new HtmlLayout();
$v = $layout->getContentType();
$e = "text/html";
self::assertEquals($v, $e);
}
- public function testTitle() {
+ public function testTitle()
+ {
$layout = new HtmlLayout();
$v = $layout->getTitle();
$e = "Log4php Log Messages";
@@ -85,13 +89,15 @@
self::assertEquals($v, $e);
}
- public function testHeader() {
+ public function testHeader()
+ {
$layout = new HtmlLayout();
$v = $layout->getHeader();
self::assertTrue(strpos($v, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">") === 0);
}
- public function testFooter() {
+ public function testFooter()
+ {
$layout = new HtmlLayout();
$v = $layout->getFooter();
self::assertTrue(strpos($v, "</table>") === 0);
diff --git a/tests/src/Layouts/PatternLayoutTest.php b/tests/src/Layouts/PatternLayoutTest.php
index 71d331d..06d1999 100644
--- a/tests/src/Layouts/PatternLayoutTest.php
+++ b/tests/src/Layouts/PatternLayoutTest.php
@@ -28,29 +28,29 @@
/**
* @group layouts
*/
-class PatternLayoutTest extends \PHPUnit_Framework_TestCase {
+class PatternLayoutTest extends \PHPUnit_Framework_TestCase
+{
+ /** Pattern used for testing. */
+ private $pattern = "%-6level %logger: %msg from %class::%method() in %file at %line%n";
- /** Pattern used for testing. */
- private $pattern = "%-6level %logger: %msg from %class::%method() in %file at %line%n";
+ public function testComplexLayout()
+ {
+ $config = TestHelper::getEchoPatternConfig($this->pattern);
+ Logger::configure($config);
- public function testComplexLayout() {
+ ob_start();
+ $log = Logger::getLogger('LoggerTest');
+ $log->error("my message"); $line = __LINE__;
+ $actual = ob_get_contents();
+ ob_end_clean();
- $config = TestHelper::getEchoPatternConfig($this->pattern);
- Logger::configure($config);
+ $file = __FILE__;
+ $class = __CLASS__;
+ $method = __FUNCTION__;
- ob_start();
- $log = Logger::getLogger('LoggerTest');
- $log->error("my message"); $line = __LINE__;
- $actual = ob_get_contents();
- ob_end_clean();
+ $expected = "ERROR LoggerTest: my message from $class::$method() in $file at $line" . PHP_EOL;
+ self::assertSame($expected, $actual);
- $file = __FILE__;
- $class = __CLASS__;
- $method = __FUNCTION__;
-
- $expected = "ERROR LoggerTest: my message from $class::$method() in $file at $line" . PHP_EOL;
- self::assertSame($expected, $actual);
-
- Logger::resetConfiguration();
+ Logger::resetConfiguration();
}
}
diff --git a/tests/src/Layouts/SerializedLayoutTest.php b/tests/src/Layouts/SerializedLayoutTest.php
index 257fde2..8f33212 100644
--- a/tests/src/Layouts/SerializedLayoutTest.php
+++ b/tests/src/Layouts/SerializedLayoutTest.php
@@ -29,82 +29,86 @@
/**
* @group layouts
*/
-class SerializedLayoutTest extends \PHPUnit_Framework_TestCase {
+class SerializedLayoutTest extends \PHPUnit_Framework_TestCase
+{
+ public function testLocationInfo()
+ {
+ $layout = new SerializedLayout();
+ self::assertFalse($layout->getLocationInfo());
+ $layout->setLocationInfo(true);
+ self::assertTrue($layout->getLocationInfo());
+ $layout->setLocationInfo(false);
+ self::assertFalse($layout->getLocationInfo());
+ }
- public function testLocationInfo() {
- $layout = new SerializedLayout();
- self::assertFalse($layout->getLocationInfo());
- $layout->setLocationInfo(true);
- self::assertTrue($layout->getLocationInfo());
- $layout->setLocationInfo(false);
- self::assertFalse($layout->getLocationInfo());
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Invalid value given for 'locationInfo' property: ['foo']. Expected a boolean value. Property not changed.
+ */
+ public function testLocationInfoFail()
+ {
+ $layout = new SerializedLayout();
+ $layout->setLocationInfo('foo');
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Invalid value given for 'locationInfo' property: ['foo']. Expected a boolean value. Property not changed.
- */
- public function testLocationInfoFail() {
- $layout = new SerializedLayout();
- $layout->setLocationInfo('foo');
- }
+ public function testLayout()
+ {
+ Logger::configure(array(
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SerializedLayout'
+ )
+ )
+ ),
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ )
+ ));
- public function testLayout() {
- Logger::configure(array(
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SerializedLayout'
- )
- )
- ),
- 'rootLogger' => array(
- 'appenders' => array('default')
- )
- ));
+ ob_start();
+ $foo = Logger::getLogger('foo');
+ $foo->info("Interesting message.");
+ $actual = ob_get_contents();
+ ob_end_clean();
- ob_start();
- $foo = Logger::getLogger('foo');
- $foo->info("Interesting message.");
- $actual = ob_get_contents();
- ob_end_clean();
+ $event = unserialize($actual);
- $event = unserialize($actual);
+ self::assertInstanceOf('Apache\\Log4php\\LoggingEvent', $event);
+ self::assertEquals('Interesting message.', $event->getMessage());
+ self::assertEquals(Level::getLevelInfo(), $event->getLevel());
+ }
- self::assertInstanceOf('Apache\\Log4php\\LoggingEvent', $event);
- self::assertEquals('Interesting message.', $event->getMessage());
- self::assertEquals(Level::getLevelInfo(), $event->getLevel());
- }
+ public function testLayoutWithLocationInfo()
+ {
+ Logger::configure(array(
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SerializedLayout',
+ 'params' => array(
+ 'locationInfo' => true
+ )
+ )
+ )
+ ),
+ 'rootLogger' => array(
+ 'appenders' => array('default')
+ )
+ ));
- public function testLayoutWithLocationInfo() {
- Logger::configure(array(
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SerializedLayout',
- 'params' => array(
- 'locationInfo' => true
- )
- )
- )
- ),
- 'rootLogger' => array(
- 'appenders' => array('default')
- )
- ));
+ ob_start();
+ $foo = Logger::getLogger('foo');
+ $foo->info("Interesting message.");
+ $actual = ob_get_contents();
+ ob_end_clean();
- ob_start();
- $foo = Logger::getLogger('foo');
- $foo->info("Interesting message.");
- $actual = ob_get_contents();
- ob_end_clean();
+ $event = unserialize($actual);
- $event = unserialize($actual);
-
- self::assertInstanceOf('Apache\\Log4php\\LoggingEvent', $event);
- self::assertEquals('Interesting message.', $event->getMessage());
- self::assertEquals(Level::getLevelInfo(), $event->getLevel());
- }
+ self::assertInstanceOf('Apache\\Log4php\\LoggingEvent', $event);
+ self::assertEquals('Interesting message.', $event->getMessage());
+ self::assertEquals(Level::getLevelInfo(), $event->getLevel());
+ }
}
diff --git a/tests/src/Layouts/SimpleLayoutTest.php b/tests/src/Layouts/SimpleLayoutTest.php
index f33057d..fa3bb3b 100644
--- a/tests/src/Layouts/SimpleLayoutTest.php
+++ b/tests/src/Layouts/SimpleLayoutTest.php
@@ -30,14 +30,15 @@
/**
* @group layouts
*/
-class SimpleLayoutTest extends \PHPUnit_Framework_TestCase {
+class SimpleLayoutTest extends \PHPUnit_Framework_TestCase
+{
+ public function testSimpleLayout()
+ {
+ $event = new LoggingEvent("SimpleLayoutTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
- public function testSimpleLayout() {
- $event = new LoggingEvent("SimpleLayoutTest", new Logger("TEST"), Level::getLevelError(), "testmessage");
-
- $layout = new SimpleLayout();
- $actual = $layout->format($event);
- $expected = "ERROR - testmessage" . PHP_EOL;
- self::assertEquals($expected, $actual);
- }
+ $layout = new SimpleLayout();
+ $actual = $layout->format($event);
+ $expected = "ERROR - testmessage" . PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
}
diff --git a/tests/src/Layouts/XmlLayoutTest.php b/tests/src/Layouts/XmlLayoutTest.php
index bbcb7dd..a55b9e8 100644
--- a/tests/src/Layouts/XmlLayoutTest.php
+++ b/tests/src/Layouts/XmlLayoutTest.php
@@ -31,123 +31,126 @@
/**
* @group layouts
*/
-class XmlLayoutTest extends \PHPUnit_Framework_TestCase {
+class XmlLayoutTest extends \PHPUnit_Framework_TestCase
+{
+ public function testErrorLayout()
+ {
+ $event = TestHelper::getErrorEvent("testmessage");
- public function testErrorLayout() {
- $event = TestHelper::getErrorEvent("testmessage");
+ $layout = new XmlLayout();
+ $layout->activateOptions();
- $layout = new XmlLayout();
- $layout->activateOptions();
+ $actual = $layout->format($event);
- $actual = $layout->format($event);
+ $thread = $event->getThreadName();
+ $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
+ $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
+ "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
+ "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
+ "method=\"getLocationInformation\" />" . PHP_EOL .
+ "</log4php:event>" . PHP_EOL;
- $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
- "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
- "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
- "method=\"getLocationInformation\" />" . PHP_EOL .
- "</log4php:event>" . PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
- self::assertEquals($expected, $actual);
- }
+ public function testWarnLayout()
+ {
+ $event = TestHelper::getWarnEvent("testmessage");
- public function testWarnLayout() {
- $event = TestHelper::getWarnEvent("testmessage");
+ $layout = new XmlLayout();
+ $layout->activateOptions();
- $layout = new XmlLayout();
- $layout->activateOptions();
+ $actual = $layout->format($event);
- $actual = $layout->format($event);
+ $thread = $event->getThreadName();
+ $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
+ $expected = "<log4php:event logger=\"test\" level=\"WARN\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
+ "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
+ "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
+ "method=\"getLocationInformation\" />" . PHP_EOL .
+ "</log4php:event>" . PHP_EOL;
- $expected = "<log4php:event logger=\"test\" level=\"WARN\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
- "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
- "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
- "method=\"getLocationInformation\" />" . PHP_EOL .
- "</log4php:event>" . PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
- self::assertEquals($expected, $actual);
- }
+ public function testLog4JNamespaceErrorLayout()
+ {
+ $event = TestHelper::getErrorEvent("testmessage");
- public function testLog4JNamespaceErrorLayout() {
- $event = TestHelper::getErrorEvent("testmessage");
+ $layout = new XmlLayout();
+ $layout->setLog4jNamespace(true);
+ $layout->activateOptions();
- $layout = new XmlLayout();
- $layout->setLog4jNamespace(true);
- $layout->activateOptions();
+ $actual = $layout->format($event);
- $actual = $layout->format($event);
+ $thread = $event->getThreadName();
+ $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
+ $expected = "<log4j:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
+ "<log4j:message><![CDATA[testmessage]]></log4j:message>" . PHP_EOL .
+ "<log4j:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
+ "method=\"getLocationInformation\" />" . PHP_EOL .
+ "</log4j:event>" . PHP_EOL;
- $expected = "<log4j:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
- "<log4j:message><![CDATA[testmessage]]></log4j:message>" . PHP_EOL .
- "<log4j:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
- "method=\"getLocationInformation\" />" . PHP_EOL .
- "</log4j:event>" . PHP_EOL;
+ self::assertEquals($expected, $actual);
+ }
- self::assertEquals($expected, $actual);
- }
+ public function testNDC()
+ {
+ NDC::push('foo');
+ NDC::push('bar');
- public function testNDC()
- {
- NDC::push('foo');
- NDC::push('bar');
+ $event = TestHelper::getErrorEvent("testmessage");
- $event = TestHelper::getErrorEvent("testmessage");
+ $layout = new XmlLayout();
+ $layout->activateOptions();
- $layout = new XmlLayout();
- $layout->activateOptions();
+ $actual = $layout->format($event);
- $actual = $layout->format($event);
+ $thread = $event->getThreadName();
+ $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
+ $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
+ "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
+ "<log4php:NDC><![CDATA[<![CDATA[foo bar]]>]]></log4php:NDC>" . PHP_EOL .
+ "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
+ "method=\"getLocationInformation\" />" . PHP_EOL .
+ "</log4php:event>" . PHP_EOL;
- $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
- "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
- "<log4php:NDC><![CDATA[<![CDATA[foo bar]]>]]></log4php:NDC>" . PHP_EOL .
- "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
- "method=\"getLocationInformation\" />" . PHP_EOL .
- "</log4php:event>" . PHP_EOL;
+ self::assertEquals($expected, $actual);
- self::assertEquals($expected, $actual);
+ NDC::clear();
+ }
- NDC::clear();
- }
+ public function testMDC()
+ {
+ MDC::put('foo', 'bar');
+ MDC::put('bla', 'tra');
- public function testMDC()
- {
- MDC::put('foo', 'bar');
- MDC::put('bla', 'tra');
+ $event = TestHelper::getErrorEvent("testmessage");
- $event = TestHelper::getErrorEvent("testmessage");
+ $layout = new XmlLayout();
+ $layout->activateOptions();
- $layout = new XmlLayout();
- $layout->activateOptions();
+ $actual = $layout->format($event);
- $actual = $layout->format($event);
+ $thread = $event->getThreadName();
+ $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
- $thread = $event->getThreadName();
- $timestamp = number_format(($event->getTimeStamp() * 1000), 0, '', '');
+ $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
+ "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
+ "<log4php:properties>" . PHP_EOL .
+ "<log4php:data name=\"foo\" value=\"bar\" />" . PHP_EOL .
+ "<log4php:data name=\"bla\" value=\"tra\" />" . PHP_EOL .
+ "</log4php:properties>" . PHP_EOL .
+ "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
+ "method=\"getLocationInformation\" />" . PHP_EOL .
+ "</log4php:event>" . PHP_EOL;
- $expected = "<log4php:event logger=\"test\" level=\"ERROR\" thread=\"$thread\" timestamp=\"$timestamp\">" . PHP_EOL .
- "<log4php:message><![CDATA[testmessage]]></log4php:message>" . PHP_EOL .
- "<log4php:properties>" . PHP_EOL .
- "<log4php:data name=\"foo\" value=\"bar\" />" . PHP_EOL .
- "<log4php:data name=\"bla\" value=\"tra\" />" . PHP_EOL .
- "</log4php:properties>" . PHP_EOL .
- "<log4php:locationInfo class=\"Apache\\Log4php\\LoggingEvent\" file=\"NA\" line=\"NA\" " .
- "method=\"getLocationInformation\" />" . PHP_EOL .
- "</log4php:event>" . PHP_EOL;
+ self::assertEquals($expected, $actual);
- self::assertEquals($expected, $actual);
-
- MDC::clear();
- }
+ MDC::clear();
+ }
}
diff --git a/tests/src/LevelTest.php b/tests/src/LevelTest.php
index 29ece9b..0933bf2 100644
--- a/tests/src/LevelTest.php
+++ b/tests/src/LevelTest.php
@@ -27,60 +27,69 @@
/**
* @group main
*/
-class LevelTest extends \PHPUnit_Framework_TestCase {
-
- protected function doTestLevel($level, $code, $str, $syslog) {
- self::assertTrue($level instanceof Level);
- self::assertEquals($level->toInt(), $code);
- self::assertEquals($level->toString(), $str);
- self::assertEquals($level->getSyslogEquivalent(), $syslog);
- }
-
- public function testLevelOff() {
- $this->doTestLevel(Level::getLevelOff(), Level::OFF, 'OFF', LOG_ALERT);
- $this->doTestLevel(Level::toLevel(Level::OFF), Level::OFF, 'OFF', LOG_ALERT);
- $this->doTestLevel(Level::toLevel('OFF'), Level::OFF, 'OFF', LOG_ALERT);
+class LevelTest extends \PHPUnit_Framework_TestCase
+{
+ protected function doTestLevel($level, $code, $str, $syslog)
+ {
+ self::assertTrue($level instanceof Level);
+ self::assertEquals($level->toInt(), $code);
+ self::assertEquals($level->toString(), $str);
+ self::assertEquals($level->getSyslogEquivalent(), $syslog);
}
- public function testLevelFatal() {
- $this->doTestLevel(Level::getLevelFatal(), Level::FATAL, 'FATAL', LOG_ALERT);
- $this->doTestLevel(Level::toLevel(Level::FATAL), Level::FATAL, 'FATAL', LOG_ALERT);
- $this->doTestLevel(Level::toLevel('FATAL'), Level::FATAL, 'FATAL', LOG_ALERT);
+ public function testLevelOff()
+ {
+ $this->doTestLevel(Level::getLevelOff(), Level::OFF, 'OFF', LOG_ALERT);
+ $this->doTestLevel(Level::toLevel(Level::OFF), Level::OFF, 'OFF', LOG_ALERT);
+ $this->doTestLevel(Level::toLevel('OFF'), Level::OFF, 'OFF', LOG_ALERT);
}
- public function testLevelError() {
- $this->doTestLevel(Level::getLevelError(), Level::ERROR, 'ERROR', LOG_ERR);
- $this->doTestLevel(Level::toLevel(Level::ERROR), Level::ERROR, 'ERROR', LOG_ERR);
- $this->doTestLevel(Level::toLevel('ERROR'), Level::ERROR, 'ERROR', LOG_ERR);
+ public function testLevelFatal()
+ {
+ $this->doTestLevel(Level::getLevelFatal(), Level::FATAL, 'FATAL', LOG_ALERT);
+ $this->doTestLevel(Level::toLevel(Level::FATAL), Level::FATAL, 'FATAL', LOG_ALERT);
+ $this->doTestLevel(Level::toLevel('FATAL'), Level::FATAL, 'FATAL', LOG_ALERT);
}
- public function testLevelWarn() {
- $this->doTestLevel(Level::getLevelWarn(), Level::WARN, 'WARN', LOG_WARNING);
- $this->doTestLevel(Level::toLevel(Level::WARN), Level::WARN, 'WARN', LOG_WARNING);
- $this->doTestLevel(Level::toLevel('WARN'), Level::WARN, 'WARN', LOG_WARNING);
+ public function testLevelError()
+ {
+ $this->doTestLevel(Level::getLevelError(), Level::ERROR, 'ERROR', LOG_ERR);
+ $this->doTestLevel(Level::toLevel(Level::ERROR), Level::ERROR, 'ERROR', LOG_ERR);
+ $this->doTestLevel(Level::toLevel('ERROR'), Level::ERROR, 'ERROR', LOG_ERR);
}
- public function testLevelInfo() {
- $this->doTestLevel(Level::getLevelInfo(), Level::INFO, 'INFO', LOG_INFO);
- $this->doTestLevel(Level::toLevel(Level::INFO), Level::INFO, 'INFO', LOG_INFO);
- $this->doTestLevel(Level::toLevel('INFO'), Level::INFO, 'INFO', LOG_INFO);
+ public function testLevelWarn()
+ {
+ $this->doTestLevel(Level::getLevelWarn(), Level::WARN, 'WARN', LOG_WARNING);
+ $this->doTestLevel(Level::toLevel(Level::WARN), Level::WARN, 'WARN', LOG_WARNING);
+ $this->doTestLevel(Level::toLevel('WARN'), Level::WARN, 'WARN', LOG_WARNING);
}
- public function testLevelDebug() {
- $this->doTestLevel(Level::getLevelDebug(), Level::DEBUG, 'DEBUG', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel(Level::DEBUG), Level::DEBUG, 'DEBUG', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel('DEBUG'), Level::DEBUG, 'DEBUG', LOG_DEBUG);
- }
-
- public function testLevelTrace() {
- $this->doTestLevel(Level::getLevelTrace(), Level::TRACE, 'TRACE', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel(Level::TRACE), Level::TRACE, 'TRACE', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel('TRACE'), Level::TRACE, 'TRACE', LOG_DEBUG);
+ public function testLevelInfo()
+ {
+ $this->doTestLevel(Level::getLevelInfo(), Level::INFO, 'INFO', LOG_INFO);
+ $this->doTestLevel(Level::toLevel(Level::INFO), Level::INFO, 'INFO', LOG_INFO);
+ $this->doTestLevel(Level::toLevel('INFO'), Level::INFO, 'INFO', LOG_INFO);
}
- public function testLevelAll() {
- $this->doTestLevel(Level::getLevelAll(), Level::ALL, 'ALL', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel(Level::ALL), Level::ALL, 'ALL', LOG_DEBUG);
- $this->doTestLevel(Level::toLevel('ALL'), Level::ALL, 'ALL', LOG_DEBUG);
+ public function testLevelDebug()
+ {
+ $this->doTestLevel(Level::getLevelDebug(), Level::DEBUG, 'DEBUG', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel(Level::DEBUG), Level::DEBUG, 'DEBUG', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel('DEBUG'), Level::DEBUG, 'DEBUG', LOG_DEBUG);
+ }
+
+ public function testLevelTrace()
+ {
+ $this->doTestLevel(Level::getLevelTrace(), Level::TRACE, 'TRACE', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel(Level::TRACE), Level::TRACE, 'TRACE', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel('TRACE'), Level::TRACE, 'TRACE', LOG_DEBUG);
+ }
+
+ public function testLevelAll()
+ {
+ $this->doTestLevel(Level::getLevelAll(), Level::ALL, 'ALL', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel(Level::ALL), Level::ALL, 'ALL', LOG_DEBUG);
+ $this->doTestLevel(Level::toLevel('ALL'), Level::ALL, 'ALL', LOG_DEBUG);
}
}
diff --git a/tests/src/LoggerTest.php b/tests/src/LoggerTest.php
index a511aa4..e231248 100644
--- a/tests/src/LoggerTest.php
+++ b/tests/src/LoggerTest.php
@@ -27,199 +27,209 @@
/**
* @group main
*/
-class LoggerTest extends \PHPUnit_Framework_TestCase {
+class LoggerTest extends \PHPUnit_Framework_TestCase
+{
+ private $testConfig1 = array (
+ 'rootLogger' => array (
+ 'level' => 'ERROR',
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ 'appenders' => array (
+ 'default' => array (
+ 'class' => 'EchoAppender',
+ ),
+ ),
+ 'loggers' => array (
+ 'mylogger' => array (
+ 'additivity' => 'false',
+ 'level' => 'DEBUG',
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ ),
+ );
- private $testConfig1 = array (
- 'rootLogger' => array (
- 'level' => 'ERROR',
- 'appenders' => array (
- 'default',
- ),
- ),
- 'appenders' => array (
- 'default' => array (
- 'class' => 'EchoAppender',
- ),
- ),
- 'loggers' => array (
- 'mylogger' => array (
- 'additivity' => 'false',
- 'level' => 'DEBUG',
- 'appenders' => array (
- 'default',
- ),
- ),
- ),
- );
+ // For testing additivity
+ private $testConfig2 = array (
+ 'appenders' => array (
+ 'default' => array (
+ 'class' => 'EchoAppender',
+ ),
+ ),
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'loggers' => array (
+ 'foo' => array (
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ 'foo.bar' => array (
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ 'foo.bar.baz' => array (
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ ),
+ );
- // For testing additivity
- private $testConfig2 = array (
- 'appenders' => array (
- 'default' => array (
- 'class' => 'EchoAppender',
- ),
- ),
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'loggers' => array (
- 'foo' => array (
- 'appenders' => array (
- 'default',
- ),
- ),
- 'foo.bar' => array (
- 'appenders' => array (
- 'default',
- ),
- ),
- 'foo.bar.baz' => array (
- 'appenders' => array (
- 'default',
- ),
- ),
- ),
- );
+ // For testing additivity
+ private $testConfig3 = array (
+ 'appenders' => array (
+ 'default' => array (
+ 'class' => 'EchoAppender',
+ ),
+ ),
+ 'rootLogger' => array(
+ 'appenders' => array('default'),
+ ),
+ 'loggers' => array (
+ 'foo' => array (
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ 'foo.bar' => array (
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ 'foo.bar.baz' => array (
+ 'level' => 'ERROR',
+ 'appenders' => array (
+ 'default',
+ ),
+ ),
+ ),
+ );
- // For testing additivity
- private $testConfig3 = array (
- 'appenders' => array (
- 'default' => array (
- 'class' => 'EchoAppender',
- ),
- ),
- 'rootLogger' => array(
- 'appenders' => array('default'),
- ),
- 'loggers' => array (
- 'foo' => array (
- 'appenders' => array (
- 'default',
- ),
- ),
- 'foo.bar' => array (
- 'appenders' => array (
- 'default',
- ),
- ),
- 'foo.bar.baz' => array (
- 'level' => 'ERROR',
- 'appenders' => array (
- 'default',
- ),
- ),
- ),
- );
+ protected function setUp()
+ {
+ Logger::clear();
+ Logger::resetConfiguration();
+ }
- protected function setUp() {
- Logger::clear();
- Logger::resetConfiguration();
- }
+ protected function tearDown()
+ {
+ Logger::clear();
+ Logger::resetConfiguration();
+ }
- protected function tearDown() {
- Logger::clear();
- Logger::resetConfiguration();
- }
+ public function testLoggerExist()
+ {
+ $l = Logger::getLogger('test');
+ self::assertEquals($l->getName(), 'test');
+ self::assertTrue(Logger::exists('test'));
+ }
- public function testLoggerExist() {
- $l = Logger::getLogger('test');
- self::assertEquals($l->getName(), 'test');
- self::assertTrue(Logger::exists('test'));
- }
+ public function testCanGetRootLogger()
+ {
+ $l = Logger::getRootLogger();
+ self::assertEquals($l->getName(), 'root');
+ }
- public function testCanGetRootLogger() {
- $l = Logger::getRootLogger();
- self::assertEquals($l->getName(), 'root');
- }
+ public function testCanGetASpecificLogger()
+ {
+ $l = Logger::getLogger('test');
+ self::assertEquals($l->getName(), 'test');
+ }
- public function testCanGetASpecificLogger() {
- $l = Logger::getLogger('test');
- self::assertEquals($l->getName(), 'test');
- }
+ public function testCanLogToAllLevels()
+ {
+ Logger::configure($this->testConfig1);
- public function testCanLogToAllLevels() {
- Logger::configure($this->testConfig1);
+ $logger = Logger::getLogger('mylogger');
+ ob_start();
+ $logger->info('this is an info');
+ $logger->warn('this is a warning');
+ $logger->error('this is an error');
+ $logger->debug('this is a debug message');
+ $logger->fatal('this is a fatal message');
+ $v = ob_get_contents();
+ ob_end_clean();
- $logger = Logger::getLogger('mylogger');
- ob_start();
- $logger->info('this is an info');
- $logger->warn('this is a warning');
- $logger->error('this is an error');
- $logger->debug('this is a debug message');
- $logger->fatal('this is a fatal message');
- $v = ob_get_contents();
- ob_end_clean();
+ $e = 'INFO - this is an info'.PHP_EOL;
+ $e .= 'WARN - this is a warning'.PHP_EOL;
+ $e .= 'ERROR - this is an error'.PHP_EOL;
+ $e .= 'DEBUG - this is a debug message'.PHP_EOL;
+ $e .= 'FATAL - this is a fatal message'.PHP_EOL;
- $e = 'INFO - this is an info'.PHP_EOL;
- $e .= 'WARN - this is a warning'.PHP_EOL;
- $e .= 'ERROR - this is an error'.PHP_EOL;
- $e .= 'DEBUG - this is a debug message'.PHP_EOL;
- $e .= 'FATAL - this is a fatal message'.PHP_EOL;
+ self::assertEquals($v, $e);
+ }
- self::assertEquals($v, $e);
- }
+ public function testIsEnabledFor()
+ {
+ Logger::configure($this->testConfig1);
- public function testIsEnabledFor() {
- Logger::configure($this->testConfig1);
+ $logger = Logger::getLogger('mylogger');
- $logger = Logger::getLogger('mylogger');
+ self::assertFalse($logger->isTraceEnabled());
+ self::assertTrue($logger->isDebugEnabled());
+ self::assertTrue($logger->isInfoEnabled());
+ self::assertTrue($logger->isWarnEnabled());
+ self::assertTrue($logger->isErrorEnabled());
+ self::assertTrue($logger->isFatalEnabled());
- self::assertFalse($logger->isTraceEnabled());
- self::assertTrue($logger->isDebugEnabled());
- self::assertTrue($logger->isInfoEnabled());
- self::assertTrue($logger->isWarnEnabled());
- self::assertTrue($logger->isErrorEnabled());
- self::assertTrue($logger->isFatalEnabled());
+ $logger = Logger::getRootLogger();
- $logger = Logger::getRootLogger();
+ self::assertFalse($logger->isTraceEnabled());
+ self::assertFalse($logger->isDebugEnabled());
+ self::assertFalse($logger->isInfoEnabled());
+ self::assertFalse($logger->isWarnEnabled());
+ self::assertTrue($logger->isErrorEnabled());
+ self::assertTrue($logger->isFatalEnabled());
+ }
- self::assertFalse($logger->isTraceEnabled());
- self::assertFalse($logger->isDebugEnabled());
- self::assertFalse($logger->isInfoEnabled());
- self::assertFalse($logger->isWarnEnabled());
- self::assertTrue($logger->isErrorEnabled());
- self::assertTrue($logger->isFatalEnabled());
- }
+ public function testGetCurrentLoggers()
+ {
+ Logger::clear();
+ Logger::resetConfiguration();
- public function testGetCurrentLoggers() {
- Logger::clear();
- Logger::resetConfiguration();
+ self::assertEquals(0, count(Logger::getCurrentLoggers()));
- self::assertEquals(0, count(Logger::getCurrentLoggers()));
+ Logger::configure($this->testConfig1);
+ self::assertEquals(1, count(Logger::getCurrentLoggers()));
+ $list = Logger::getCurrentLoggers();
+ self::assertEquals('mylogger', $list[0]->getName());
+ }
- Logger::configure($this->testConfig1);
- self::assertEquals(1, count(Logger::getCurrentLoggers()));
- $list = Logger::getCurrentLoggers();
- self::assertEquals('mylogger', $list[0]->getName());
- }
+ public function testAdditivity()
+ {
+ Logger::configure($this->testConfig2);
- public function testAdditivity() {
- Logger::configure($this->testConfig2);
+ $logger = Logger::getLogger('foo.bar.baz');
+ ob_start();
+ $logger->info('test');
+ $actual = ob_get_contents();
+ ob_end_clean();
- $logger = Logger::getLogger('foo.bar.baz');
- ob_start();
- $logger->info('test');
- $actual = ob_get_contents();
- ob_end_clean();
+ // The message should get logged 4 times: once by every logger in the
+ // hierarchy (including root)
+ $expected = str_repeat('INFO - test' . PHP_EOL, 4);
+ self::assertSame($expected, $actual);
+ }
- // The message should get logged 4 times: once by every logger in the
- // hierarchy (including root)
- $expected = str_repeat('INFO - test' . PHP_EOL, 4);
- self::assertSame($expected, $actual);
- }
+ public function testAdditivity2()
+ {
+ Logger::configure($this->testConfig3);
- public function testAdditivity2() {
- Logger::configure($this->testConfig3);
+ $logger = Logger::getLogger('foo.bar.baz');
+ ob_start();
+ $logger->info('test');
+ $actual = ob_get_contents();
+ ob_end_clean();
- $logger = Logger::getLogger('foo.bar.baz');
- ob_start();
- $logger->info('test');
- $actual = ob_get_contents();
- ob_end_clean();
-
- // The message should get logged 3 times: once by every logger in the
- // hierarchy, except foo.bar.baz which is set to level ERROR
- $expected = str_repeat('INFO - test' . PHP_EOL, 3);
- self::assertSame($expected, $actual);
- }
+ // The message should get logged 3 times: once by every logger in the
+ // hierarchy, except foo.bar.baz which is set to level ERROR
+ $expected = str_repeat('INFO - test' . PHP_EOL, 3);
+ self::assertSame($expected, $actual);
+ }
}
diff --git a/tests/src/LoggingEventTest.php b/tests/src/LoggingEventTest.php
index f07e7c3..9aff60e 100644
--- a/tests/src/LoggingEventTest.php
+++ b/tests/src/LoggingEventTest.php
@@ -29,111 +29,120 @@
use Apache\Log4php\Logger;
use Apache\Log4php\LoggingEvent;
-class LoggingEventTestCaseAppender extends NullAppender {
+class LoggingEventTestCaseAppender extends NullAppender
+{
+ protected $requiresLayout = true;
- protected $requiresLayout = true;
-
- public function append(LoggingEvent $event) {
- $this->layout->format($event);
- }
+ public function append(LoggingEvent $event)
+ {
+ $this->layout->format($event);
+ }
}
-class LoggingEventTestCaseLayout extends AbstractLayout {
+class LoggingEventTestCaseLayout extends AbstractLayout
+{
+ public function activateOptions()
+ {
+ return;
+ }
- public function activateOptions() {
- return;
- }
-
- public function format(LoggingEvent $event) {
- LoggingEventTest::$locationInfo = $event->getLocationInformation();
+ public function format(LoggingEvent $event)
+ {
+ LoggingEventTest::$locationInfo = $event->getLocationInformation();
LoggingEventTest::$throwableInfo = $event->getThrowableInformation();
- }
+ }
}
/**
* @group main
*/
-class LoggingEventTest extends \PHPUnit_Framework_TestCase {
-
- public static $locationInfo;
+class LoggingEventTest extends \PHPUnit_Framework_TestCase
+{
+ public static $locationInfo;
public static $throwableInfo;
- public function testConstructWithLoggerName() {
- $l = Level::getLevelDebug();
- $e = new LoggingEvent('fqcn', 'TestLogger', $l, 'test');
- self::assertEquals($e->getLoggerName(), 'TestLogger');
- }
+ public function testConstructWithLoggerName()
+ {
+ $l = Level::getLevelDebug();
+ $e = new LoggingEvent('fqcn', 'TestLogger', $l, 'test');
+ self::assertEquals($e->getLoggerName(), 'TestLogger');
+ }
- public function testConstructWithTimestamp() {
- $l = Level::getLevelDebug();
- $timestamp = microtime(true);
- $e = new LoggingEvent('fqcn', 'TestLogger', $l, 'test', $timestamp);
- self::assertEquals($e->getTimeStamp(), $timestamp);
- }
+ public function testConstructWithTimestamp()
+ {
+ $l = Level::getLevelDebug();
+ $timestamp = microtime(true);
+ $e = new LoggingEvent('fqcn', 'TestLogger', $l, 'test', $timestamp);
+ self::assertEquals($e->getTimeStamp(), $timestamp);
+ }
- public function testGetStartTime() {
- $time = LoggingEvent::getStartTime();
- self::assertInternalType('float', $time);
- $time2 = LoggingEvent::getStartTime();
- self::assertEquals($time, $time2);
- }
+ public function testGetStartTime()
+ {
+ $time = LoggingEvent::getStartTime();
+ self::assertInternalType('float', $time);
+ $time2 = LoggingEvent::getStartTime();
+ self::assertEquals($time, $time2);
+ }
- public function testGetLocationInformation() {
- $hierarchy = Logger::getHierarchy();
- $root = $hierarchy->getRootLogger();
+ public function testGetLocationInformation()
+ {
+ $hierarchy = Logger::getHierarchy();
+ $root = $hierarchy->getRootLogger();
- $a = new LoggingEventTestCaseAppender('A1');
- $a->setLayout(new LoggingEventTestCaseLayout());
- $root->addAppender($a);
+ $a = new LoggingEventTestCaseAppender('A1');
+ $a->setLayout(new LoggingEventTestCaseLayout());
+ $root->addAppender($a);
- $logger = $hierarchy->getLogger('test');
+ $logger = $hierarchy->getLogger('test');
- $line = __LINE__; $logger->debug('test');
- $hierarchy->shutdown();
+ $line = __LINE__; $logger->debug('test');
+ $hierarchy->shutdown();
- $li = self::$locationInfo;
+ $li = self::$locationInfo;
- self::assertEquals(get_class($this), $li->getClassName());
- self::assertEquals(__FILE__, $li->getFileName());
- self::assertEquals($line, $li->getLineNumber());
- self::assertEquals(__FUNCTION__, $li->getMethodName());
- }
+ self::assertEquals(get_class($this), $li->getClassName());
+ self::assertEquals(__FILE__, $li->getFileName());
+ self::assertEquals($line, $li->getLineNumber());
+ self::assertEquals(__FUNCTION__, $li->getMethodName());
+ }
- public function testGetThrowableInformation1() {
- $hierarchy = Logger::getHierarchy();
- $root = $hierarchy->getRootLogger();
+ public function testGetThrowableInformation1()
+ {
+ $hierarchy = Logger::getHierarchy();
+ $root = $hierarchy->getRootLogger();
- $a = new LoggingEventTestCaseAppender('A1');
- $a->setLayout( new LoggingEventTestCaseLayout() );
- $root->addAppender($a);
+ $a = new LoggingEventTestCaseAppender('A1');
+ $a->setLayout( new LoggingEventTestCaseLayout() );
+ $root->addAppender($a);
- $logger = $hierarchy->getLogger('test');
- $logger->debug('test');
- $hierarchy->shutdown();
+ $logger = $hierarchy->getLogger('test');
+ $logger->debug('test');
+ $hierarchy->shutdown();
- $ti = self::$throwableInfo;
+ $ti = self::$throwableInfo;
- self::assertEquals($ti, null);
- }
+ self::assertEquals($ti, null);
+ }
- public function testGetThrowableInformation2() {
- $hierarchy = Logger::getHierarchy();
- $root = $hierarchy->getRootLogger();
+ public function testGetThrowableInformation2()
+ {
+ $hierarchy = Logger::getHierarchy();
+ $root = $hierarchy->getRootLogger();
- $a = new LoggingEventTestCaseAppender('A1');
- $a->setLayout( new LoggingEventTestCaseLayout() );
- $root->addAppender($a);
+ $a = new LoggingEventTestCaseAppender('A1');
+ $a->setLayout( new LoggingEventTestCaseLayout() );
+ $root->addAppender($a);
- $ex = new \Exception('Message1');
- $logger = $hierarchy->getLogger('test');
- $logger->debug('test', $ex);
- $hierarchy->shutdown();
+ $ex = new \Exception('Message1');
+ $logger = $hierarchy->getLogger('test');
+ $logger->debug('test', $ex);
+ $hierarchy->shutdown();
- $ti = self::$throwableInfo;
+ $ti = self::$throwableInfo;
- self::assertInstanceOf("Apache\\Log4php\\ThrowableInformation", $ti);
+ self::assertInstanceOf("Apache\\Log4php\\ThrowableInformation", $ti);
- $result = $ti->getStringRepresentation();
- self::assertInternalType('array', $result);
- }
+ $result = $ti->getStringRepresentation();
+ self::assertInternalType('array', $result);
+ }
}
diff --git a/tests/src/MDCTest.php b/tests/src/MDCTest.php
index 0d33383..020b7e6 100644
--- a/tests/src/MDCTest.php
+++ b/tests/src/MDCTest.php
@@ -29,91 +29,93 @@
/**
* @group main
*/
-class MDCTest extends \PHPUnit_Framework_TestCase {
+class MDCTest extends \PHPUnit_Framework_TestCase
+{
+ /** A pattern with 1 key. */
+ private $pattern1 = "%-5p %c: %X{key1} %m";
- /** A pattern with 1 key. */
- private $pattern1 = "%-5p %c: %X{key1} %m";
+ /** A pattern with 2 keys. */
+ private $pattern2 = "%-5p %c: %X{key1} %X{key2} %m";
- /** A pattern with 2 keys. */
- private $pattern2 = "%-5p %c: %X{key1} %X{key2} %m";
+ /** A pattern with 3 keys (one is numeric). */
+ private $pattern3 = "%-5p %c: %X{key1} %X{key2} %X{3} %m";
- /** A pattern with 3 keys (one is numeric). */
- private $pattern3 = "%-5p %c: %X{key1} %X{key2} %X{3} %m";
+ /** A pattern with a non-existant key. */
+ private $pattern4 = "%-5p %c: %X{key_does_not_exist} %m";
- /** A pattern with a non-existant key. */
- private $pattern4 = "%-5p %c: %X{key_does_not_exist} %m";
+ /** A pattern without a key. */
+ private $pattern5 = "%-5p %c: %X %m";
- /** A pattern without a key. */
- private $pattern5 = "%-5p %c: %X %m";
-
- protected function setUp() {
- MDC::clear();
- }
-
- protected function tearDown() {
- MDC::clear();
- }
-
- public function testPatterns() {
-
- // Create some data to test with
- MDC::put('key1', 'valueofkey1');
- MDC::put('key2', 'valueofkey2');
- MDC::put(3, 'valueofkey3');
-
- $expected = array(
- 'key1' => 'valueofkey1',
- 'key2' => 'valueofkey2',
- 3 => 'valueofkey3',
- );
- $actual = MDC::getMap();
-
- self::assertSame($expected, $actual);
-
- $event = TestHelper::getInfoEvent("Test message");
-
- // Pattern with 1 key
- $actual = $this->formatEvent($event, $this->pattern1);
- $expected = "INFO test: valueofkey1 Test message";
- self::assertEquals($expected, $actual);
-
- // Pattern with 2 keys
- $actual = $this->formatEvent($event, $this->pattern2);
- $expected = "INFO test: valueofkey1 valueofkey2 Test message";
- self::assertEquals($expected, $actual);
-
- // Pattern with 3 keys (one numeric)
- $actual = $this->formatEvent($event, $this->pattern3);
- $expected = "INFO test: valueofkey1 valueofkey2 valueofkey3 Test message";
- self::assertEquals($expected, $actual);
-
- // Pattern with non-existant key
- $actual = $this->formatEvent($event, $this->pattern4);
- $expected = "INFO test: Test message";
- self::assertEquals($expected, $actual);
-
- // Pattern with an empty key
- $actual = $this->formatEvent($event, $this->pattern5);
- $expected = "INFO test: key1=valueofkey1, key2=valueofkey2, 3=valueofkey3 Test message";
- self::assertEquals($expected, $actual);
-
- // Test key removal
- MDC::remove('key1');
- $value = MDC::get('key1');
- self::assertEquals('', $value);
-
- // Pattern with 1 key, now removed
- $actual = $this->formatEvent($event, $this->pattern1);
- $expected = "INFO test: Test message";
- self::assertEquals($expected, $actual);
+ protected function setUp()
+ {
+ MDC::clear();
}
- private function formatEvent($event, $pattern) {
- $layout = new PatternLayout();
- $layout->setConversionPattern($pattern);
- $layout->activateOptions();
- return $layout->format($event);
- }
-}
+ protected function tearDown()
+ {
+ MDC::clear();
+ }
-?>
+ public function testPatterns()
+ {
+ // Create some data to test with
+ MDC::put('key1', 'valueofkey1');
+ MDC::put('key2', 'valueofkey2');
+ MDC::put(3, 'valueofkey3');
+
+ $expected = array(
+ 'key1' => 'valueofkey1',
+ 'key2' => 'valueofkey2',
+ 3 => 'valueofkey3',
+ );
+ $actual = MDC::getMap();
+
+ self::assertSame($expected, $actual);
+
+ $event = TestHelper::getInfoEvent("Test message");
+
+ // Pattern with 1 key
+ $actual = $this->formatEvent($event, $this->pattern1);
+ $expected = "INFO test: valueofkey1 Test message";
+ self::assertEquals($expected, $actual);
+
+ // Pattern with 2 keys
+ $actual = $this->formatEvent($event, $this->pattern2);
+ $expected = "INFO test: valueofkey1 valueofkey2 Test message";
+ self::assertEquals($expected, $actual);
+
+ // Pattern with 3 keys (one numeric)
+ $actual = $this->formatEvent($event, $this->pattern3);
+ $expected = "INFO test: valueofkey1 valueofkey2 valueofkey3 Test message";
+ self::assertEquals($expected, $actual);
+
+ // Pattern with non-existant key
+ $actual = $this->formatEvent($event, $this->pattern4);
+ $expected = "INFO test: Test message";
+ self::assertEquals($expected, $actual);
+
+ // Pattern with an empty key
+ $actual = $this->formatEvent($event, $this->pattern5);
+ $expected = "INFO test: key1=valueofkey1, key2=valueofkey2, 3=valueofkey3 Test message";
+ self::assertEquals($expected, $actual);
+
+ // Test key removal
+ MDC::remove('key1');
+ $value = MDC::get('key1');
+ self::assertEquals('', $value);
+
+ // Pattern with 1 key, now removed
+ $actual = $this->formatEvent($event, $this->pattern1);
+ $expected = "INFO test: Test message";
+ self::assertEquals($expected, $actual);
+ }
+
+ private function formatEvent($event, $pattern)
+ {
+ $layout = new PatternLayout();
+ $layout->setConversionPattern($pattern);
+ $layout->activateOptions();
+
+ return $layout->format($event);
+ }
+}
diff --git a/tests/src/NDCTest.php b/tests/src/NDCTest.php
index b65b822..c07d2d6 100644
--- a/tests/src/NDCTest.php
+++ b/tests/src/NDCTest.php
@@ -28,67 +28,65 @@
/**
* @group main
*/
-class NDCTest extends \PHPUnit_Framework_TestCase {
+class NDCTest extends \PHPUnit_Framework_TestCase
+{
+ public function testItemHandling()
+ {
+ // Test the empty stack
+ self::assertSame('', NDC::get());
+ self::assertSame('', NDC::peek());
+ self::assertSame(0, NDC::getDepth());
+ self::assertSame('', NDC::pop());
- public function testItemHandling()
- {
- // Test the empty stack
- self::assertSame('', NDC::get());
- self::assertSame('', NDC::peek());
- self::assertSame(0, NDC::getDepth());
- self::assertSame('', NDC::pop());
+ // Add some data to the stack
+ NDC::push('1');
+ NDC::push('2');
+ NDC::push('3');
- // Add some data to the stack
- NDC::push('1');
- NDC::push('2');
- NDC::push('3');
+ self::assertSame('1 2 3', NDC::get());
+ self::assertSame('3', NDC::peek());
+ self::assertSame(3, NDC::getDepth());
- self::assertSame('1 2 3', NDC::get());
- self::assertSame('3', NDC::peek());
- self::assertSame(3, NDC::getDepth());
+ // Remove last item
+ self::assertSame('3', NDC::pop());
+ self::assertSame('1 2', NDC::get());
+ self::assertSame('2', NDC::peek());
+ self::assertSame(2, NDC::getDepth());
- // Remove last item
- self::assertSame('3', NDC::pop());
- self::assertSame('1 2', NDC::get());
- self::assertSame('2', NDC::peek());
- self::assertSame(2, NDC::getDepth());
+ // Remove all items
+ NDC::remove();
- // Remove all items
- NDC::remove();
+ // Test the empty stack
+ self::assertSame('', NDC::get());
+ self::assertSame('', NDC::peek());
+ self::assertSame(0, NDC::getDepth());
+ self::assertSame('', NDC::pop());
+ }
- // Test the empty stack
- self::assertSame('', NDC::get());
- self::assertSame('', NDC::peek());
- self::assertSame(0, NDC::getDepth());
- self::assertSame('', NDC::pop());
- }
+ public function testMaxDepth()
+ {
+ // Clear stack; add some testing data
+ NDC::clear();
+ NDC::push('1');
+ NDC::push('2');
+ NDC::push('3');
+ NDC::push('4');
+ NDC::push('5');
+ NDC::push('6');
- public function testMaxDepth()
- {
- // Clear stack; add some testing data
- NDC::clear();
- NDC::push('1');
- NDC::push('2');
- NDC::push('3');
- NDC::push('4');
- NDC::push('5');
- NDC::push('6');
+ self::assertSame('1 2 3 4 5 6', NDC::get());
- self::assertSame('1 2 3 4 5 6', NDC::get());
+ // Edge case, should not change stack
+ NDC::setMaxDepth(6);
+ self::assertSame('1 2 3 4 5 6', NDC::get());
+ self::assertSame(6, NDC::getDepth());
- // Edge case, should not change stack
- NDC::setMaxDepth(6);
- self::assertSame('1 2 3 4 5 6', NDC::get());
- self::assertSame(6, NDC::getDepth());
+ NDC::setMaxDepth(3);
+ self::assertSame('1 2 3', NDC::get());
+ self::assertSame(3, NDC::getDepth());
- NDC::setMaxDepth(3);
- self::assertSame('1 2 3', NDC::get());
- self::assertSame(3, NDC::getDepth());
-
- NDC::setMaxDepth(0);
- self::assertSame('', NDC::get());
- self::assertSame(0, NDC::getDepth());
- }
+ NDC::setMaxDepth(0);
+ self::assertSame('', NDC::get());
+ self::assertSame(0, NDC::getDepth());
+ }
}
-
-?>
diff --git a/tests/src/Pattern/PatternConverterTest.php b/tests/src/Pattern/PatternConverterTest.php
index e491dba..a458369 100644
--- a/tests/src/Pattern/PatternConverterTest.php
+++ b/tests/src/Pattern/PatternConverterTest.php
@@ -27,19 +27,14 @@
use Apache\Log4php\MDC;
use Apache\Log4php\NDC;
-use Apache\Log4php\Pattern\ClassConverter;
use Apache\Log4php\Pattern\CookieConverter;
use Apache\Log4php\Pattern\DateConverter;
use Apache\Log4php\Pattern\EnvironmentConverter;
-use Apache\Log4php\Pattern\FileConverter;
use Apache\Log4php\Pattern\LevelConverter;
-use Apache\Log4php\Pattern\LineConverter;
use Apache\Log4php\Pattern\LiteralConverter;
-use Apache\Log4php\Pattern\LocationConverter;
use Apache\Log4php\Pattern\LoggerConverter;
use Apache\Log4php\Pattern\MdcConverter;
use Apache\Log4php\Pattern\MessageConverter;
-use Apache\Log4php\Pattern\MethodConverter;
use Apache\Log4php\Pattern\NdcConverter;
use Apache\Log4php\Pattern\NewLineConverter;
use Apache\Log4php\Pattern\ProcessConverter;
@@ -49,367 +44,392 @@
use Apache\Log4php\Pattern\SessionConverter;
use Apache\Log4php\Pattern\SessionIdConverter;
use Apache\Log4php\Pattern\SuperglobalConverter;
-use Apache\Log4php\Pattern\ThrowableConverter;
-
use Apache\Log4php\Tests\TestHelper;
/** Converter referencing non-existant superglobal variable. */
-class InvalidSuperglobalConverter extends SuperglobalConverter {
- protected $name = '_FOO';
+class InvalidSuperglobalConverter extends SuperglobalConverter
+{
+ protected $name = '_FOO';
}
/**
* @group pattern
*/
-class PatternConverterTest extends \PHPUnit_Framework_TestCase {
+class PatternConverterTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * A logging event for testing.
+ * @var LoggingEvent
+ */
+ private $event;
- /**
- * A logging event for testing.
- * @var LoggingEvent
- */
- private $event;
+ /**
+ * Fromatting info used with the logging event.
+ * @var LoggerFormattingInfos
+ */
+ private $info;
- /**
- * Fromatting info used with the logging event.
- * @var LoggerFormattingInfos
- */
- private $info;
+ public function __construct()
+ {
+ $this->event = TestHelper::getInfoEvent('foobar');
+ $this->info = new FormattingInfo();
+ }
- public function __construct() {
- $this->event = TestHelper::getInfoEvent('foobar');
- $this->info = new FormattingInfo();
- }
+ public function testCookie()
+ {
+ // Fake a couple of cookies
+ $_COOKIE['test1'] = 'value1';
+ $_COOKIE['test2'] = 'value2';
- public function testCookie() {
- // Fake a couple of cookies
- $_COOKIE['test1'] = 'value1';
- $_COOKIE['test2'] = 'value2';
+ $converter = new CookieConverter($this->info, 'test1');
+ $actual = $converter->convert($this->event);
+ $expected = 'value1';
+ self::assertSame($expected, $actual);
- $converter = new CookieConverter($this->info, 'test1');
- $actual = $converter->convert($this->event);
- $expected = 'value1';
- self::assertSame($expected, $actual);
+ $converter = new CookieConverter($this->info, 'test2');
+ $actual = $converter->convert($this->event);
+ $expected = 'value2';
+ self::assertSame($expected, $actual);
- $converter = new CookieConverter($this->info, 'test2');
- $actual = $converter->convert($this->event);
- $expected = 'value2';
- self::assertSame($expected, $actual);
+ $converter = new CookieConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = "test1=value1, test2=value2";
+ self::assertSame($expected, $actual);
+ }
- $converter = new CookieConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = "test1=value1, test2=value2";
- self::assertSame($expected, $actual);
- }
+ public function testDate()
+ {
+ $converter = new DateConverter($this->info, 'c');
+ $actual = $converter->convert($this->event);
+ $expected = date('c', $this->event->getTimeStamp());
+ self::assertSame($expected, $actual);
- public function testDate() {
- $converter = new DateConverter($this->info, 'c');
- $actual = $converter->convert($this->event);
- $expected = date('c', $this->event->getTimeStamp());
- self::assertSame($expected, $actual);
+ // Format defaults to 'c'
+ $converter = new DateConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = date('c', $this->event->getTimeStamp());
+ self::assertSame($expected, $actual);
- // Format defaults to 'c'
- $converter = new DateConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = date('c', $this->event->getTimeStamp());
- self::assertSame($expected, $actual);
+ $converter = new DateConverter($this->info, '');
+ $actual = $converter->convert($this->event);
+ $expected = date('c', $this->event->getTimeStamp());
+ self::assertSame($expected, $actual);
- $converter = new DateConverter($this->info, '');
- $actual = $converter->convert($this->event);
- $expected = date('c', $this->event->getTimeStamp());
- self::assertSame($expected, $actual);
+ // Test ABSOLUTE
+ $converter = new DateConverter($this->info, 'ABSOLUTE');
+ $actual = $converter->convert($this->event);
+ $expected = date('H:i:s', $this->event->getTimeStamp());
+ self::assertSame($expected, $actual);
- // Test ABSOLUTE
- $converter = new DateConverter($this->info, 'ABSOLUTE');
- $actual = $converter->convert($this->event);
- $expected = date('H:i:s', $this->event->getTimeStamp());
- self::assertSame($expected, $actual);
+ // Test DATE
+ $converter = new DateConverter($this->info, 'DATE');
+ $actual = $converter->convert($this->event);
+ $expected = date('d M Y H:i:s.', $this->event->getTimeStamp());
- // Test DATE
- $converter = new DateConverter($this->info, 'DATE');
- $actual = $converter->convert($this->event);
- $expected = date('d M Y H:i:s.', $this->event->getTimeStamp());
+ $timestamp = $this->event->getTimeStamp();
+ $ms = floor(($timestamp - floor($timestamp)) * 1000);
+ $ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
- $timestamp = $this->event->getTimeStamp();
- $ms = floor(($timestamp - floor($timestamp)) * 1000);
- $ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
+ $expected .= $ms;
- $expected .= $ms;
+ self::assertSame($expected, $actual);
+ }
- self::assertSame($expected, $actual);
- }
+ public function testEnvironment()
+ {
+ // Fake a couple of environment values
+ $_ENV['test1'] = 'value1';
+ $_ENV['test2'] = 'value2';
- public function testEnvironment() {
- // Fake a couple of environment values
- $_ENV['test1'] = 'value1';
- $_ENV['test2'] = 'value2';
+ $converter = new EnvironmentConverter($this->info, 'test1');
+ $actual = $converter->convert($this->event);
+ $expected = 'value1';
+ self::assertSame($expected, $actual);
- $converter = new EnvironmentConverter($this->info, 'test1');
- $actual = $converter->convert($this->event);
- $expected = 'value1';
- self::assertSame($expected, $actual);
+ $converter = new EnvironmentConverter($this->info, 'test2');
+ $actual = $converter->convert($this->event);
+ $expected = 'value2';
+ self::assertSame($expected, $actual);
+ }
- $converter = new EnvironmentConverter($this->info, 'test2');
- $actual = $converter->convert($this->event);
- $expected = 'value2';
- self::assertSame($expected, $actual);
- }
+ public function testLevel()
+ {
+ $converter = new LevelConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = $this->event->getLevel()->toString();
+ self::assertEquals($expected, $actual);
+ }
- public function testLevel() {
- $converter = new LevelConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = $this->event->getLevel()->toString();
- self::assertEquals($expected, $actual);
- }
+ public function testLiteral()
+ {
+ $converter = new LiteralConverter('foo bar baz');
+ $actual = $converter->convert($this->event);
+ $expected = 'foo bar baz';
+ self::assertEquals($expected, $actual);
+ }
- public function testLiteral() {
- $converter = new LiteralConverter('foo bar baz');
- $actual = $converter->convert($this->event);
- $expected = 'foo bar baz';
- self::assertEquals($expected, $actual);
- }
+ public function testLoggerWithoutOption()
+ {
+ $event = TestHelper::getInfoEvent('foo', 'TestLoggerName');
+ $converter = new LoggerConverter($this->info);
- public function testLoggerWithoutOption() {
- $event = TestHelper::getInfoEvent('foo', 'TestLoggerName');
- $converter = new LoggerConverter($this->info);
+ $actual = $converter->convert($event);
+ $expected = 'TestLoggerName';
+ self::assertEquals($expected, $actual);
+ }
- $actual = $converter->convert($event);
- $expected = 'TestLoggerName';
- self::assertEquals($expected, $actual);
- }
+ public function testLoggerWithOption0()
+ {
+ $event = TestHelper::getInfoEvent('foo', 'TestLoggerName');
+ $converter = new LoggerConverter($this->info, '0');
- public function testLoggerWithOption0() {
- $event = TestHelper::getInfoEvent('foo', 'TestLoggerName');
- $converter = new LoggerConverter($this->info, '0');
+ $actual = $converter->convert($event);
+ $expected = 'TestLoggerName';
+ self::assertEquals($expected, $actual);
+ }
- $actual = $converter->convert($event);
- $expected = 'TestLoggerName';
- self::assertEquals($expected, $actual);
- }
+ public function testLocation()
+ {
+ $config = TestHelper::getEchoPatternConfig("%file:%line:%class:%method");
+ Logger::configure($config);
- public function testLocation() {
- $config = TestHelper::getEchoPatternConfig("%file:%line:%class:%method");
- Logger::configure($config);
+ // Test by capturing output. Logging methods of a Logger object must
+ // be used for the location info to be formed correctly.
+ ob_start();
+ $log = Logger::getLogger('foo');
+ $log->info('foo'); $line = __LINE__; // Do NOT move this to next line.
+ $actual = ob_get_contents();
+ ob_end_clean();
- // Test by capturing output. Logging methods of a Logger object must
- // be used for the location info to be formed correctly.
- ob_start();
- $log = Logger::getLogger('foo');
- $log->info('foo'); $line = __LINE__; // Do NOT move this to next line.
- $actual = ob_get_contents();
- ob_end_clean();
+ $expected = implode(':', array(__FILE__, $line, __CLASS__, __FUNCTION__));
+ self::assertSame($expected, $actual);
- $expected = implode(':', array(__FILE__, $line, __CLASS__, __FUNCTION__));
- self::assertSame($expected, $actual);
+ Logger::resetConfiguration();
+ }
- Logger::resetConfiguration();
- }
+ public function testLocation2()
+ {
+ $config = TestHelper::getEchoPatternConfig("%location");
+ Logger::configure($config);
- public function testLocation2() {
- $config = TestHelper::getEchoPatternConfig("%location");
- Logger::configure($config);
+ // Test by capturing output. Logging methods of a Logger object must
+ // be used for the location info to be formed correctly.
+ ob_start();
+ $log = Logger::getLogger('foo');
+ $log->info('foo'); $line = __LINE__; // Do NOT move this to next line.
+ $actual = ob_get_contents();
+ ob_end_clean();
- // Test by capturing output. Logging methods of a Logger object must
- // be used for the location info to be formed correctly.
- ob_start();
- $log = Logger::getLogger('foo');
- $log->info('foo'); $line = __LINE__; // Do NOT move this to next line.
- $actual = ob_get_contents();
- ob_end_clean();
+ $class = __CLASS__;
+ $func = __FUNCTION__;
+ $file = __FILE__;
- $class = __CLASS__;
- $func = __FUNCTION__;
- $file = __FILE__;
+ $expected = "$class.$func($file:$line)";
+ self::assertSame($expected, $actual);
- $expected = "$class.$func($file:$line)";
- self::assertSame($expected, $actual);
+ Logger::resetConfiguration();
+ }
- Logger::resetConfiguration();
- }
+ public function testMessage()
+ {
+ $expected = "This is a message.";
+ $event = TestHelper::getInfoEvent($expected);
+ $converter = new MessageConverter($this->info);
+ $actual = $converter->convert($event);
+ self::assertSame($expected, $actual);
+ }
- public function testMessage() {
- $expected = "This is a message.";
- $event = TestHelper::getInfoEvent($expected);
- $converter = new MessageConverter($this->info);
- $actual = $converter->convert($event);
- self::assertSame($expected, $actual);
- }
+ public function testMDC()
+ {
+ MDC::put('foo', 'bar');
+ MDC::put('bla', 'tra');
- public function testMDC() {
- MDC::put('foo', 'bar');
- MDC::put('bla', 'tra');
-
- // Entire context
- $converter = new MdcConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = 'foo=bar, bla=tra';
- self::assertSame($expected, $actual);
+ // Entire context
+ $converter = new MdcConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = 'foo=bar, bla=tra';
+ self::assertSame($expected, $actual);
- // Just foo
- $converter = new MdcConverter($this->info, 'foo');
- $actual = $converter->convert($this->event);
- $expected = 'bar';
- self::assertSame($expected, $actual);
+ // Just foo
+ $converter = new MdcConverter($this->info, 'foo');
+ $actual = $converter->convert($this->event);
+ $expected = 'bar';
+ self::assertSame($expected, $actual);
- // Non existant key
- $converter = new MdcConverter($this->info, 'doesnotexist');
- $actual = $converter->convert($this->event);
- $expected = '';
- self::assertSame($expected, $actual);
+ // Non existant key
+ $converter = new MdcConverter($this->info, 'doesnotexist');
+ $actual = $converter->convert($this->event);
+ $expected = '';
+ self::assertSame($expected, $actual);
- MDC::clear();
- }
+ MDC::clear();
+ }
- public function testNDC() {
- NDC::push('foo');
- NDC::push('bar');
- NDC::push('baz');
+ public function testNDC()
+ {
+ NDC::push('foo');
+ NDC::push('bar');
+ NDC::push('baz');
- $converter = new NdcConverter($this->info);
- $expected = 'foo bar baz';
- $actual = $converter->convert($this->event);
- self::assertEquals($expected, $actual);
- }
+ $converter = new NdcConverter($this->info);
+ $expected = 'foo bar baz';
+ $actual = $converter->convert($this->event);
+ self::assertEquals($expected, $actual);
+ }
- public function testNewline() {
- $converter = new NewLineConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = PHP_EOL;
- self::assertSame($expected, $actual);
- }
+ public function testNewline()
+ {
+ $converter = new NewLineConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = PHP_EOL;
+ self::assertSame($expected, $actual);
+ }
- public function testProcess() {
- $converter = new ProcessConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = getmypid();
- self::assertSame($expected, $actual);
- }
+ public function testProcess()
+ {
+ $converter = new ProcessConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = getmypid();
+ self::assertSame($expected, $actual);
+ }
- public function testRelative() {
- $converter = new RelativeConverter($this->info);
- $expected = number_format($this->event->getTimeStamp() - $this->event->getStartTime(), 4);
- $actual = $converter->convert($this->event);
- self::assertSame($expected, $actual);
- }
+ public function testRelative()
+ {
+ $converter = new RelativeConverter($this->info);
+ $expected = number_format($this->event->getTimeStamp() - $this->event->getStartTime(), 4);
+ $actual = $converter->convert($this->event);
+ self::assertSame($expected, $actual);
+ }
- public function testRequest() {
- // Fake a couple of request values
- $_REQUEST['test1'] = 'value1';
- $_REQUEST['test2'] = 'value2';
+ public function testRequest()
+ {
+ // Fake a couple of request values
+ $_REQUEST['test1'] = 'value1';
+ $_REQUEST['test2'] = 'value2';
- // Entire request
- $converter = new RequestConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = 'test1=value1, test2=value2';
- self::assertSame($expected, $actual);
+ // Entire request
+ $converter = new RequestConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = 'test1=value1, test2=value2';
+ self::assertSame($expected, $actual);
- // Just test2
- $converter = new RequestConverter($this->info, 'test2');
- $actual = $converter->convert($this->event);
- $expected = 'value2';
- self::assertSame($expected, $actual);
- }
+ // Just test2
+ $converter = new RequestConverter($this->info, 'test2');
+ $actual = $converter->convert($this->event);
+ $expected = 'value2';
+ self::assertSame($expected, $actual);
+ }
- public function testServer() {
- // Fake a server value
- $_SERVER['test1'] = 'value1';
+ public function testServer()
+ {
+ // Fake a server value
+ $_SERVER['test1'] = 'value1';
- $converter = new ServerConverter($this->info, 'test1');
- $actual = $converter->convert($this->event);
- $expected = 'value1';
- self::assertSame($expected, $actual);
- }
+ $converter = new ServerConverter($this->info, 'test1');
+ $actual = $converter->convert($this->event);
+ $expected = 'value1';
+ self::assertSame($expected, $actual);
+ }
- public function testSession() {
- // Fake a session value
- $_SESSION['test1'] = 'value1';
+ public function testSession()
+ {
+ // Fake a session value
+ $_SESSION['test1'] = 'value1';
- $converter = new SessionConverter($this->info, 'test1');
- $actual = $converter->convert($this->event);
- $expected = 'value1';
- self::assertSame($expected, $actual);
- }
+ $converter = new SessionConverter($this->info, 'test1');
+ $actual = $converter->convert($this->event);
+ $expected = 'value1';
+ self::assertSame($expected, $actual);
+ }
- public function testSessionID() {
- $converter = new SessionIdConverter($this->info);
- $actual = $converter->convert($this->event);
- $expected = session_id();
- self::assertSame($expected, $actual);
- }
+ public function testSessionID()
+ {
+ $converter = new SessionIdConverter($this->info);
+ $actual = $converter->convert($this->event);
+ $expected = session_id();
+ self::assertSame($expected, $actual);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: InvalidSuperglobalConverter: Cannot find superglobal variable $_FOO
- */
- public function testNonexistantSuperglobal() {
- $converter = new InvalidSuperglobalConverter($this->info);
- $actual = $converter->convert($this->event);
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: InvalidSuperglobalConverter: Cannot find superglobal variable $_FOO
+ */
+ public function testNonexistantSuperglobal()
+ {
+ $converter = new InvalidSuperglobalConverter($this->info);
+ $actual = $converter->convert($this->event);
+ }
- public function testFormattingTrimRight() {
- $event = TestHelper::getInfoEvent('0123456789');
+ public function testFormattingTrimRight()
+ {
+ $event = TestHelper::getInfoEvent('0123456789');
- $info = new FormattingInfo();
- $info->max = 5;
+ $info = new FormattingInfo();
+ $info->max = 5;
- $converter = new MessageConverter($info);
- $actual = "";
- $converter->format($actual, $event);
- $expected = "01234";
- self::assertSame($expected, $actual);
- }
+ $converter = new MessageConverter($info);
+ $actual = "";
+ $converter->format($actual, $event);
+ $expected = "01234";
+ self::assertSame($expected, $actual);
+ }
- public function testFormattingTrimLeft() {
- $event = TestHelper::getInfoEvent('0123456789');
+ public function testFormattingTrimLeft()
+ {
+ $event = TestHelper::getInfoEvent('0123456789');
- $info = new FormattingInfo();
- $info->max = 5;
- $info->trimLeft = true;
+ $info = new FormattingInfo();
+ $info->max = 5;
+ $info->trimLeft = true;
- $converter = new MessageConverter($info);
- $actual = "";
- $converter->format($actual, $event);
- $expected = "56789";
- self::assertSame($expected, $actual);
- }
+ $converter = new MessageConverter($info);
+ $actual = "";
+ $converter->format($actual, $event);
+ $expected = "56789";
+ self::assertSame($expected, $actual);
+ }
- public function testFormattingPadEmpty() {
- $event = TestHelper::getInfoEvent('');
+ public function testFormattingPadEmpty()
+ {
+ $event = TestHelper::getInfoEvent('');
- $info = new FormattingInfo();
- $info->min = 5;
+ $info = new FormattingInfo();
+ $info->min = 5;
- $converter = new MessageConverter($info);
- $actual = "";
- $converter->format($actual, $event);
- $expected = " ";
- self::assertSame($expected, $actual);
- }
+ $converter = new MessageConverter($info);
+ $actual = "";
+ $converter->format($actual, $event);
+ $expected = " ";
+ self::assertSame($expected, $actual);
+ }
- public function testFormattingPadLeft() {
- $event = TestHelper::getInfoEvent('0');
+ public function testFormattingPadLeft()
+ {
+ $event = TestHelper::getInfoEvent('0');
- $info = new FormattingInfo();
- $info->min = 5;
+ $info = new FormattingInfo();
+ $info->min = 5;
- $converter = new MessageConverter($info);
- $actual = "";
- $converter->format($actual, $event);
- $expected = " 0";
- self::assertSame($expected, $actual);
- }
+ $converter = new MessageConverter($info);
+ $actual = "";
+ $converter->format($actual, $event);
+ $expected = " 0";
+ self::assertSame($expected, $actual);
+ }
- public function testFormattingPadRight() {
- $event = TestHelper::getInfoEvent('0');
+ public function testFormattingPadRight()
+ {
+ $event = TestHelper::getInfoEvent('0');
- $info = new FormattingInfo();
- $info->min = 5;
- $info->padLeft = false;
+ $info = new FormattingInfo();
+ $info->min = 5;
+ $info->padLeft = false;
- $converter = new MessageConverter($info);
- $actual = "";
- $converter->format($actual, $event);
- $expected = "0 ";
- self::assertSame($expected, $actual);
- }
+ $converter = new MessageConverter($info);
+ $actual = "";
+ $converter->format($actual, $event);
+ $expected = "0 ";
+ self::assertSame($expected, $actual);
+ }
}
diff --git a/tests/src/ReflectionUtilsTest.php b/tests/src/ReflectionUtilsTest.php
index 2357657..1e5229b 100644
--- a/tests/src/ReflectionUtilsTest.php
+++ b/tests/src/ReflectionUtilsTest.php
@@ -24,23 +24,28 @@
use Apache\Log4php\ReflectionUtils;
-class Simple {
+class Simple
+{
private $name;
private $male;
- public function getName() {
+ public function getName()
+ {
return $this->name;
}
- public function isMale() {
+ public function isMale()
+ {
return $this->male;
}
- public function setName($name) {
+ public function setName($name)
+ {
$this->name = $name;
}
- public function setMale($male) {
+ public function setMale($male)
+ {
$this->male = $male;
}
}
@@ -48,44 +53,48 @@
/**
* @group main
*/
-class ReflectionUtilsTest extends \PHPUnit_Framework_TestCase {
+class ReflectionUtilsTest extends \PHPUnit_Framework_TestCase
+{
+ public function testSimpleSet()
+ {
+ $s = new Simple();
+ $ps = new ReflectionUtils($s);
+ $ps->setProperty("name", "Joe");
+ $ps->setProperty("male", true);
- public function testSimpleSet() {
- $s = new Simple();
- $ps = new ReflectionUtils($s);
- $ps->setProperty("name", "Joe");
- $ps->setProperty("male", true);
+ $this->assertEquals($s->isMale(), true);
+ $this->assertEquals($s->getName(), 'Joe');
+ }
- $this->assertEquals($s->isMale(), true);
- $this->assertEquals($s->getName(), 'Joe');
- }
+ public function testSimpleArraySet()
+ {
+ $arr['xxxname'] = 'Joe';
+ $arr['xxxmale'] = true;
- public function testSimpleArraySet() {
- $arr['xxxname'] = 'Joe';
- $arr['xxxmale'] = true;
+ $s = new Simple();
+ $ps = new ReflectionUtils($s);
+ $ps->setProperties($arr, "xxx");
- $s = new Simple();
- $ps = new ReflectionUtils($s);
- $ps->setProperties($arr, "xxx");
+ $this->assertEquals($s->getName(), 'Joe');
+ $this->assertEquals($s->isMale(), true);
+ }
- $this->assertEquals($s->getName(), 'Joe');
- $this->assertEquals($s->isMale(), true);
- }
+ public function testStaticArraySet()
+ {
+ $arr['xxxname'] = 'Joe';
+ $arr['xxxmale'] = true;
- public function testStaticArraySet() {
- $arr['xxxname'] = 'Joe';
- $arr['xxxmale'] = true;
+ $s = new Simple();
+ ReflectionUtils::setPropertiesByObject($s,$arr,"xxx");
- $s = new Simple();
- ReflectionUtils::setPropertiesByObject($s,$arr,"xxx");
-
- $this->assertEquals($s->getName(), 'Joe');
- $this->assertEquals($s->isMale(), true);
- }
- public function testCreateObject() {
+ $this->assertEquals($s->getName(), 'Joe');
+ $this->assertEquals($s->isMale(), true);
+ }
+ public function testCreateObject()
+ {
$class = 'Apache\\Log4php\\Layouts\\SimpleLayout';
- $object = ReflectionUtils::createObject($class);
- $name = get_class($object);
- self::assertEquals($name, $class);
- }
+ $object = ReflectionUtils::createObject($class);
+ $name = get_class($object);
+ self::assertEquals($name, $class);
+ }
}
diff --git a/tests/src/Renderers/RendererMapTest.php b/tests/src/Renderers/RendererMapTest.php
index 3960660..664bb71 100644
--- a/tests/src/Renderers/RendererMapTest.php
+++ b/tests/src/Renderers/RendererMapTest.php
@@ -27,223 +27,229 @@
use Apache\Log4php\LoggerException;
/** Renders everything as 'foo'. */
-class FooRenderer implements RendererInterface {
- public function render($input) {
- return 'foo';
- }
+class FooRenderer implements RendererInterface
+{
+ public function render($input)
+ {
+ return 'foo';
+ }
}
class InvalidCostumObjectRenderer { }
-class Fruit3 {
+class Fruit3
+{
public $test1 = 'test1';
public $test2 = 'test2';
public $test3 = 'test3';
}
-class Fruit3Descendant extends Fruit3 {
+class Fruit3Descendant extends Fruit3
+{
}
-class FruitRenderer3 implements RendererInterface {
- public function render($fruit) {
- return $fruit->test1 . ',' . $fruit->test2 . ',' . $fruit->test3;
- }
+class FruitRenderer3 implements RendererInterface
+{
+ public function render($fruit)
+ {
+ return $fruit->test1 . ',' . $fruit->test2 . ',' . $fruit->test3;
+ }
}
-class SampleObject {
+class SampleObject
+{
}
/**
* @group renderers
*/
-class RendererMapTest extends \PHPUnit_Framework_TestCase {
+class RendererMapTest extends \PHPUnit_Framework_TestCase
+{
+ public function testDefaults()
+ {
+ $map = new RendererMap();
+ $actual = $map->getByClassName('Exception');
+ $expected = 'Apache\\Log4php\\Renderers\\ExceptionRenderer';
+ self::assertInstanceOf($expected, $actual);
- public function testDefaults() {
+ // Check non-configured objects return null
+ self::assertNull($map->getByObject(new stdClass()));
+ self::assertNull($map->getByClassName('stdClass'));
+ }
- $map = new RendererMap();
- $actual = $map->getByClassName('Exception');
- $expected = 'Apache\\Log4php\\Renderers\\ExceptionRenderer';
- self::assertInstanceOf($expected, $actual);
+ public function testClear()
+ {
+ $map = new RendererMap();
+ $map->clear(); // This should clear the map and remove default renderers
+ self::assertNull($map->getByClassName('Exception'));
+ }
- // Check non-configured objects return null
- self::assertNull($map->getByObject(new stdClass()));
- self::assertNull($map->getByClassName('stdClass'));
- }
+ public function testFindAndRender()
+ {
+ $map = new RendererMap();
+ $map->addRenderer('Fruit3', 'FruitRenderer3');
- public function testClear()
- {
- $map = new RendererMap();
- $map->clear(); // This should clear the map and remove default renderers
- self::assertNull($map->getByClassName('Exception'));
- }
+ $fruit = new Fruit3();
+ $descendant = new Fruit3Descendant();
- public function testFindAndRender()
- {
- $map = new RendererMap();
- $map->addRenderer('Fruit3', 'FruitRenderer3');
+ // Check rendering of fruit
+ $actual = $map->findAndRender($fruit);
+ $expected = 'test1,test2,test3';
+ self::assertSame($expected, $actual);
- $fruit = new Fruit3();
- $descendant = new Fruit3Descendant();
+ $actual = $map->getByObject($fruit);
+ self::assertInstanceOf('FruitRenderer3', $actual);
- // Check rendering of fruit
- $actual = $map->findAndRender($fruit);
- $expected = 'test1,test2,test3';
- self::assertSame($expected, $actual);
+ // Check rendering of fruit's descendant
+ $actual = $map->findAndRender($descendant);
+ $expected = 'test1,test2,test3';
+ self::assertSame($expected, $actual);
- $actual = $map->getByObject($fruit);
- self::assertInstanceOf('FruitRenderer3', $actual);
+ $actual = $map->getByObject($descendant);
+ self::assertInstanceOf('FruitRenderer3', $actual);
- // Check rendering of fruit's descendant
- $actual = $map->findAndRender($descendant);
- $expected = 'test1,test2,test3';
- self::assertSame($expected, $actual);
+ // Test rendering null returns null
+ self::assertNull($map->findAndRender(null));
+ }
- $actual = $map->getByObject($descendant);
- self::assertInstanceOf('FruitRenderer3', $actual);
+ /**
+ * Try adding a non-existant class as renderer.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed adding renderer. Rendering class [DoesNotExist] not found.
+ */
+ public function testAddRendererError1()
+ {
+ $map = new RendererMap();
+ $map->addRenderer('Fruit3', 'DoesNotExist');
+ }
- // Test rendering null returns null
- self::assertNull($map->findAndRender(null));
- }
+ /**
+ * Try adding a class which does not implement RendererInterface as renderer.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed adding renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
+ */
+ public function testAddRendererError2()
+ {
+ $map = new RendererMap();
+ $map->addRenderer('Fruit3', 'stdClass');
+ }
- /**
- * Try adding a non-existant class as renderer.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed adding renderer. Rendering class [DoesNotExist] not found.
- */
- public function testAddRendererError1()
- {
- $map = new RendererMap();
- $map->addRenderer('Fruit3', 'DoesNotExist');
- }
+ public function testAddRendererError3()
+ {
+ $map = new RendererMap();
+ @$map->addRenderer('Fruit3', 'stdClass');
+ self::assertNull($map->getByClassName('Fruit3'));
- /**
- * Try adding a class which does not implement RendererInterface as renderer.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed adding renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
- */
- public function testAddRendererError2()
- {
- $map = new RendererMap();
- $map->addRenderer('Fruit3', 'stdClass');
- }
+ @$map->addRenderer('Fruit3', 'DoesNotExist');
+ self::assertNull($map->getByClassName('Fruit3'));
+ }
- public function testAddRendererError3()
- {
- $map = new RendererMap();
- @$map->addRenderer('Fruit3', 'stdClass');
- self::assertNull($map->getByClassName('Fruit3'));
+ /**
+ * Try setting a non-existant class as default renderer.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed setting default renderer. Rendering class [DoesNotExist] not found.
+ */
+ public function testSetDefaultRendererError1()
+ {
+ $map = new RendererMap();
+ $map->setDefaultRenderer('DoesNotExist');
+ }
- @$map->addRenderer('Fruit3', 'DoesNotExist');
- self::assertNull($map->getByClassName('Fruit3'));
- }
+ /**
+ * Try setting a class which does not implement RendererInterface as default renderer.
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage Failed setting default renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
+ */
+ public function testSetDefaultRendererError2()
+ {
+ $map = new RendererMap();
+ $map->setDefaultRenderer('stdClass');
+ }
- /**
- * Try setting a non-existant class as default renderer.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed setting default renderer. Rendering class [DoesNotExist] not found.
- */
- public function testSetDefaultRendererError1()
- {
- $map = new RendererMap();
- $map->setDefaultRenderer('DoesNotExist');
- }
+ public function testSetDefaultRendererError3()
+ {
+ $map = new RendererMap();
+ $expected = $map->getDefaultRenderer();
- /**
- * Try setting a class which does not implement RendererInterface as default renderer.
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage Failed setting default renderer. Rendering class [stdClass] does not implement the RendererInterface interface.
- */
- public function testSetDefaultRendererError2()
- {
- $map = new RendererMap();
- $map->setDefaultRenderer('stdClass');
- }
+ @$map->setDefaultRenderer('stdClass');
+ $actual = $map->getDefaultRenderer();
+ self::assertSame($expected, $actual);
- public function testSetDefaultRendererError3()
- {
- $map = new RendererMap();
- $expected = $map->getDefaultRenderer();
+ @$map->setDefaultRenderer('DoesNotExist');
+ $actual = $map->getDefaultRenderer();
+ self::assertSame($expected, $actual);
+ }
- @$map->setDefaultRenderer('stdClass');
- $actual = $map->getDefaultRenderer();
- self::assertSame($expected, $actual);
+ public function testFetchingRenderer()
+ {
+ $map = new RendererMap();
+ $map->addRenderer('Fruit3', 'FruitRenderer3');
+ }
- @$map->setDefaultRenderer('DoesNotExist');
- $actual = $map->getDefaultRenderer();
- self::assertSame($expected, $actual);
- }
+ public function testDefaultRenderer()
+ {
+ $fruit = new Fruit3();
- public function testFetchingRenderer()
- {
- $map = new RendererMap();
- $map->addRenderer('Fruit3', 'FruitRenderer3');
- }
+ $map = new RendererMap();
+ $actual = $map->findAndRender($fruit);
- public function testDefaultRenderer()
- {
- $fruit = new Fruit3();
+ $defaultRenderer = new DefaultRenderer();
+ $expected = $defaultRenderer->render($fruit);
+ self::assertSame($expected, $actual);
+ }
- $map = new RendererMap();
- $actual = $map->findAndRender($fruit);
+ public function testOverrideDefaultRenderer()
+ {
+ $map = new RendererMap();
+ $default = $map->getDefaultRenderer();
- $defaultRenderer = new DefaultRenderer();
- $expected = $defaultRenderer->render($fruit);
- self::assertSame($expected, $actual);
- }
+ $array = array(1, 2, 3);
- public function testOverrideDefaultRenderer()
- {
- $map = new RendererMap();
- $default = $map->getDefaultRenderer();
+ $actual = $map->findAndRender($array);
+ $expected = print_r($array, true);
+ self::assertSame($actual, $expected);
- $array = array(1, 2, 3);
+ // Now switch the default renderer
+ $map->setDefaultRenderer('FooRenderer');
+ $actual = $map->findAndRender($array);
+ $expected = 'foo';
+ self::assertSame($actual, $expected);
+ }
- $actual = $map->findAndRender($array);
- $expected = print_r($array, true);
- self::assertSame($actual, $expected);
+ public function testGetByObjectCrap()
+ {
+ $map = new RendererMap();
- // Now switch the default renderer
- $map->setDefaultRenderer('FooRenderer');
- $actual = $map->findAndRender($array);
- $expected = 'foo';
- self::assertSame($actual, $expected);
- }
+ // Non object input should always return null
+ self::assertNull($map->getByObject(null));
+ self::assertNull($map->getByObject(array()));
+ self::assertNull($map->getByObject('sdasda'));
+ }
- public function testGetByObjectCrap()
- {
- $map = new RendererMap();
+ public function testXMLConfig()
+ {
+ $map = Logger::getHierarchy()->getRendererMap();
+ Logger::resetConfiguration();
- // Non object input should always return null
- self::assertNull($map->getByObject(null));
- self::assertNull($map->getByObject(array()));
- self::assertNull($map->getByObject('sdasda'));
- }
+ $expected = 'Apache\\Log4php\\Renderers\\DefaultRenderer';
+ self::assertInstanceOf($expected, $map->getDefaultRenderer());
- public function testXMLConfig()
- {
- $map = Logger::getHierarchy()->getRendererMap();
- Logger::resetConfiguration();
+ Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_default_renderer.xml');
+ self::assertInstanceOf('FruitRenderer3', $map->getDefaultRenderer());
- $expected = 'Apache\\Log4php\\Renderers\\DefaultRenderer';
- self::assertInstanceOf($expected, $map->getDefaultRenderer());
+ Logger::resetConfiguration();
+ self::assertInstanceOf($expected, $map->getDefaultRenderer());
+ }
- Logger::configure(PHPUNIT_CONFIG_DIR . '/renderers/config_default_renderer.xml');
- self::assertInstanceOf('FruitRenderer3', $map->getDefaultRenderer());
+ public function testExceptionRenderer()
+ {
+ $ex = new LoggerException("This is a test");
- Logger::resetConfiguration();
- self::assertInstanceOf($expected, $map->getDefaultRenderer());
- }
+ $map = new RendererMap();
+ $actual = $map->findAndRender($ex);
+ $expected = (string) $ex;
- public function testExceptionRenderer()
- {
- $ex = new LoggerException("This is a test");
-
- $map = new RendererMap();
- $actual = $map->findAndRender($ex);
- $expected = (string) $ex;
-
- self::assertSame($expected, $actual);
- }
-
+ self::assertSame($expected, $actual);
+ }
}
diff --git a/tests/src/RootLoggerTest.php b/tests/src/RootLoggerTest.php
index aa6429e..471ed7e 100644
--- a/tests/src/RootLoggerTest.php
+++ b/tests/src/RootLoggerTest.php
@@ -29,39 +29,43 @@
/**
* @group main
*/
-class RootLoggerTest extends \PHPUnit_Framework_TestCase {
+class RootLoggerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testInitialSetup()
+ {
+ $root = new RootLogger();
+ self::assertSame(Level::getLevelAll(), $root->getLevel());
+ self::assertSame(Level::getLevelAll(), $root->getEffectiveLevel());
+ self::assertSame('root', $root->getName());
+ self::assertNull($root->getParent());
+ }
- public function testInitialSetup() {
- $root = new RootLogger();
- self::assertSame(Level::getLevelAll(), $root->getLevel());
- self::assertSame(Level::getLevelAll(), $root->getEffectiveLevel());
- self::assertSame('root', $root->getName());
- self::assertNull($root->getParent());
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: RootLogger cannot have a parent.
+ */
+ public function testSetParentWarning()
+ {
+ $root = new RootLogger();
+ $logger = new Logger('test');
+ $root->setParent($logger);
+ }
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: RootLogger cannot have a parent.
- */
- public function testSetParentWarning() {
- $root = new RootLogger();
- $logger = new Logger('test');
- $root->setParent($logger);
- }
+ public function testSetParentResult()
+ {
+ $root = new RootLogger();
+ $logger = new Logger('test');
+ @$root->setParent($logger);
+ self::assertNull($root->getParent());
+ }
- public function testSetParentResult() {
- $root = new RootLogger();
- $logger = new Logger('test');
- @$root->setParent($logger);
- self::assertNull($root->getParent());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- * @expectedExceptionMessage log4php: Cannot set RootLogger level to null.
- */
- public function testNullLevelWarning() {
- $root = new RootLogger();
- $root->setLevel(null);
- }
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ * @expectedExceptionMessage log4php: Cannot set RootLogger level to null.
+ */
+ public function testNullLevelWarning()
+ {
+ $root = new RootLogger();
+ $root->setLevel(null);
+ }
}
diff --git a/tests/src/TestHelper.php b/tests/src/TestHelper.php
index c653eca..5366e6d 100644
--- a/tests/src/TestHelper.php
+++ b/tests/src/TestHelper.php
@@ -29,132 +29,141 @@
use Apache\Log4php\LoggingEvent;
/** A set of helper functions for running tests. */
-class TestHelper {
+class TestHelper
+{
+ /**
+ * Returns a test logging event with level set to TRACE.
+ * @return LoggingEvent
+ */
+ public static function getTraceEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelTrace(), $message);
+ }
- /**
- * Returns a test logging event with level set to TRACE.
- * @return LoggingEvent
- */
- public static function getTraceEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelTrace(), $message);
- }
+ /**
+ * Returns a test logging event with level set to DEBUG.
+ * @return LoggingEvent
+ */
+ public static function getDebugEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelDebug(), $message);
+ }
- /**
- * Returns a test logging event with level set to DEBUG.
- * @return LoggingEvent
- */
- public static function getDebugEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelDebug(), $message);
- }
+ /**
+ * Returns a test logging event with level set to INFO.
+ * @return LoggingEvent
+ */
+ public static function getInfoEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelInfo(), $message);
+ }
- /**
- * Returns a test logging event with level set to INFO.
- * @return LoggingEvent
- */
- public static function getInfoEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelInfo(), $message);
- }
+ /**
+ * Returns a test logging event with level set to WARN.
+ * @return LoggingEvent
+ */
+ public static function getWarnEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelWarn(), $message);
+ }
- /**
- * Returns a test logging event with level set to WARN.
- * @return LoggingEvent
- */
- public static function getWarnEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelWarn(), $message);
- }
+ /**
+ * Returns a test logging event with level set to ERROR.
+ * @return LoggingEvent
+ */
+ public static function getErrorEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelError(), $message);
+ }
- /**
- * Returns a test logging event with level set to ERROR.
- * @return LoggingEvent
- */
- public static function getErrorEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelError(), $message);
- }
+ /**
+ * Returns a test logging event with level set to FATAL.
+ * @return LoggingEvent
+ */
+ public static function getFatalEvent($message = 'test', $logger = "test")
+ {
+ return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelFatal(), $message);
+ }
- /**
- * Returns a test logging event with level set to FATAL.
- * @return LoggingEvent
- */
- public static function getFatalEvent($message = 'test', $logger = "test") {
- return new LoggingEvent(__CLASS__, new Logger($logger), Level::getLevelFatal(), $message);
- }
+ /**
+ * Returns an array of logging events, one for each level, sorted ascending
+ * by severitiy.
+ */
+ public static function getAllEvents($message = 'test')
+ {
+ return array(
+ self::getTraceEvent($message),
+ self::getDebugEvent($message),
+ self::getInfoEvent($message),
+ self::getWarnEvent($message),
+ self::getErrorEvent($message),
+ self::getFatalEvent($message),
+ );
+ }
- /**
- * Returns an array of logging events, one for each level, sorted ascending
- * by severitiy.
- */
- public static function getAllEvents($message = 'test') {
- return array(
- self::getTraceEvent($message),
- self::getDebugEvent($message),
- self::getInfoEvent($message),
- self::getWarnEvent($message),
- self::getErrorEvent($message),
- self::getFatalEvent($message),
- );
- }
+ /** Returns an array of all existing levels, sorted ascending by severity. */
+ public static function getAllLevels()
+ {
+ return array(
+ Level::getLevelTrace(),
+ Level::getLevelDebug(),
+ Level::getLevelInfo(),
+ Level::getLevelWarn(),
+ Level::getLevelError(),
+ Level::getLevelFatal(),
+ );
+ }
- /** Returns an array of all existing levels, sorted ascending by severity. */
- public static function getAllLevels() {
- return array(
- Level::getLevelTrace(),
- Level::getLevelDebug(),
- Level::getLevelInfo(),
- Level::getLevelWarn(),
- Level::getLevelError(),
- Level::getLevelFatal(),
- );
- }
+ /** Returns a string representation of a filter decision. */
+ public static function decisionToString($decision)
+ {
+ switch ($decision) {
+ case AbstractFilter::ACCEPT: return 'ACCEPT';
+ case AbstractFilter::NEUTRAL: return 'NEUTRAL';
+ case AbstractFilter::DENY: return 'DENY';
+ }
+ }
- /** Returns a string representation of a filter decision. */
- public static function decisionToString($decision) {
- switch($decision) {
- case AbstractFilter::ACCEPT: return 'ACCEPT';
- case AbstractFilter::NEUTRAL: return 'NEUTRAL';
- case AbstractFilter::DENY: return 'DENY';
- }
- }
+ /** Returns a simple configuration with one echo appender tied to root logger. */
+ public static function getEchoConfig()
+ {
+ return array(
+ 'threshold' => 'ALL',
+ 'rootLogger' => array(
+ 'level' => 'trace',
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'SimpleLayout',
+ ),
+ ),
+ ),
+ );
+ }
- /** Returns a simple configuration with one echo appender tied to root logger. */
- public static function getEchoConfig() {
- return array(
- 'threshold' => 'ALL',
- 'rootLogger' => array(
- 'level' => 'trace',
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'SimpleLayout',
- ),
- ),
- ),
- );
- }
-
- /** Returns a simple configuration with one echo appender using the pattern layout. */
- public static function getEchoPatternConfig($pattern) {
- return array(
- 'threshold' => 'ALL',
- 'rootLogger' => array(
- 'level' => 'trace',
- 'appenders' => array('default'),
- ),
- 'appenders' => array(
- 'default' => array(
- 'class' => 'EchoAppender',
- 'layout' => array(
- 'class' => 'PatternLayout',
- 'params' => array(
- 'conversionPattern' => $pattern
- )
- ),
- ),
- ),
- );
- }
+ /** Returns a simple configuration with one echo appender using the pattern layout. */
+ public static function getEchoPatternConfig($pattern)
+ {
+ return array(
+ 'threshold' => 'ALL',
+ 'rootLogger' => array(
+ 'level' => 'trace',
+ 'appenders' => array('default'),
+ ),
+ 'appenders' => array(
+ 'default' => array(
+ 'class' => 'EchoAppender',
+ 'layout' => array(
+ 'class' => 'PatternLayout',
+ 'params' => array(
+ 'conversionPattern' => $pattern
+ )
+ ),
+ ),
+ ),
+ );
+ }
}
-
-?>
\ No newline at end of file
diff --git a/tests/src/ThrowableInformationTest.php b/tests/src/ThrowableInformationTest.php
index 9d230da..d07c945 100644
--- a/tests/src/ThrowableInformationTest.php
+++ b/tests/src/ThrowableInformationTest.php
@@ -29,30 +29,33 @@
/**
* @group main
*/
-class ThrowableInformationTest extends \PHPUnit_Framework_TestCase {
+class ThrowableInformationTest extends \PHPUnit_Framework_TestCase
+{
+ public function testConstructor()
+ {
+ $ex = new \Exception();
+ $tInfo = new ThrowableInformation($ex);
- public function testConstructor() {
- $ex = new \Exception();
- $tInfo = new ThrowableInformation($ex);
+ $result = $tInfo->getStringRepresentation();
+ $this->assertInternalType('array', $result);
+ }
- $result = $tInfo->getStringRepresentation();
- $this->assertInternalType('array', $result);
- }
+ public function testExceptionChain()
+ {
+ $ex1 = new ThrowableInformationTestException('Message1');
+ $ex2 = new ThrowableInformationTestException('Message2', 0, $ex1);
+ $ex3 = new ThrowableInformationTestException('Message3', 0, $ex2);
- public function testExceptionChain() {
- $ex1 = new ThrowableInformationTestException('Message1');
- $ex2 = new ThrowableInformationTestException('Message2', 0, $ex1);
- $ex3 = new ThrowableInformationTestException('Message3', 0, $ex2);
+ $tInfo = new ThrowableInformation($ex3);
+ $result = $tInfo->getStringRepresentation();
+ $this->assertInternalType('array', $result);
+ }
- $tInfo = new ThrowableInformation($ex3);
- $result = $tInfo->getStringRepresentation();
- $this->assertInternalType('array', $result);
- }
-
- public function testGetThrowable() {
- $ex = new ThrowableInformationTestException('Message1');
- $tInfo = new ThrowableInformation($ex);
- $result = $tInfo->getThrowable();
- $this->assertEquals($ex, $result);
- }
+ public function testGetThrowable()
+ {
+ $ex = new ThrowableInformationTestException('Message1');
+ $tInfo = new ThrowableInformation($ex);
+ $result = $tInfo->getThrowable();
+ $this->assertEquals($ex, $result);
+ }
}