3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Log\Formatter
;
14 use Zend\Stdlib\ErrorHandler
;
16 class Base
implements FormatterInterface
19 * Format specifier for DateTime objects in event data (default: ISO 8601)
21 * @see http://php.net/manual/en/function.date.php
24 protected $dateTimeFormat = self
::DEFAULT_DATETIME_FORMAT
;
29 * @see http://php.net/manual/en/function.date.php
30 * @param null|string|array|Traversable $dateTimeFormat Format for DateTime objects
32 public function __construct($dateTimeFormat = null)
34 if ($dateTimeFormat instanceof Traversable
) {
35 $dateTimeFormat = iterator_to_array($dateTimeFormat);
38 if (is_array($dateTimeFormat)) {
39 $dateTimeFormat = isset($dateTimeFormat['dateTimeFormat'])?
$dateTimeFormat['dateTimeFormat'] : null;
42 if (null !== $dateTimeFormat) {
43 $this->dateTimeFormat
= $dateTimeFormat;
48 * Formats data to be written by the writer.
50 * @param array $event event data
53 public function format($event)
55 foreach ($event as $key => $value) {
56 // Keep extra as an array
57 if ('extra' === $key) {
58 $event[$key] = self
::format($value);
60 $event[$key] = $this->normalize($value);
68 * Normalize all non-scalar data types (except null) in a string value
73 protected function normalize($value)
75 if (is_scalar($value) ||
null === $value) {
79 // better readable JSON
81 if ($jsonFlags === null) {
83 $jsonFlags |
= defined('JSON_UNESCAPED_SLASHES') ? JSON_UNESCAPED_SLASHES
: 0;
84 $jsonFlags |
= defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE
: 0;
87 ErrorHandler
::start();
88 if ($value instanceof DateTime
) {
89 $value = $value->format($this->getDateTimeFormat());
90 } elseif ($value instanceof Traversable
) {
91 $value = json_encode(iterator_to_array($value), $jsonFlags);
92 } elseif (is_array($value)) {
93 $value = json_encode($value, $jsonFlags);
94 } elseif (is_object($value) && !method_exists($value, '__toString')) {
95 $value = sprintf('object(%s) %s', get_class($value), json_encode($value));
96 } elseif (is_resource($value)) {
97 $value = sprintf('resource(%s)', get_resource_type($value));
98 } elseif (!is_object($value)) {
99 $value = gettype($value);
101 ErrorHandler
::stop();
103 return (string) $value;
109 public function getDateTimeFormat()
111 return $this->dateTimeFormat
;
117 public function setDateTimeFormat($dateTimeFormat)
119 $this->dateTimeFormat
= (string) $dateTimeFormat;