Dispatcher.php 6.24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\log;

use Yii;
use yii\base\Component;
12
use yii\base\ErrorHandler;
13 14 15 16

/**
 * Dispatcher manages a set of [[Target|log targets]].
 *
17
 * Dispatcher implements the [[dispatch()]]-method that forwards the log messages from a [[Logger]] to
18 19
 * the registered log [[targets]].
 *
20
 * An instance of Dispatcher is registered as a core application component and can be accessed using `Yii::$app->log`.
21 22 23
 *
 * You may configure the targets in application configuration, like the following:
 *
24
 * ```php
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 * [
 *     'components' => [
 *         'log' => [
 *             'targets' => [
 *                 'file' => [
 *                     'class' => 'yii\log\FileTarget',
 *                     'levels' => ['trace', 'info'],
 *                     'categories' => ['yii\*'],
 *                 ],
 *                 'email' => [
 *                     'class' => 'yii\log\EmailTarget',
 *                     'levels' => ['error', 'warning'],
 *                     'message' => [
 *                         'to' => 'admin@example.com',
 *                     ],
 *                 ],
 *             ],
 *         ],
 *     ],
 * ]
45
 * ```
46
 *
47
 * Each log target can have a name and can be referenced via the [[targets]] property as follows:
48
 *
49
 * ```php
50
 * Yii::$app->log->targets['file']->enabled = false;
51
 * ```
52
 *
53 54 55 56 57 58
 * @property integer $flushInterval How many messages should be logged before they are sent to targets. This
 * method returns the value of [[Logger::flushInterval]].
 * @property Logger $logger The logger. If not set, [[\Yii::getLogger()]] will be used.
 * @property integer $traceLevel How many application call stacks should be logged together with each message.
 * This method returns the value of [[Logger::traceLevel]]. Defaults to 0.
 *
59 60 61 62 63 64 65 66 67 68
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Dispatcher extends Component
{
    /**
     * @var array|Target[] the log targets. Each array element represents a single [[Target|log target]] instance
     * or the configuration for creating the log target instance.
     */
    public $targets = [];
69

Qiang Xue committed
70
    /**
71
     * @var Logger the logger.
Qiang Xue committed
72
     */
73 74
    private $_logger;

75

76 77 78 79 80
    /**
     * @inheritdoc
     */
    public function __construct($config = [])
    {
81
        // ensure logger gets set before any other config option
82
        if (isset($config['logger'])) {
83
            $this->setLogger($config['logger']);
84 85 86 87 88 89 90 91
            unset($config['logger']);
        }
        // connect logger and dispatcher
        $this->getLogger();

        parent::__construct($config);
    }

92
    /**
93
     * @inheritdoc
94 95 96 97 98 99 100 101 102 103
     */
    public function init()
    {
        parent::init();

        foreach ($this->targets as $name => $target) {
            if (!$target instanceof Target) {
                $this->targets[$name] = Yii::createObject($target);
            }
        }
104 105 106 107 108 109 110 111 112 113 114
    }

    /**
     * Gets the connected logger.
     * If not set, [[\Yii::getLogger()]] will be used.
     * @property Logger the logger. If not set, [[\Yii::getLogger()]] will be used.
     * @return Logger the logger.
     */
    public function getLogger()
    {
        if ($this->_logger === null) {
115
            $this->setLogger(Yii::getLogger());
Qiang Xue committed
116
        }
117 118 119 120 121 122 123 124 125 126
        return $this->_logger;
    }

    /**
     * Sets the connected logger.
     * @param Logger $value the logger.
     */
    public function setLogger($value)
    {
        $this->_logger = $value;
127
        $this->_logger->dispatcher = $this;
128 129 130 131 132 133 134 135
    }

    /**
     * @return integer how many application call stacks should be logged together with each message.
     * This method returns the value of [[Logger::traceLevel]]. Defaults to 0.
     */
    public function getTraceLevel()
    {
136
        return $this->getLogger()->traceLevel;
137 138 139 140 141 142 143 144 145 146
    }

    /**
     * @param integer $value how many application call stacks should be logged together with each message.
     * This method will set the value of [[Logger::traceLevel]]. If the value is greater than 0,
     * at most that number of call stacks will be logged. Note that only application call stacks are counted.
     * Defaults to 0.
     */
    public function setTraceLevel($value)
    {
147
        $this->getLogger()->traceLevel = $value;
148 149 150 151 152 153 154 155
    }

    /**
     * @return integer how many messages should be logged before they are sent to targets.
     * This method returns the value of [[Logger::flushInterval]].
     */
    public function getFlushInterval()
    {
156
        return $this->getLogger()->flushInterval;
157 158 159 160 161 162 163 164 165 166 167 168
    }

    /**
     * @param integer $value how many messages should be logged before they are sent to targets.
     * This method will set the value of [[Logger::flushInterval]].
     * Defaults to 1000, meaning the [[Logger::flush()]] method will be invoked once every 1000 messages logged.
     * Set this property to be 0 if you don't want to flush messages until the application terminates.
     * This property mainly affects how much memory will be taken by the logged messages.
     * A smaller value means less memory, but will increase the execution time due to the overhead of [[Logger::flush()]].
     */
    public function setFlushInterval($value)
    {
169
        $this->getLogger()->flushInterval = $value;
170 171 172 173 174 175 176 177 178
    }

    /**
     * Dispatches the logged messages to [[targets]].
     * @param array $messages the logged messages
     * @param boolean $final whether this method is called at the end of the current application
     */
    public function dispatch($messages, $final)
    {
179
        $targetErrors = [];
180 181
        foreach ($this->targets as $target) {
            if ($target->enabled) {
182 183 184 185 186
                try {
                    $target->collect($messages, $final);
                } catch (\Exception $e) {
                    $target->enabled = false;
                    $targetErrors[] = [
187
                        'Unable to send log via ' . get_class($target) . ': ' . ErrorHandler::convertExceptionToString($e),
188 189 190 191 192 193
                        Logger::LEVEL_WARNING,
                        __METHOD__,
                        microtime(true),
                        [],
                    ];
                }
194 195
            }
        }
196 197 198 199

        if (!empty($targetErrors)) {
            $this->dispatch($targetErrors, true);
        }
200 201
    }
}