scratch – Blame information for rev 122
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
120 | office | 1 | <?php |
2 | |||
3 | /* |
||
4 | * This file is part of the Monolog package. |
||
5 | * |
||
6 | * (c) Jordi Boggiano <j.boggiano@seld.be> |
||
7 | * |
||
8 | * For the full copyright and license information, please view the LICENSE |
||
9 | * file that was distributed with this source code. |
||
10 | */ |
||
11 | |||
12 | namespace Monolog\Formatter; |
||
13 | |||
14 | /** |
||
15 | * Class FluentdFormatter |
||
16 | * |
||
17 | * Serializes a log message to Fluentd unix socket protocol |
||
18 | * |
||
19 | * Fluentd config: |
||
20 | * |
||
21 | * <source> |
||
22 | * type unix |
||
23 | * path /var/run/td-agent/td-agent.sock |
||
24 | * </source> |
||
25 | * |
||
26 | * Monolog setup: |
||
27 | * |
||
28 | * $logger = new Monolog\Logger('fluent.tag'); |
||
29 | * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock'); |
||
30 | * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter()); |
||
31 | * $logger->pushHandler($fluentHandler); |
||
32 | * |
||
33 | * @author Andrius Putna <fordnox@gmail.com> |
||
34 | */ |
||
35 | class FluentdFormatter implements FormatterInterface |
||
36 | { |
||
37 | /** |
||
38 | * @var bool $levelTag should message level be a part of the fluentd tag |
||
39 | */ |
||
40 | protected $levelTag = false; |
||
41 | |||
42 | public function __construct($levelTag = false) |
||
43 | { |
||
44 | if (!function_exists('json_encode')) { |
||
45 | throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter'); |
||
46 | } |
||
47 | |||
48 | $this->levelTag = (bool) $levelTag; |
||
49 | } |
||
50 | |||
51 | public function isUsingLevelsInTag() |
||
52 | { |
||
53 | return $this->levelTag; |
||
54 | } |
||
55 | |||
56 | public function format(array $record) |
||
57 | { |
||
58 | $tag = $record['channel']; |
||
59 | if ($this->levelTag) { |
||
60 | $tag .= '.' . strtolower($record['level_name']); |
||
61 | } |
||
62 | |||
63 | $message = array( |
||
64 | 'message' => $record['message'], |
||
65 | 'extra' => $record['extra'], |
||
66 | ); |
||
67 | |||
68 | if (!$this->levelTag) { |
||
69 | $message['level'] = $record['level']; |
||
70 | $message['level_name'] = $record['level_name']; |
||
71 | } |
||
72 | |||
73 | return json_encode(array($tag, $record['datetime']->getTimestamp(), $message)); |
||
74 | } |
||
75 | |||
76 | public function formatBatch(array $records) |
||
77 | { |
||
78 | $message = ''; |
||
79 | foreach ($records as $record) { |
||
80 | $message .= $this->format($record); |
||
81 | } |
||
82 | |||
83 | return $message; |
||
84 | } |
||
85 | } |