4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Handler;
14 use Monolog\Formatter\LineFormatter;
17 * Handler sending logs to browser's javascript console with no browser extension required
19 * @author Olivier Poitrey <rs@dailymotion.com>
21 class BrowserConsoleHandler extends AbstractProcessingHandler
23 protected static $initialized = false;
24 protected static $records = array();
29 * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format.
31 * Example of formatted string:
33 * You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white}
35 protected function getDefaultFormatter()
37 return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%');
43 protected function write(array $record)
46 self::$records[] = $record;
48 // Register shutdown handler if not already done
49 if (!self::$initialized) {
50 self::$initialized = true;
51 $this->registerShutdownFunction();
56 * Convert records to javascript console commands and send it to the browser.
57 * This method is automatically called on PHP shutdown if output is HTML or Javascript.
59 public static function send()
61 $format = self::getResponseFormat();
62 if ($format === 'unknown') {
66 if (count(self::$records)) {
67 if ($format === 'html') {
68 self::writeOutput('<script>' . self::generateScript() . '</script>');
69 } elseif ($format === 'js') {
70 self::writeOutput(self::generateScript());
77 * Forget all logged records
79 public static function reset()
81 self::$records = array();
85 * Wrapper for register_shutdown_function to allow overriding
87 protected function registerShutdownFunction()
89 if (PHP_SAPI !== 'cli') {
90 register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send'));
95 * Wrapper for echo to allow overriding
99 protected static function writeOutput($str)
105 * Checks the format of the response
107 * If Content-Type is set to application/javascript or text/javascript -> js
108 * If Content-Type is set to text/html, or is unset -> html
109 * If Content-Type is anything else -> unknown
111 * @return string One of 'js', 'html' or 'unknown'
113 protected static function getResponseFormat()
115 // Check content type
116 foreach (headers_list() as $header) {
117 if (stripos($header, 'content-type:') === 0) {
118 // This handler only works with HTML and javascript outputs
119 // text/javascript is obsolete in favour of application/javascript, but still used
120 if (stripos($header, 'application/javascript') !== false || stripos($header, 'text/javascript') !== false) {
123 if (stripos($header, 'text/html') === false) {
133 private static function generateScript()
136 foreach (self::$records as $record) {
137 $context = self::dump('Context', $record['context']);
138 $extra = self::dump('Extra', $record['extra']);
140 if (empty($context) && empty($extra)) {
141 $script[] = self::call_array('log', self::handleStyles($record['formatted']));
143 $script = array_merge($script,
144 array(self::call_array('groupCollapsed', self::handleStyles($record['formatted']))),
147 array(self::call('groupEnd'))
152 return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);";
155 private static function handleStyles($formatted)
157 $args = array(self::quote('font-weight: normal'));
158 $format = '%c' . $formatted;
159 preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
161 foreach (array_reverse($matches) as $match) {
162 $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0]));
163 $args[] = '"font-weight: normal"';
166 $format = substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . substr($format, $pos + strlen($match[0][0]));
169 array_unshift($args, self::quote($format));
174 private static function handleCustomStyles($style, $string)
176 static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey');
177 static $labels = array();
179 return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) {
180 if (trim($m[1]) === 'autolabel') {
181 // Format the string as a label with consistent auto assigned background color
182 if (!isset($labels[$string])) {
183 $labels[$string] = $colors[count($labels) % count($colors)];
185 $color = $labels[$string];
187 return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px";
194 private static function dump($title, array $dict)
197 $dict = array_filter($dict);
201 $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title));
202 foreach ($dict as $key => $value) {
203 $value = json_encode($value);
205 $value = self::quote('');
207 $script[] = self::call('log', self::quote('%s: %o'), self::quote($key), $value);
213 private static function quote($arg)
215 return '"' . addcslashes($arg, "\"\n\\") . '"';
218 private static function call()
220 $args = func_get_args();
221 $method = array_shift($args);
223 return self::call_array($method, $args);
226 private static function call_array($method, array $args)
228 return 'c.' . $method . '(' . implode(', ', $args) . ');';