Skip to content

Commit

Permalink
Tweaked the formatting of complex data in the LineFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
stof committed May 31, 2011
1 parent 53c9b20 commit a8d4fc4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
6 changes: 3 additions & 3 deletions src/Monolog/Formatter/FormatterInterface.php
Expand Up @@ -22,15 +22,15 @@ interface FormatterInterface
* Formats a log record.
*
* @param array $record A record to format
* @return string The formatted message
* @return mixed The formatted record
*/
function format(array $record);

/**
* Formats a set of log records.
*
* @param array $record A record to format
* @return string The formatted batch message
* @param array $records A set of records to format
* @return mixed The formatted set of records
*/
function formatBatch(array $records);
}
42 changes: 27 additions & 15 deletions src/Monolog/Formatter/LineFormatter.php
Expand Up @@ -19,6 +19,7 @@
* This is especially useful for logging to files
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Christophe Coevoet <stof@notk.org>
*/
class LineFormatter implements FormatterInterface
{
Expand Down Expand Up @@ -47,20 +48,12 @@ public function format(array $record)
$vars['datetime'] = $vars['datetime']->format($this->dateFormat);

$output = $this->format;
foreach ($vars as $var => $val) {
if (is_array($val)) {
$strval = array();
foreach ($val as $subvar => $subval) {
$strval[] = $subvar.': '.$this->convertToString($subval);
}
$replacement = $strval ? $var.'('.implode(', ', $strval).')' : '';
$output = str_replace('%'.$var.'%', $replacement, $output);
} else {
$output = str_replace('%'.$var.'%', $this->convertToString($val), $output);
}
}
foreach ($vars['extra'] as $var => $val) {
$output = str_replace('%extra.'.$var.'%', $this->convertToString($val), $output);
unset($vars['extra'][$var]);
}
foreach ($vars as $var => $val) {
$output = str_replace('%'.$var.'%', $this->convertToString($val), $output);
}

return $output;
Expand All @@ -76,12 +69,31 @@ public function formatBatch(array $records)
return $message;
}

private function convertToString($data)
protected function convertToString($data)
{
if (is_scalar($data) || (is_object($data) && method_exists($data, '__toString'))) {
if (null === $data || is_scalar($data)) {
return (string) $data;
}

return serialize($data);
return json_encode($this->normalize($data));
}

protected function normalize($data)
{
if (null === $data || is_scalar($data)) {
return $data;
}

if (is_array($data) || $data instanceof \Traversable) {
$normalized = array();

foreach ($data as $key => $value) {
$normalized[$key] = $this->normalize($value);
}

return $normalized;
}

return sprintf("[object] (%s: %s)", get_class($data), json_decode($data));
}
}

0 comments on commit a8d4fc4

Please sign in to comment.