LineFormatter.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Formatter;
  11. use Monolog\Logger;
  12. /**
  13. * Formats incoming messages into a one-line string
  14. *
  15. * This is especially useful for logging to files
  16. *
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. class LineFormatter implements FormatterInterface
  20. {
  21. const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %extra%\n";
  22. const SIMPLE_DATE = "Y-m-d H:i:s";
  23. protected $format;
  24. protected $dateFormat;
  25. public function __construct($format = null, $dateFormat = null)
  26. {
  27. $this->format = $format ?: self::SIMPLE_FORMAT;
  28. $this->dateFormat = $dateFormat ?: self::SIMPLE_DATE;
  29. }
  30. public function format($message)
  31. {
  32. $vars = $message;
  33. $vars['datetime'] = $vars['datetime']->format($this->dateFormat);
  34. $output = $this->format;
  35. foreach ($vars as $var => $val) {
  36. if (is_array($val)) {
  37. $strval = array();
  38. foreach ($val as $subvar => $subval) {
  39. $strval[] = $subvar.': '.$subval;
  40. }
  41. $replacement = $strval ? $var.'('.implode(', ', $strval).')' : '';
  42. $output = str_replace('%'.$var.'%', $replacement, $output);
  43. } else {
  44. $output = str_replace('%'.$var.'%', $val, $output);
  45. }
  46. }
  47. foreach ($vars['extra'] as $var => $val) {
  48. $output = str_replace('%extra.'.$var.'%', $val, $output);
  49. }
  50. $message['message'] = $output;
  51. return $message;
  52. }
  53. }