4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Formatter;
15 * Formats a record for use with the MongoDBHandler.
17 * @author Florian Plattner <me@florianplattner.de>
19 class MongoDBFormatter implements FormatterInterface
21 private $exceptionTraceAsString;
22 private $maxNestingLevel;
25 * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2
26 * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings
28 public function __construct($maxNestingLevel = 3, $exceptionTraceAsString = true)
30 $this->maxNestingLevel = max($maxNestingLevel, 0);
31 $this->exceptionTraceAsString = (bool) $exceptionTraceAsString;
37 public function format(array $record)
39 return $this->formatArray($record);
45 public function formatBatch(array $records)
47 foreach ($records as $key => $record) {
48 $records[$key] = $this->format($record);
54 protected function formatArray(array $record, $nestingLevel = 0)
56 if ($this->maxNestingLevel == 0 || $nestingLevel <= $this->maxNestingLevel) {
57 foreach ($record as $name => $value) {
58 if ($value instanceof \DateTime) {
59 $record[$name] = $this->formatDate($value, $nestingLevel + 1);
60 } elseif ($value instanceof \Exception) {
61 $record[$name] = $this->formatException($value, $nestingLevel + 1);
62 } elseif (is_array($value)) {
63 $record[$name] = $this->formatArray($value, $nestingLevel + 1);
64 } elseif (is_object($value)) {
65 $record[$name] = $this->formatObject($value, $nestingLevel + 1);
75 protected function formatObject($value, $nestingLevel)
77 $objectVars = get_object_vars($value);
78 $objectVars['class'] = get_class($value);
80 return $this->formatArray($objectVars, $nestingLevel);
83 protected function formatException(\Exception $exception, $nestingLevel)
85 $formattedException = array(
86 'class' => get_class($exception),
87 'message' => $exception->getMessage(),
88 'code' => $exception->getCode(),
89 'file' => $exception->getFile() . ':' . $exception->getLine(),
92 if ($this->exceptionTraceAsString === true) {
93 $formattedException['trace'] = $exception->getTraceAsString();
95 $formattedException['trace'] = $exception->getTrace();
98 return $this->formatArray($formattedException, $nestingLevel);
101 protected function formatDate(\DateTime $value, $nestingLevel)
103 return new \MongoDate($value->getTimestamp());