1: <?php
2: /**
3: * Fluent-Logger-PHP
4: *
5: * Copyright (C) 2011 - 2012 Fluent-Logger-PHP Contributors
6: *
7: * Licensed under the Apache License, Version 2.0 (the "License");
8: * you may not use this file except in compliance with the License.
9: * You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: */
19: namespace Fluent\Logger;
20:
21: /**
22: * Console Logger
23: *
24: * Console Logger client outputs readable log message to stderr.
25: *
26: */
27: class ConsoleLogger extends BaseLogger
28: {
29: /* @var resource handle */
30: protected $handle;
31:
32: /**
33: * create Console logger object.
34: *
35: * @return ConsoleLogger
36: */
37: public function __construct()
38: {
39: $this->handle = fopen("php://stderr","w");
40: }
41:
42: /**
43: * fluent-logger compatible API.
44: *
45: * @return FluentLogger created logger object.
46: */
47: public static function open()
48: {
49: $logger = new self();
50: return $logger;
51: }
52:
53: /**
54: * send a message to specified fluentd.
55: *
56: * @param string $tag
57: * @param array $data
58: */
59: public function post($tag ,array $data)
60: {
61: $entity = new Entity($tag,$data);
62: return $this->postImpl($entity);
63: }
64:
65: /**
66: * @param Entity $entity
67: * @return bool
68: */
69: public function post2(Entity $entity)
70: {
71: return $this->postImpl($entity);
72: }
73:
74: /**
75: * @param Entity $entity
76: * @return int
77: */
78: protected function postImpl(Entity $entity)
79: {
80: /*
81: * example ouputs:
82: * 2012-02-26T01:26:20+0900 debug.test {"hello":"world"}
83: */
84: $format = "%s\t%s\t%s\n";
85: return $this->write(sprintf($format,
86: date(\DateTime::ISO8601,$entity->getTime()),
87: $entity->getTag(),
88: json_encode($entity->getData())
89: ));
90: }
91:
92: /**
93: * fwrite proxy method
94: *
95: * @param string $buffer
96: * @return int
97: */
98: protected function write($buffer)
99: {
100: return fwrite($this->handle, $buffer);
101: }
102: }
103: