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

namespace yii\log;

use Yii;

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

miramir committed
25 26 27 28 29 30 31 32
    /**
     * @var integer syslog facility.
     */
    public $facility = LOG_SYSLOG;

    /**
     * @var array syslog levels
     */
33
    private $_syslogLevels = [
miramir committed
34 35 36 37 38 39
        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,
40
    ];
miramir committed
41 42

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