1: <?php
2: /**
3: * Horde Log package
4: *
5: * @author Mike Naberezny <mike@maintainable.com>
6: * @author Chuck Hagenbuch <chuck@horde.org>
7: * @category Horde
8: * @license http://www.horde.org/licenses/bsd BSD
9: * @package Log
10: * @subpackage Handlers
11: */
12:
13: /**
14: * @author Mike Naberezny <mike@maintainable.com>
15: * @author Chuck Hagenbuch <chuck@horde.org>
16: * @category Horde
17: * @license http://www.horde.org/licenses/bsd BSD
18: * @package Log
19: * @subpackage Handlers
20: */
21: class Horde_Log_Handler_Syslog extends Horde_Log_Handler_Base
22: {
23: /**
24: * Options to be set by setOption().
25: * Sets openlog and syslog options.
26: *
27: * @var array
28: */
29: protected $_options = array(
30: 'defaultPriority' => LOG_ERR,
31: 'facility' => LOG_USER,
32: 'ident' => false,
33: 'openlogOptions' => false
34: );
35:
36: /**
37: * Last ident set by a syslog-handler instance.
38: *
39: * @var string
40: */
41: protected $_lastIdent;
42:
43: /**
44: * Last facility name set by a syslog-handler instance.
45: *
46: * @var string
47: */
48: protected $_lastFacility;
49:
50: /**
51: * Map of log levels to syslog priorities.
52: *
53: * @var array
54: */
55: protected $_priorities = array(
56: Horde_Log::EMERG => LOG_EMERG,
57: Horde_Log::ALERT => LOG_ALERT,
58: Horde_Log::CRIT => LOG_CRIT,
59: Horde_Log::ERR => LOG_ERR,
60: Horde_Log::WARN => LOG_WARNING,
61: Horde_Log::NOTICE => LOG_NOTICE,
62: Horde_Log::INFO => LOG_INFO,
63: Horde_Log::DEBUG => LOG_DEBUG,
64: );
65:
66: /**
67: * Write a message to the log.
68: *
69: * @param array $event Log event.
70: *
71: * @return boolean True.
72: * @throws Horde_Log_Exception
73: */
74: public function write($event)
75: {
76: if (($this->_options['ident'] !== $this->_lastIdent) ||
77: ($this->_options['facility'] !== $this->_lastFacility)) {
78: $this->_initializeSyslog();
79: }
80:
81: $priority = $this->_toSyslog($event['level']);
82: if (!syslog($priority, $event['message'])) {
83: throw new Horde_Log_Exception('Unable to log message');
84: }
85:
86: return true;
87: }
88:
89: /**
90: * Translate a log level to a syslog LOG_* priority.
91: *
92: * @param integer $level Log level.
93: *
94: * @return integer A LOG_* constant.
95: */
96: protected function _toSyslog($level)
97: {
98: return isset($this->_priorities[$level])
99: ? $this->_priorities[$level]
100: : $this->_options['defaultPriority'];
101: }
102:
103: /**
104: * Initialize syslog / set ident and facility.
105: *
106: * @param string $ident Ident.
107: * @param string $facility Syslog facility.
108: *
109: * @throws Horde_Log_Exception
110: */
111: protected function _initializeSyslog()
112: {
113: $this->_lastIdent = $this->_options['ident'];
114: $this->_lastFacility = $this->_options['facility'];
115:
116: if (!openlog($this->_options['ident'], $this->_options['openlogOptions'], $this->_options['facility'])) {
117: throw new Horde_Log_Exception('Unable to open syslog');
118: }
119: }
120:
121: }
122: