PageRenderTime 24ms CodeModel.GetById 2ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 0ms

/cubi/openbiz/bin/service/logService.php

http://openbiz-cubi.googlecode.com/
PHP | 439 lines | 272 code | 25 blank | 142 comment | 30 complexity | 2f791b4decfd607b57c0213398e84171 MD5 | raw file
  1<?php
  2/**
  3 * PHPOpenBiz Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 *
 10 * @package   openbiz.bin.service
 11 * @copyright Copyright (c) 2005-2011, Rocky Swen
 12 * @license   http://www.opensource.org/licenses/bsd-license.php
 13 * @link      http://www.phpopenbiz.org/
 14 * @version   $Id: logService.php 4042 2011-05-01 06:36:18Z rockys $
 15 */
 16
 17require_once 'Zend/Log.php';
 18require_once 'Zend/Log/Writer/Stream.php';
 19
 20/**
 21 * ioService class is the plug-in service of handling file import/export
 22 *
 23 * @package   openbiz.bin.service
 24 * @author    Rocky Swen
 25 * @copyright Copyright (c) 2003-2009, Rocky Swen
 26 * @access    public
 27 */
 28class logService extends MetaObject
 29{
 30    /**
 31     * Log Levels are the highest level of logging to record.
 32     * By default, will log all entries up to the selected level
 33     * If this is set to NULL, logging is disabled
 34
 35     * EMERG   = 0;  // Emergency: system is unusable
 36     * ALERT   = 1;  // Alert: action must be taken immediately
 37     * CRIT    = 2;  // Critical: critical conditions
 38     * ERR     = 3;  // Error: error conditions
 39     * WARN    = 4;  // Warning: warning conditions
 40     * NOTICE  = 5;  // Notice: normal but significant condition
 41     * INFO    = 6;  // Informational: informational messages
 42     * DEBUG   = 7;  // Debug: debug messages
 43     *
 44     * @var int
 45     */
 46    private $_level;
 47
 48    /**
 49     * Logging format options include CSV, XML and HTML
 50     *
 51     * @var string
 52     */
 53    private $_format;
 54    
 55    /**
 56     * Organize files by in different ways:
 57     * PROFILE - pased on a profile userID
 58     * LEVEL - Store log files groups by their level
 59     * DATE - write log entries into a different file for each day
 60     *
 61     * @var string
 62     */
 63    private $_org;
 64    /**
 65     * Holds the formatter for a log object.  This object dictates how a log file is logged.
 66     *
 67     * @var object
 68     */
 69    private $_formatter;
 70    /**
 71     * Holds the file extension set based on the preferred format
 72     *
 73     * @var string
 74     */
 75    private $_extension = '.csv';
 76
 77    private $_daystolive;
 78    /**
 79     * Initialize logService with xml array metadata
 80     *
 81     * @param array $xmlArr
 82     * @return void
 83     */
 84    public function __construct(&$xmlArr)
 85    {
 86        $this->readMetadata($xmlArr);
 87        //Check that logging is enabled
 88        if (is_int($this->_level) == FALSE)
 89            return;
 90        $this->setFormatter();
 91        $this->setExtension();
 92    }
 93
 94    /**
 95     * Read array meta data, and store to meta object
 96     *
 97     * @param array $xmlArr
 98     * @return void
 99     */
100    protected function readMetadata(&$xmlArr)
101    {
102        parent::readMetaData($xmlArr);
103        $level = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["LEVEL"]);
104        $this->_level = (int) $level;
105        $this->_format = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["FORMAT"]);
106        $this->_org = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["ORG"]);
107        $this->_daystolive = $xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["DAYSTOLIVE"]?strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["DAYSTOLIVE"]):'0';
108    }
109
110    /**
111     * The primary log function that will take an incoming message and specified paramter and log in the
112     * appropriate location and format
113     *
114     * @param int $level - Follow common BSD error levels
115     * @param string $package - A way to group log messages
116     * @param string $message - The actual message to log
117     * @return boolean -TRUE on success otherwise FALSE
118     */
119    public function log($priority, $package, $message)
120    {
121        if (DEBUG == 0 && $priority == LOG_DEBUG)
122        	return true;
123    	//Adapt PHP LOG priority
124        switch ($priority)
125        {
126            case LOG_EMERG : // 	system is unusable
127            case LOG_ALERT :	// action must be taken immediately
128            case LOG_CRIT :	// critical conditions
129                $level = 2;
130                break;
131            case LOG_ERR :	// error conditions
132                $level = 3;
133                break;
134            case LOG_WARNING : // warning conditions
135                $level = 4;
136                break;
137            case LOG_NOTICE : //	normal, but significant, condition
138            case LOG_INFO :	// informational message
139            case LOG_DEBUG :	// debug-level message
140                $level = 7;
141                break;
142        }
143        //echo "log levels: ".LOG_EMERG.", ".LOG_ALERT.", ".LOG_CRIT.", ".LOG_ERR.", ".LOG_WARNING.", ".LOG_NOTICE.", ".LOG_INFO.", ".LOG_DEBUG."<br>";
144
145        if ($this->_level == FALSE)
146            return true;
147        //Get the file path
148        $this->_level = $level;
149        $path = $this->_getPath($file_name);
150        if(!is_file($path))
151        {
152        	@touch($path);
153        	@chmod($path,0777);
154        }
155        if (!is_writable($path))
156            return false;        
157        $this->prepFile($path);
158        //Create the log writer object
159        $writer = new Zend_Log_Writer_Stream($path);
160        $writer->setFormatter($this->_formatter);
161        //Instantiate logging object
162        $logger = new Zend_Log($writer);
163        //Filter log entries to those allowed by configuration
164        $filter = new Zend_Log_Filter_Priority($this->_level);
165        $logger->addFilter($filter);
166
167        $logger->setEventItem('back_trace', 'n/a');
168        $logger->setEventItem('package', $package);
169        $logger->setEventItem('date', date("m/d/Y"));
170        $logger->setEventItem('time', date("H:i:s"));
171
172        //Write Log Entry
173        $logger->log($message, $level);
174        $this->closeFile($path);
175        return TRUE;
176    }
177
178    /**
179     * The primary log function that will take an incoming message and specified paramter and log in the
180     * appropriate location and format
181     *
182     * @param int $level - Follow common BSD error levels
183     * @param string $package - A way to group log messages
184     * @param string $message - The actual message to log
185     * @param string $fileName - An optional specific file name where the message should be logged
186     * @param string $string - An optional list of the Application stack at the time of error
187     * @return boolean -TRUE on success otherwise FALSE
188     */
189    public function logError($level = 7, $package, $message, $fileName = NULL, $backTrace = '')
190    {
191        //Adapt PHP Errors
192        switch ($level)
193        {
194            case 8:          // E_NOTICE
195            case 1024:       // E_USER_NOTICE
196                $level = 4;
197                break;
198
199            case 2048:       //E_STRICT
200            case 8192:       //E_DEPRICIATED
201            case 16384:      //E_DEPRICIATED
202                $level = 5;
203                break;
204
205            case 2:          //E_WARNING
206            case 512:        //E_USER_WARNING
207                $level = 3;
208                break;
209
210            case 256:
211                $level = 2;
212                break;
213            
214            default:
215                $level = 2;
216        }
217
218        if ($this->_level == FALSE)
219            return true;
220        //Get the file path
221        $this->_level = $level;
222        $path = $this->_getPath($fileName);
223        if (!is_writable($path))
224            return false;
225        $this->prepFile($path);
226
227        //Create the log writer object
228        $writer = new Zend_Log_Writer_Stream($path);
229        $writer->setFormatter($this->_formatter);
230
231        //Instantiate logging object
232        $logger = new Zend_Log($writer);
233
234        //Filter log entries to those allowed by configuration
235        $filter = new Zend_Log_Filter_Priority($this->_level);
236        $logger->addFilter($filter);
237        //Set additional information about the class and function that called the log
238
239
240        // Add custom elements to default log package
241        $logger->setEventItem('back_trace', $backTrace);
242        $logger->setEventItem('package', $package);
243        $logger->setEventItem('date', date("m/d/Y"));
244        $logger->setEventItem('time', date("H:i:s"));
245        //Write Log Entry
246        $logger->log($message, $level);
247        $this->closeFile($path);
248        return TRUE;
249    }
250
251    /**
252     * Set the formatter based on the type of format selected in app.inc
253     *
254     * @return void
255     */
256    public function setFormatter()
257    {
258        switch ($this->_format)
259        {
260            case 'HTML':
261            //HTML Format
262                $this->_formatter = new Zend_Log_Formatter_Simple('<tr><td>%date%</td> <td>%time%</td> <td>%priorityName%</td> <td>%package%</td> <td>%message%</td> <td>%back_trace%</td> </tr>' . PHP_EOL);
263                break;
264            case 'XML':
265            //XML Format
266                require_once 'Zend/Log/Formatter/Xml.php';
267                $this->_formatter = new Zend_Log_Formatter_Xml();
268                break;
269            case 'CSV':
270            default:
271            //CSV Format
272                $this->_formatter = new Zend_Log_Formatter_Simple("'%date%','%time%','%priorityName%','%package%','%message%','%back_trace%'" . PHP_EOL);
273                break;
274        }
275    }
276    /**
277     * Set the extension based on the type of format selected in app.inc
278     *
279     * @return void
280     */
281    public function setExtension()
282    {
283        switch ($this->_format)
284        {
285            case 'HTML':
286                $this->_extension = '.html';
287                break;
288            case 'XML':
289                $this->_extension = '.xml';
290                break;
291            case 'CSV':
292            default:
293                $this->_extension = '.log';
294                break;
295        }
296    }
297    /**
298     * Either open a new file with the correct string or remove a previous closing string
299     *
300     * @return void
301     */
302    public function prepFile($path)
303    {
304        //Check for existing file and HTML format
305        if (file_exists($path) and $this->_format == 'HTML')
306        {
307            $file = file($path);
308            array_pop($file);
309            file_put_contents($path, $file);
310        } elseif ($this->_format == 'HTML')
311        {
312            $html = '<html><head></head><body><table border="1">' . PHP_EOL;
313            $file = fopen($path, 'a');
314            fwrite($file, $html);
315            fclose($file);
316        } elseif (file_exists($path) and $this->_format == 'XML')
317        {
318            $file = file($path);
319            array_pop($file);
320            file_put_contents($path, $file);
321        } elseif ($this->_format == 'XML')
322        {
323            $xml = '<?xml version="1.0" standalone="no"?><log>' . PHP_EOL;
324            $file = fopen($path, 'a');
325            fwrite($file, $xml);
326            fclose($file);
327        }
328    }
329
330    /**
331     * Close a file with the correct string depending on the configured format
332     *
333     * @return void
334     */
335    public function closeFile($path)
336    {
337        //Close up the file if needed
338        switch ($this->_format)
339        {
340            case 'HTML':
341                $html = "</table></body></html>";
342                $file = fopen($path, 'a');
343                fwrite($file, $html);
344                fclose($file);
345                break;
346            case 'XML':
347                $xml = "</log>";
348                $file = fopen($path, 'a');
349                fwrite($file, $xml);
350                fclose($file);
351                break;
352            default:
353                break;
354        }
355    }
356
357    /**
358     * Get path based on config options
359     *
360     * @global BizSystem $g_BizSystem
361     * @param string $fileName
362     * @return string log_path - The path where a log entry should be written
363     */
364    private function _getPath($fileName = null)
365    {
366        $level = $this->_level;
367        if ($fileName)
368            return LOG_PATH . '/' . $fileName . $this->_extension;
369        switch ($this->_org)
370        {
371            case 'DATE':
372                return LOG_PATH . '/' . date("Y_m_d") . $this->_extension;
373                break;
374            case 'LEVEL':
375                $level = $this->_level2filename($level);                
376                return LOG_PATH . '/' . $level . $this->_extension;
377                break;
378            case 'LEVEL-DATE':
379                $level = $this->_level2filename($level);
380                //delete old log files                
381                if($this->_daystolive>0){
382	                if(is_array(glob(LOG_PATH . '/' . $level .'-*' .  $this->_extension))){
383		                foreach (glob(LOG_PATH . '/' . $level .'-*' .  $this->_extension) as $filename) {
384						    $mtime = filemtime($filename);
385						    if((time() - $mtime) >= $this->_daystolive*86400 ){
386						    	@unlink($filename);
387						    }
388						}
389                	}
390                }
391                return LOG_PATH . '/' . $level .'-'. date("Y_m_d") .  $this->_extension;
392                break;
393            case 'PROFILE':
394                $profile = BizSystem::getUserProfile('USERID');
395                if (! $profile)
396                    $profile = 'Guest';
397                return LOG_PATH . '/' . $profile . $this->_extension;
398                break;
399            default:
400                ;
401                break;
402        }
403    }
404    
405    private function _level2filename($level)
406    {
407   				switch ($this->_level)
408                {
409                    case 0:
410                        $level = 'EMERG';
411                        break;
412                    case 1:
413                        $level = 'ALERT';
414                        break;
415                    case 2:
416                        $level = 'CRIT';
417                        break;
418                    case 3:
419                        $level = 'ERR';
420                        break;
421                    case 4:
422                        $level = 'WARN';
423                        break;
424                    case 5:
425                        $level = 'NOTICE';
426                        break;
427                    case 6:
428                        $level = 'INFO';
429                        break;
430                    case 7:
431                        $level = 'DEBUG';
432                        break;
433                    default:
434                        ;
435                        break;
436                }    
437                return $level;
438    }
439}