MonologFormatterJsonFormatter

Encodes whatever record data is passed to it as json.

Defined (1)

The class is defined in the following location(s).

/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php  
  1. class JsonFormatter implements FormatterInterface 
  2. const BATCH_MODE_JSON = 1; 
  3. const BATCH_MODE_NEWLINES = 2; 
  4.  
  5. protected $batchMode; 
  6. protected $appendNewline; 
  7.  
  8. /** 
  9. * @param int $batchMode 
  10. */ 
  11. public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true) 
  12. $this->batchMode = $batchMode; 
  13. $this->appendNewline = $appendNewline; 
  14.  
  15. /** 
  16. * The batch mode option configures the formatting style for 
  17. * multiple records. By default, multiple records will be 
  18. * formatted as a JSON-encoded array. However, for 
  19. * compatibility with some API endpoints, alternative styles 
  20. * are available. 
  21. * @return int 
  22. */ 
  23. public function getBatchMode() 
  24. return $this->batchMode; 
  25.  
  26. /** 
  27. * True if newlines are appended to every formatted record 
  28. * @return bool 
  29. */ 
  30. public function isAppendingNewlines() 
  31. return $this->appendNewline; 
  32.  
  33. /** 
  34. * {@inheritdoc} 
  35. */ 
  36. public function format(array $record) 
  37. return json_encode($record) . ($this->appendNewline ? "\n" : ''); 
  38.  
  39. /** 
  40. * {@inheritdoc} 
  41. */ 
  42. public function formatBatch(array $records) 
  43. switch ($this->batchMode) { 
  44. case static::BATCH_MODE_NEWLINES: 
  45. return $this->formatBatchNewlines($records); 
  46.  
  47. case static::BATCH_MODE_JSON: 
  48. default: 
  49. return $this->formatBatchJson($records); 
  50.  
  51. /** 
  52. * Return a JSON-encoded array of records. 
  53. * @param array $records 
  54. * @return string 
  55. */ 
  56. protected function formatBatchJson(array $records) 
  57. return json_encode($records); 
  58.  
  59. /** 
  60. * Use new lines to separate records instead of a 
  61. * JSON-encoded array. 
  62. * @param array $records 
  63. * @return string 
  64. */ 
  65. protected function formatBatchNewlines(array $records) 
  66. $instance = $this; 
  67.  
  68. $oldNewline = $this->appendNewline; 
  69. $this->appendNewline = false; 
  70. array_walk($records, function (&$value, $key) use ($instance) { 
  71. $value = $instance->format($value); 
  72. }); 
  73. $this->appendNewline = $oldNewline; 
  74.  
  75. return implode("\n", $records);