PageRenderTime 465ms CodeModel.GetById 281ms app.highlight 7ms RepoModel.GetById 174ms app.codeStats 0ms

/libs/pear/Log/file.php

https://bitbucket.org/davidmpaz/ezpdo
PHP | 267 lines | 104 code | 37 blank | 126 comment | 17 complexity | 10c26ec06659e2cdfbe1eb21e109fe48 MD5 | raw file
  1<?php
  2// $Id: file.php 212 2005-04-18 19:38:02Z nauhygon $
  3
  4/**
  5 * The Log_file class is a concrete implementation of the Log abstract
  6 * class that logs messages to a text file.
  7 *
  8 * @author  Jon Parise <jon@php.net>
  9 * @author  Roman Neuhauser <neuhauser@bellavista.cz>
 10 * @version $Revision: 212 $
 11 * @package Log
 12 */
 13//class Log_file extends Log
 14class epLib_Log_file extends epLib_Log
 15{
 16    /**
 17     * String containing the name of the log file.
 18     * @var string
 19     * @access private
 20     */
 21    var $_filename = 'php.log';
 22
 23    /**
 24     * Handle to the log file.
 25     * @var resource
 26     * @access private
 27     */
 28    var $_fp = false;
 29
 30    /**
 31     * Should new log entries be append to an existing log file, or should the
 32     * a new log file overwrite an existing one?
 33     * @var boolean
 34     * @access private
 35     */
 36    var $_append = true;
 37
 38    /**
 39     * Integer (in octal) containing the log file's permissions mode.
 40     * @var integer
 41     */
 42    var $_mode = 0644;
 43
 44    /**
 45     * String containing the format of a log line.
 46     * @var string
 47     * @access private
 48     */
 49    var $_lineFormat = '%1$s %2$s [%3$s] %4$s';
 50
 51    /**
 52     * String containing the timestamp format.  It will be passed directly to
 53     * strftime().  Note that the timestamp string will generated using the
 54     * current locale.
 55     * @var string
 56     * @access private
 57     */
 58    var $_timeFormat = '%b %d %H:%M:%S';
 59
 60    /**
 61     * Hash that maps canonical format keys to position arguments for the
 62     * "line format" string.
 63     * @var array
 64     * @access private
 65     */
 66    var $_formatMap = array('%{timestamp}'  => '%1$s',
 67                            '%{ident}'      => '%2$s',
 68                            '%{priority}'   => '%3$s',
 69                            '%{message}'    => '%4$s',
 70                            '%\{'           => '%%{');
 71
 72    /**
 73     * String containing the end-on-line character sequence.
 74     * @var string
 75     * @access private
 76     */
 77    var $_eol = "\n";
 78
 79    /**
 80     * Constructs a new Log_file object.
 81     *
 82     * @param string $name     Ignored.
 83     * @param string $ident    The identity string.
 84     * @param array  $conf     The configuration array.
 85     * @param array  $maxLevel Maximum priority level at which to log.
 86     * @access public
 87     */
 88    function epLib_Log_file($name, $ident = '', $conf = array(),
 89                      $maxLevel = PEAR_LOG_DEBUG)
 90    //function Log_file($name, $ident = '', $conf = array(),
 91    //                  $maxLevel = PEAR_LOG_DEBUG)
 92    {
 93        $this->_id = md5(microtime());
 94        $this->_filename = $name;
 95        $this->_ident = $ident;
 96        //$this->_mask = Log::UPTO($maxLevel);
 97        $this->_mask = epLib_Log::UPTO($maxLevel);
 98
 99        if (isset($conf['append'])) {
100            $this->_append = $conf['append'];
101        }
102
103        if (!empty($conf['mode'])) {
104            $this->_mode = $conf['mode'];
105        }
106
107        if (!empty($conf['lineFormat'])) {
108            $this->_lineFormat = str_replace(array_keys($this->_formatMap),
109                                             array_values($this->_formatMap),
110                                             $conf['lineFormat']);
111        }
112
113        if (!empty($conf['timeFormat'])) {
114            $this->_timeFormat = $conf['timeFormat'];
115        }
116
117        if (!empty($conf['eol'])) {
118            $this->_eol = $conf['eol'];
119        } else {
120            $this->_eol = (strstr(PHP_OS, 'WIN')) ? "\r\n" : "\n";
121        }
122
123        register_shutdown_function(array(&$this, '_Log_file'));
124    }
125
126    /**
127     * Destructor
128     */
129    function _Log_file()
130    {
131        if ($this->_opened) {
132            $this->close();
133        }
134    }
135
136    /**
137     * Creates the given directory path.  If the parent directories don't
138     * already exist, they will be created, too.
139     *
140     * @param   string  $path       The full directory path to create.
141     * @param   integer $mode       The permissions mode with which the
142     *                              directories will be created.
143     *
144     * @return  True if the full path is successfully created or already
145     *          exists.
146     *
147     * @access  private
148     */
149    function _mkpath($path, $mode = 0700)
150    {
151        static $depth = 0;
152
153        /* Guard against potentially infinite recursion. */
154        if ($depth++ > 25) {
155            trigger_error("_mkpath(): Maximum recursion depth (25) exceeded",
156                          E_USER_WARNING);
157            return false;
158        }
159
160        /* We're only interested in the directory component of the path. */
161        $path = dirname($path);
162
163        /* If the directory already exists, return success immediately. */
164        if (is_dir($path)) {
165            $depth = 0;
166            return true;
167        }
168
169        /*
170         * In order to understand recursion, you must first understand
171         * recursion ...
172         */
173        if ($this->_mkpath($path, $mode) === false) {
174            return false;
175        }
176
177        return @mkdir($path, $mode);
178    }
179
180    /**
181     * Opens the log file for output.  If the specified log file does not
182     * already exist, it will be created.  By default, new log entries are
183     * appended to the end of the log file.
184     *
185     * This is implicitly called by log(), if necessary.
186     *
187     * @access public
188     */
189    function open()
190    {
191        if (!$this->_opened) {
192            /* If the log file's directory doesn't exist, create it. */
193            if (!is_dir(dirname($this->_filename))) {
194                $this->_mkpath($this->_filename);
195            }
196
197            /* Obtain a handle to the log file. */
198            $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w');
199
200            $this->_opened = ($this->_fp !== false);
201
202            /* Attempt to set the log file's mode. */
203            @chmod($this->_filename, $this->_mode);
204        }
205
206        return $this->_opened;
207    }
208
209    /**
210     * Closes the log file if it is open.
211     *
212     * @access public
213     */
214    function close()
215    {
216        /* If the log file is open, close it. */
217        if ($this->_opened && fclose($this->_fp)) {
218            $this->_opened = false;
219        }
220
221        return ($this->_opened === false);
222    }
223
224    /**
225     * Logs $message to the output window.  The message is also passed along
226     * to any Log_observer instances that are observing this Log.
227     *
228     * @param mixed  $message  String or object containing the message to log.
229     * @param string $priority The priority of the message.  Valid
230     *                  values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT,
231     *                  PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING,
232     *                  PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG.
233     *                  The default is PEAR_LOG_INFO.
234     * @return boolean  True on success or false on failure.
235     * @access public
236     */
237    function log($message, $priority = PEAR_LOG_INFO)
238    {
239        /* Abort early if the priority is above the maximum logging level. */
240        if (!$this->_isMasked($priority)) {
241            return false;
242        }
243
244        /* If the log file isn't already open, open it now. */
245        if (!$this->_opened && !$this->open()) {
246            return false;
247        }
248
249        /* Extract the string representation of the message. */
250        $message = $this->_extractMessage($message);
251
252        /* Build the string containing the complete log line. */
253        $line = sprintf($this->_lineFormat, strftime($this->_timeFormat),
254                $this->_ident, $this->priorityToString($priority),
255                $message) . $this->_eol;
256
257        /* Write the log line to the log file. */
258        $success = (fwrite($this->_fp, $line) !== false);
259
260        /* Notify observers about this log message. */
261        $this->_announce(array('priority' => $priority, 'message' => $message));
262
263        return $success;
264    }
265}
266
267?>