FluentdFormatter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php declare(strict_types=1);
  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. /**
  12. * Class FluentdFormatter
  13. *
  14. * Serializes a log message to Fluentd unix socket protocol
  15. *
  16. * Fluentd config:
  17. *
  18. * <source>
  19. * type unix
  20. * path /var/run/td-agent/td-agent.sock
  21. * </source>
  22. *
  23. * Monolog setup:
  24. *
  25. * $logger = new Monolog\Logger('fluent.tag');
  26. * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock');
  27. * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter());
  28. * $logger->pushHandler($fluentHandler);
  29. *
  30. * @author Andrius Putna <fordnox@gmail.com>
  31. */
  32. class FluentdFormatter implements FormatterInterface
  33. {
  34. /**
  35. * @var bool $levelTag should message level be a part of the fluentd tag
  36. */
  37. protected $levelTag = false;
  38. public function __construct($levelTag = false)
  39. {
  40. if (!function_exists('json_encode')) {
  41. throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter');
  42. }
  43. $this->levelTag = (bool) $levelTag;
  44. }
  45. public function isUsingLevelsInTag()
  46. {
  47. return $this->levelTag;
  48. }
  49. public function format(array $record)
  50. {
  51. $tag = $record['channel'];
  52. if ($this->levelTag) {
  53. $tag .= '.' . strtolower($record['level_name']);
  54. }
  55. $message = [
  56. 'message' => $record['message'],
  57. 'extra' => $record['extra'],
  58. ];
  59. if (!$this->levelTag) {
  60. $message['level'] = $record['level'];
  61. $message['level_name'] = $record['level_name'];
  62. }
  63. return json_encode([$tag, $record['datetime']->getTimestamp(), $message]);
  64. }
  65. public function formatBatch(array $records)
  66. {
  67. $message = '';
  68. foreach ($records as $record) {
  69. $message .= $this->format($record);
  70. }
  71. return $message;
  72. }
  73. }