SyslogTarget.php 1.54 KB
Newer Older
miramir committed
1 2 3 4 5 6 7 8 9 10 11
<?php
/**
 * @link http://www.yiiframework.com/
 * @license http://www.yiiframework.com/license/
 */

namespace yii\log;

use Yii;

/**
12
 * SyslogTarget writes log to syslog.
miramir committed
13 14 15 16 17 18 19
 *
 * @author miramir <gmiramir@gmail.com>
 * @since 2.0
 */
class SyslogTarget extends Target
{
    /**
20
     * @var string syslog identity
miramir committed
21 22
     */
    public $identity;
23

miramir committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    /**
     * @var integer syslog facility.
     */
    public $facility = LOG_SYSLOG;

    /**
     * @var array syslog levels
     */
    private $syslogLevels = [
        Logger::LEVEL_TRACE => LOG_DEBUG,
        Logger::LEVEL_PROFILE_BEGIN => LOG_DEBUG,
        Logger::LEVEL_PROFILE_END => LOG_DEBUG,
        Logger::LEVEL_INFO => LOG_INFO,
        Logger::LEVEL_WARNING => LOG_WARNING,
        Logger::LEVEL_ERROR => LOG_ERR,
39
    ];
miramir committed
40 41

    /**
42
     * Writes log messages to syslog
miramir committed
43 44 45 46
     */
    public function export()
    {
        openlog($this->identity, LOG_ODELAY | LOG_PID, $this->facility);
47
        foreach ($this->messages as $message) {
miramir committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            syslog($this->syslogLevels[$message[1]], $this->formatMessage($message));
        }
        closelog();
    }

    /**
     * @inheritdoc
     */
    public function formatMessage($message)
    {
        list($text, $level, $category, $timestamp) = $message;
        $level = Logger::getLevelName($level);
        if (!is_string($text)) {
            $text = var_export($text, true);
        }

        $prefix = $this->prefix ? call_user_func($this->prefix, $message) : $this->getMessagePrefix($message);

        return "{$prefix}[$level][$category] $text";
    }
}