1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakefoundation.org CakePHP(tm) Project
12: * @since 2.2.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Log\Engine;
16:
17: use Cake\Console\ConsoleOutput;
18: use InvalidArgumentException;
19:
20: /**
21: * Console logging. Writes logs to console output.
22: */
23: class ConsoleLog extends BaseLog
24: {
25: /**
26: * Default config for this class
27: *
28: * @var array
29: */
30: protected $_defaultConfig = [
31: 'stream' => 'php://stderr',
32: 'levels' => null,
33: 'scopes' => [],
34: 'outputAs' => null,
35: ];
36:
37: /**
38: * Output stream
39: *
40: * @var \Cake\Console\ConsoleOutput
41: */
42: protected $_output;
43:
44: /**
45: * Constructs a new Console Logger.
46: *
47: * Config
48: *
49: * - `levels` string or array, levels the engine is interested in
50: * - `scopes` string or array, scopes the engine is interested in
51: * - `stream` the path to save logs on.
52: * - `outputAs` integer or ConsoleOutput::[RAW|PLAIN|COLOR]
53: *
54: * @param array $config Options for the FileLog, see above.
55: * @throws \InvalidArgumentException
56: */
57: public function __construct(array $config = [])
58: {
59: parent::__construct($config);
60:
61: $config = $this->_config;
62: if ($config['stream'] instanceof ConsoleOutput) {
63: $this->_output = $config['stream'];
64: } elseif (is_string($config['stream'])) {
65: $this->_output = new ConsoleOutput($config['stream']);
66: } else {
67: throw new InvalidArgumentException('`stream` not a ConsoleOutput nor string');
68: }
69:
70: if (isset($config['outputAs'])) {
71: $this->_output->setOutputAs($config['outputAs']);
72: }
73: }
74:
75: /**
76: * Implements writing to console.
77: *
78: * @param string $level The severity level of log you are making.
79: * @param string $message The message you want to log.
80: * @param array $context Additional information about the logged message
81: * @return bool success of write.
82: */
83: public function log($level, $message, array $context = [])
84: {
85: $message = $this->_format($message, $context);
86: $output = date('Y-m-d H:i:s') . ' ' . ucfirst($level) . ': ' . $message;
87:
88: return (bool)$this->_output->write(sprintf('<%s>%s</%s>', $level, $output, $level));
89: }
90: }
91: